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 def __init__(self):\n self.all = []\n\n def ping(self, t: int) -> int:\n self.all.append(t)\n min_time = t-3000\n while self.all[0] < min_time:\n self.all.pop(0)\n return len(self.all) \n\n# Your RecentCounter object will be instantiated and called as such:\n# obj = RecentCounter()\n# param_1 = obj.ping(t)\n``` | 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 flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`.
Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.
**Example 1:**
**Input:** arr = \[3,2,4,1\]
**Output:** \[4,2,4,3\]
**Explanation:**
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = \[3, 2, 4, 1\]
After 1st flip (k = 4): arr = \[1, 4, 2, 3\]
After 2nd flip (k = 2): arr = \[4, 1, 2, 3\]
After 3rd flip (k = 4): arr = \[3, 2, 1, 4\]
After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted.
**Example 2:**
**Input:** arr = \[1,2,3\]
**Output:** \[\]
**Explanation:** The input is already sorted, so there is no need to flip anything.
Note that other answers, such as \[3, 3\], would also be accepted.
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= arr.length`
* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`). | 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)$$ -->\n\n# Code\n```\nclass RecentCounter:\n\n def __init__(self):\n self.li=set()\n def ping(self, t: int) -> int:\n self.li.add(t)\n c=set(range(t-3000,t+1))\n return len(self.li&c)\n \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, and returns the number of requests that has happened in the past `3000` milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range `[t - 3000, t]`.
It is **guaranteed** that every call to `ping` uses a strictly larger value of `t` than the previous call.
**Example 1:**
**Input**
\[ "RecentCounter ", "ping ", "ping ", "ping ", "ping "\]
\[\[\], \[1\], \[100\], \[3001\], \[3002\]\]
**Output**
\[null, 1, 2, 3, 3\]
**Explanation**
RecentCounter recentCounter = new RecentCounter();
recentCounter.ping(1); // requests = \[1\], range is \[-2999,1\], return 1
recentCounter.ping(100); // requests = \[1, 100\], range is \[-2900,100\], return 2
recentCounter.ping(3001); // requests = \[1, 100, 3001\], range is \[1,3001\], return 3
recentCounter.ping(3002); // requests = \[1, 100, 3001, 3002\], range is \[2,3002\], return 3
**Constraints:**
* `1 <= t <= 109`
* Each test case will call `ping` with **strictly increasing** values of `t`.
* At most `104` calls will be made to `ping`. | 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)$$ -->\n\n# Code\n```\nclass RecentCounter:\n\n def __init__(self):\n self.li=set()\n def ping(self, t: int) -> int:\n self.li.add(t)\n c=set(range(t-3000,t+1))\n return len(self.li&c)\n \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 flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`.
Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.
**Example 1:**
**Input:** arr = \[3,2,4,1\]
**Output:** \[4,2,4,3\]
**Explanation:**
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = \[3, 2, 4, 1\]
After 1st flip (k = 4): arr = \[1, 4, 2, 3\]
After 2nd flip (k = 2): arr = \[4, 1, 2, 3\]
After 3rd flip (k = 4): arr = \[3, 2, 1, 4\]
After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted.
**Example 2:**
**Input:** arr = \[1,2,3\]
**Output:** \[\]
**Explanation:** The input is already sorted, so there is no need to flip anything.
Note that other answers, such as \[3, 3\], would also be accepted.
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= arr.length`
* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`). | 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. $$O(n)$$ -->\n\n# Code\n```\nclass RecentCounter:\n def __init__(self):\n self.queue = collections.deque()\n\n def ping(self, t: int) -> int:\n while self.queue and t - self.queue[0] > 3000:\n self.queue.popleft()\n self.queue.append(t)\n \n return len(self.queue)\n\n\n# Your RecentCounter object will be instantiated and called as such:\n# obj = RecentCounter()\n# param_1 = obj.ping(t)\n``` | 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, and returns the number of requests that has happened in the past `3000` milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range `[t - 3000, t]`.
It is **guaranteed** that every call to `ping` uses a strictly larger value of `t` than the previous call.
**Example 1:**
**Input**
\[ "RecentCounter ", "ping ", "ping ", "ping ", "ping "\]
\[\[\], \[1\], \[100\], \[3001\], \[3002\]\]
**Output**
\[null, 1, 2, 3, 3\]
**Explanation**
RecentCounter recentCounter = new RecentCounter();
recentCounter.ping(1); // requests = \[1\], range is \[-2999,1\], return 1
recentCounter.ping(100); // requests = \[1, 100\], range is \[-2900,100\], return 2
recentCounter.ping(3001); // requests = \[1, 100, 3001\], range is \[1,3001\], return 3
recentCounter.ping(3002); // requests = \[1, 100, 3001, 3002\], range is \[2,3002\], return 3
**Constraints:**
* `1 <= t <= 109`
* Each test case will call `ping` with **strictly increasing** values of `t`.
* At most `104` calls will be made to `ping`. | 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. $$O(n)$$ -->\n\n# Code\n```\nclass RecentCounter:\n def __init__(self):\n self.queue = collections.deque()\n\n def ping(self, t: int) -> int:\n while self.queue and t - self.queue[0] > 3000:\n self.queue.popleft()\n self.queue.append(t)\n \n return len(self.queue)\n\n\n# Your RecentCounter object will be instantiated and called as such:\n# obj = RecentCounter()\n# param_1 = obj.ping(t)\n``` | 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 flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`.
Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.
**Example 1:**
**Input:** arr = \[3,2,4,1\]
**Output:** \[4,2,4,3\]
**Explanation:**
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = \[3, 2, 4, 1\]
After 1st flip (k = 4): arr = \[1, 4, 2, 3\]
After 2nd flip (k = 2): arr = \[4, 1, 2, 3\]
After 3rd flip (k = 4): arr = \[3, 2, 1, 4\]
After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted.
**Example 2:**
**Input:** arr = \[1,2,3\]
**Output:** \[\]
**Explanation:** The input is already sorted, so there is no need to flip anything.
Note that other answers, such as \[3, 3\], would also be accepted.
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= arr.length`
* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`). | 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(queue)\n```\n\nC++\n```\n//USING DEQUE\nclass RecentCounter {\npublic:\n deque<int> dq;\n RecentCounter() {\n return ;\n }\n \n int ping(int t) {\n dq.push_back(t);\n while(!dq.empty() && dq.front()<t-3000)\n dq.pop_front();\n return dq.size();\n }\n};\n```\n\n\nBINARY SEARCH APPROACH IN PYTHON\n```\n# USING BINARY SEARCH\nclass RecentCounter:\n def __init__(self):\n self.arr = []\n\n def ping(self, t: int) -> int:\n self.arr.append(t)\n start = t - 3000\n if(t<=0):\n return len(self.arr)\n # find t which is >= start in arr\n def binSearch(start,arr):\n i = 0\n j = len(arr)\n while(i<=j):\n mid = (i+j)//2\n if(arr[mid] > start):\n j = mid - 1\n elif(arr[mid] < start):\n i = mid + 1\n else:\n return mid\n return i\n \n indx = binSearch(start,self.arr)\n return len(self.arr) - indx\n``` | 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, and returns the number of requests that has happened in the past `3000` milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range `[t - 3000, t]`.
It is **guaranteed** that every call to `ping` uses a strictly larger value of `t` than the previous call.
**Example 1:**
**Input**
\[ "RecentCounter ", "ping ", "ping ", "ping ", "ping "\]
\[\[\], \[1\], \[100\], \[3001\], \[3002\]\]
**Output**
\[null, 1, 2, 3, 3\]
**Explanation**
RecentCounter recentCounter = new RecentCounter();
recentCounter.ping(1); // requests = \[1\], range is \[-2999,1\], return 1
recentCounter.ping(100); // requests = \[1, 100\], range is \[-2900,100\], return 2
recentCounter.ping(3001); // requests = \[1, 100, 3001\], range is \[1,3001\], return 3
recentCounter.ping(3002); // requests = \[1, 100, 3001, 3002\], range is \[2,3002\], return 3
**Constraints:**
* `1 <= t <= 109`
* Each test case will call `ping` with **strictly increasing** values of `t`.
* At most `104` calls will be made to `ping`. | 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(queue)\n```\n\nC++\n```\n//USING DEQUE\nclass RecentCounter {\npublic:\n deque<int> dq;\n RecentCounter() {\n return ;\n }\n \n int ping(int t) {\n dq.push_back(t);\n while(!dq.empty() && dq.front()<t-3000)\n dq.pop_front();\n return dq.size();\n }\n};\n```\n\n\nBINARY SEARCH APPROACH IN PYTHON\n```\n# USING BINARY SEARCH\nclass RecentCounter:\n def __init__(self):\n self.arr = []\n\n def ping(self, t: int) -> int:\n self.arr.append(t)\n start = t - 3000\n if(t<=0):\n return len(self.arr)\n # find t which is >= start in arr\n def binSearch(start,arr):\n i = 0\n j = len(arr)\n while(i<=j):\n mid = (i+j)//2\n if(arr[mid] > start):\n j = mid - 1\n elif(arr[mid] < start):\n i = mid + 1\n else:\n return mid\n return i\n \n indx = binSearch(start,self.arr)\n return len(self.arr) - indx\n``` | 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 flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`.
Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.
**Example 1:**
**Input:** arr = \[3,2,4,1\]
**Output:** \[4,2,4,3\]
**Explanation:**
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = \[3, 2, 4, 1\]
After 1st flip (k = 4): arr = \[1, 4, 2, 3\]
After 2nd flip (k = 2): arr = \[4, 1, 2, 3\]
After 3rd flip (k = 4): arr = \[3, 2, 1, 4\]
After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted.
**Example 2:**
**Input:** arr = \[1,2,3\]
**Output:** \[\]
**Explanation:** The input is already sorted, so there is no need to flip anything.
Note that other answers, such as \[3, 3\], would also be accepted.
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= arr.length`
* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`). | 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, and returns the number of requests that has happened in the past `3000` milliseconds (including the new request). Specifically, return the number of requests that have happened in the inclusive range `[t - 3000, t]`.
It is **guaranteed** that every call to `ping` uses a strictly larger value of `t` than the previous call.
**Example 1:**
**Input**
\[ "RecentCounter ", "ping ", "ping ", "ping ", "ping "\]
\[\[\], \[1\], \[100\], \[3001\], \[3002\]\]
**Output**
\[null, 1, 2, 3, 3\]
**Explanation**
RecentCounter recentCounter = new RecentCounter();
recentCounter.ping(1); // requests = \[1\], range is \[-2999,1\], return 1
recentCounter.ping(100); // requests = \[1, 100\], range is \[-2900,100\], return 2
recentCounter.ping(3001); // requests = \[1, 100, 3001\], range is \[1,3001\], return 3
recentCounter.ping(3002); // requests = \[1, 100, 3001, 3002\], range is \[2,3002\], return 3
**Constraints:**
* `1 <= t <= 109`
* Each test case will call `ping` with **strictly increasing** values of `t`.
* At most `104` calls will be made to `ping`. | 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 flip choosing `k = 3`, we reverse the sub-array `[3,2,1]`, so `arr = [1,2,3,4]` after the pancake flip at `k = 3`.
Return _an array of the_ `k`_\-values corresponding to a sequence of pancake flips that sort_ `arr`. Any valid answer that sorts the array within `10 * arr.length` flips will be judged as correct.
**Example 1:**
**Input:** arr = \[3,2,4,1\]
**Output:** \[4,2,4,3\]
**Explanation:**
We perform 4 pancake flips, with k values 4, 2, 4, and 3.
Starting state: arr = \[3, 2, 4, 1\]
After 1st flip (k = 4): arr = \[1, 4, 2, 3\]
After 2nd flip (k = 2): arr = \[4, 1, 2, 3\]
After 3rd flip (k = 4): arr = \[3, 2, 1, 4\]
After 4th flip (k = 3): arr = \[1, 2, 3, 4\], which is sorted.
**Example 2:**
**Input:** arr = \[1,2,3\]
**Output:** \[\]
**Explanation:** The input is already sorted, so there is no need to flip anything.
Note that other answers, such as \[3, 3\], would also be accepted.
**Constraints:**
* `1 <= arr.length <= 100`
* `1 <= arr[i] <= arr.length`
* All integers in `arr` are unique (i.e. `arr` is a permutation of the integers from `1` to `arr.length`). | 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, row in enumerate(grid):\n for in_y, val in enumerate(row):\n if val:\n return (in_x, in_y)\n \n # start from one point and get all position of a land\n in_x, in_y = one_land(grid)\n queue = [(in_x, in_y)]\n first_land = [(in_x, in_y)] # temp queue to find the first land\n \n from collections import defaultdict\n visited = defaultdict(lambda:False, {})\n visited[(in_x, in_y)] = True \n \n # find positions of the first land\n while first_land:\n x, y = first_land.pop(0)\n for dir_x, dir_y in directions:\n nei_x = x + dir_x\n nei_y = y + dir_y\n if nei_x in range(n) and nei_y in range(m): # point in range\n if grid[nei_x][nei_y]: # it is land\n if not visited[(nei_x, nei_y)]:\n first_land.append((nei_x, nei_y))\n queue.append((nei_x, nei_y))\n visited[(nei_x, nei_y)] = True\n \n \n \n # BFS\n cost = 0\n layer_size = 0\n while queue:\n layer_size = len(queue)\n for i in range(layer_size):\n x, y = queue.pop(0)\n for dir_x, dir_y in directions:\n nei_x = x + dir_x\n nei_y = y + dir_y\n if nei_x in range(n) and nei_y in range(m): # point in range\n if not visited[(nei_x, nei_y)]:\n if grid[nei_x][nei_y]: # it is land (second land)\n return cost\n else: # it is water\n queue.append((nei_x, nei_y))\n visited[(nei_x, nei_y)] = True\n cost += 1\n return None \n``` | 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**.
Return _the smallest number of_ `0`_'s you must flip to connect the two islands_.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 1
**Example 2:**
**Input:** grid = \[\[0,1,0\],\[0,0,0\],\[0,0,1\]\]
**Output:** 2
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1\],\[1,0,0,0,1\],\[1,0,1,0,1\],\[1,0,0,0,1\],\[1,1,1,1,1\]\]
**Output:** 1
**Constraints:**
* `n == grid.length == grid[i].length`
* `2 <= n <= 100`
* `grid[i][j]` is either `0` or `1`.
* There are exactly two islands in `grid`. | 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, row in enumerate(grid):\n for in_y, val in enumerate(row):\n if val:\n return (in_x, in_y)\n \n # start from one point and get all position of a land\n in_x, in_y = one_land(grid)\n queue = [(in_x, in_y)]\n first_land = [(in_x, in_y)] # temp queue to find the first land\n \n from collections import defaultdict\n visited = defaultdict(lambda:False, {})\n visited[(in_x, in_y)] = True \n \n # find positions of the first land\n while first_land:\n x, y = first_land.pop(0)\n for dir_x, dir_y in directions:\n nei_x = x + dir_x\n nei_y = y + dir_y\n if nei_x in range(n) and nei_y in range(m): # point in range\n if grid[nei_x][nei_y]: # it is land\n if not visited[(nei_x, nei_y)]:\n first_land.append((nei_x, nei_y))\n queue.append((nei_x, nei_y))\n visited[(nei_x, nei_y)] = True\n \n \n \n # BFS\n cost = 0\n layer_size = 0\n while queue:\n layer_size = len(queue)\n for i in range(layer_size):\n x, y = queue.pop(0)\n for dir_x, dir_y in directions:\n nei_x = x + dir_x\n nei_y = y + dir_y\n if nei_x in range(n) and nei_y in range(m): # point in range\n if not visited[(nei_x, nei_y)]:\n if grid[nei_x][nei_y]: # it is land (second land)\n return cost\n else: # it is water\n queue.append((nei_x, nei_y))\n visited[(nei_x, nei_y)] = True\n cost += 1\n return None \n``` | 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 binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect:
Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`.
Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`.
**Example 1:**
**Input:** root = \[1,2\], voyage = \[2,1\]
**Output:** \[-1\]
**Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage.
**Example 2:**
**Input:** root = \[1,2,3\], voyage = \[1,3,2\]
**Output:** \[1\]
**Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.
**Example 3:**
**Input:** root = \[1,2,3\], voyage = \[1,2,3\]
**Output:** \[\]
**Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.
**Constraints:**
* The number of nodes in the tree is `n`.
* `n == voyage.length`
* `1 <= n <= 100`
* `1 <= Node.val, voyage[i] <= n`
* All the values in the tree are **unique**.
* All the values in `voyage` are **unique**. | 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\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 of BFS.\n\nBecause **BFS visits all nodes in the nature of level by level**, this leads to the shortest path in graph.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. From top-left corner, find and locate first LAND cell as source.\n\n2. Launch 1st pass BFS, from source to explore entire island 1, and save island 1\'s boundary cells.\n\n3. Launch 2nd pass BFS, from island 1\'s boundary cells towards WATER and another island.\n\n4. Update step count as distnace during BFS.\n\n5. Once we see LAND cells in our neighbor, which means we find a shortest path from island 1 to island 2.\n\n6. The step count is the shortest path of bridge, also the shortest distance between island 1 and island 2.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(h*w), use BFS to visit entire graph at most.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(h*w), use BFS to explore from one island to another island.\nThe space cost is the size of queue in BFS.\n\n# Code\n```\nclass Solution:\n def shortestBridge(self, A: List[List[int]]) -> int:\n \n # State: cell of considered, water cell, land cell\n SEEN, WATER, LAND = -1, 0, 1\n\n # Board size\n h, w = len(A), len(A[0])\n\n # First land cell in world map A\n y, x = next( (y,x) for y in range(h) for x in range(w) if A[y][x] == LAND )\n\n # helper function to check valid grid points\n def in_board(y, x):\n return (0 <= x < w) and (0 <= y < h)\n\n # helper function to generate 4-connected nieghbor\n def neighbor(y, x):\n offset = [1,0,-1,0,1]\n for i in range(4):\n ny, nx = y+offset[i], x+offset[i+1]\n if in_board(ny, nx):\n yield ny, nx\n \n # storage of boundary cell of island 1 \n # boundary means the out-most LAND cell, connected by WATER cell\n boundary = set()\n\n # Visit all LAND cell of island 1\n # Find and save island 1\'s boundary\n def bfs_island1( src_y, src_x):\n \n queue = [(src_y, src_x)]\n while queue:\n\n next_queue = []\n\n for y, x in queue:\n\n A[y][x] = SEEN\n \n for ny, nx in neighbor(y, x):\n if A[ny][nx] != SEEN:\n \n if A[ny][nx] == LAND: \n A[ny][nx] = SEEN\n next_queue.append( (ny, nx) )\n else:\n boundary.add( (y, x) )\n\n queue = next_queue\n\n return\n\n # Explore from island 1\'s boundary in BFS\n # When we touch the LAND of island 2, the step is the shortest distance of bridge\n def bfs_distance( boundary ):\n \n queue = [*boundary]\n step = 0\n while queue:\n\n next_queue = []\n\n for y, x in queue:\n \n A[y][x] = SEEN\n \n for ny, nx in neighbor(y, x):\n if A[ny][nx] != SEEN:\n\n if A[ny][nx] == LAND: \n return step\n\n else:\n A[ny][nx] = SEEN\n next_queue.append( (ny, nx) )\n\n step += 1\n queue = next_queue\n\n return -1\n # ----------------------------\n\n # Visit island 1, and save island 1\'s boundary.\n bfs_island1( y, x)\n\n # Explore from island 1\'s boundary in BFS\n # When we touch the LAND of island 2, the step is the shortest distance of bridge\n return bfs_distance( boundary )\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**.
Return _the smallest number of_ `0`_'s you must flip to connect the two islands_.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 1
**Example 2:**
**Input:** grid = \[\[0,1,0\],\[0,0,0\],\[0,0,1\]\]
**Output:** 2
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1\],\[1,0,0,0,1\],\[1,0,1,0,1\],\[1,0,0,0,1\],\[1,1,1,1,1\]\]
**Output:** 1
**Constraints:**
* `n == grid.length == grid[i].length`
* `2 <= n <= 100`
* `grid[i][j]` is either `0` or `1`.
* There are exactly two islands in `grid`. | 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\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 of BFS.\n\nBecause **BFS visits all nodes in the nature of level by level**, this leads to the shortest path in graph.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. From top-left corner, find and locate first LAND cell as source.\n\n2. Launch 1st pass BFS, from source to explore entire island 1, and save island 1\'s boundary cells.\n\n3. Launch 2nd pass BFS, from island 1\'s boundary cells towards WATER and another island.\n\n4. Update step count as distnace during BFS.\n\n5. Once we see LAND cells in our neighbor, which means we find a shortest path from island 1 to island 2.\n\n6. The step count is the shortest path of bridge, also the shortest distance between island 1 and island 2.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(h*w), use BFS to visit entire graph at most.\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(h*w), use BFS to explore from one island to another island.\nThe space cost is the size of queue in BFS.\n\n# Code\n```\nclass Solution:\n def shortestBridge(self, A: List[List[int]]) -> int:\n \n # State: cell of considered, water cell, land cell\n SEEN, WATER, LAND = -1, 0, 1\n\n # Board size\n h, w = len(A), len(A[0])\n\n # First land cell in world map A\n y, x = next( (y,x) for y in range(h) for x in range(w) if A[y][x] == LAND )\n\n # helper function to check valid grid points\n def in_board(y, x):\n return (0 <= x < w) and (0 <= y < h)\n\n # helper function to generate 4-connected nieghbor\n def neighbor(y, x):\n offset = [1,0,-1,0,1]\n for i in range(4):\n ny, nx = y+offset[i], x+offset[i+1]\n if in_board(ny, nx):\n yield ny, nx\n \n # storage of boundary cell of island 1 \n # boundary means the out-most LAND cell, connected by WATER cell\n boundary = set()\n\n # Visit all LAND cell of island 1\n # Find and save island 1\'s boundary\n def bfs_island1( src_y, src_x):\n \n queue = [(src_y, src_x)]\n while queue:\n\n next_queue = []\n\n for y, x in queue:\n\n A[y][x] = SEEN\n \n for ny, nx in neighbor(y, x):\n if A[ny][nx] != SEEN:\n \n if A[ny][nx] == LAND: \n A[ny][nx] = SEEN\n next_queue.append( (ny, nx) )\n else:\n boundary.add( (y, x) )\n\n queue = next_queue\n\n return\n\n # Explore from island 1\'s boundary in BFS\n # When we touch the LAND of island 2, the step is the shortest distance of bridge\n def bfs_distance( boundary ):\n \n queue = [*boundary]\n step = 0\n while queue:\n\n next_queue = []\n\n for y, x in queue:\n \n A[y][x] = SEEN\n \n for ny, nx in neighbor(y, x):\n if A[ny][nx] != SEEN:\n\n if A[ny][nx] == LAND: \n return step\n\n else:\n A[ny][nx] = SEEN\n next_queue.append( (ny, nx) )\n\n step += 1\n queue = next_queue\n\n return -1\n # ----------------------------\n\n # Visit island 1, and save island 1\'s boundary.\n bfs_island1( y, x)\n\n # Explore from island 1\'s boundary in BFS\n # When we touch the LAND of island 2, the step is the shortest distance of bridge\n return bfs_distance( boundary )\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 binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect:
Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`.
Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`.
**Example 1:**
**Input:** root = \[1,2\], voyage = \[2,1\]
**Output:** \[-1\]
**Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage.
**Example 2:**
**Input:** root = \[1,2,3\], voyage = \[1,3,2\]
**Output:** \[1\]
**Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.
**Example 3:**
**Input:** root = \[1,2,3\], voyage = \[1,2,3\]
**Output:** \[\]
**Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.
**Constraints:**
* The number of nodes in the tree is `n`.
* `n == voyage.length`
* `1 <= n <= 100`
* `1 <= Node.val, voyage[i] <= n`
* All the values in the tree are **unique**.
* All the values in `voyage` are **unique**. | 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 # Find a piece of an island\n start = None\n for i in range(N):\n for j in range(N):\n if grid[i][j] == 1:\n start = (i, j)\n break\n if start:\n break\n\n # BFS to find perimeter around one island\n q = deque([start])\n seen = set()\n water = set()\n while q:\n i, j = q.popleft()\n if (i, j) in seen:\n continue\n seen.add((i, j))\n for ni, nj in get_neighbors(i, j):\n if grid[ni][nj] == 0:\n water.add((ni, nj))\n else:\n q.append((ni, nj))\n\n # BFS from the perimeter out, until the other island is reached\n q = deque(water)\n res = 0\n while q:\n for _ in range(len(q)):\n i, j = q.popleft()\n if grid[i][j] == 1:\n return res\n for ni, nj in get_neighbors(i, j):\n if (ni, nj) in seen:\n continue\n seen.add((ni, nj))\n q.append((ni, nj))\n res += 1\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**.
Return _the smallest number of_ `0`_'s you must flip to connect the two islands_.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 1
**Example 2:**
**Input:** grid = \[\[0,1,0\],\[0,0,0\],\[0,0,1\]\]
**Output:** 2
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1\],\[1,0,0,0,1\],\[1,0,1,0,1\],\[1,0,0,0,1\],\[1,1,1,1,1\]\]
**Output:** 1
**Constraints:**
* `n == grid.length == grid[i].length`
* `2 <= n <= 100`
* `grid[i][j]` is either `0` or `1`.
* There are exactly two islands in `grid`. | 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 # Find a piece of an island\n start = None\n for i in range(N):\n for j in range(N):\n if grid[i][j] == 1:\n start = (i, j)\n break\n if start:\n break\n\n # BFS to find perimeter around one island\n q = deque([start])\n seen = set()\n water = set()\n while q:\n i, j = q.popleft()\n if (i, j) in seen:\n continue\n seen.add((i, j))\n for ni, nj in get_neighbors(i, j):\n if grid[ni][nj] == 0:\n water.add((ni, nj))\n else:\n q.append((ni, nj))\n\n # BFS from the perimeter out, until the other island is reached\n q = deque(water)\n res = 0\n while q:\n for _ in range(len(q)):\n i, j = q.popleft()\n if grid[i][j] == 1:\n return res\n for ni, nj in get_neighbors(i, j):\n if (ni, nj) in seen:\n continue\n seen.add((ni, nj))\n q.append((ni, nj))\n res += 1\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 binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect:
Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`.
Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`.
**Example 1:**
**Input:** root = \[1,2\], voyage = \[2,1\]
**Output:** \[-1\]
**Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage.
**Example 2:**
**Input:** root = \[1,2,3\], voyage = \[1,3,2\]
**Output:** \[1\]
**Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.
**Example 3:**
**Input:** root = \[1,2,3\], voyage = \[1,2,3\]
**Output:** \[\]
**Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.
**Constraints:**
* The number of nodes in the tree is `n`.
* `n == voyage.length`
* `1 <= n <= 100`
* `1 <= Node.val, voyage[i] <= n`
* All the values in the tree are **unique**.
* All the values in `voyage` are **unique**. | 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,grid,n);\n dfs(r,c+1,q,grid,n);\n}\n int shortestBridge(vector<vector<int>>& grid) {\n queue<pair<int,int>>q;\n int ans=0;\n int n=grid.size();\n bool ok=true;\n for(int i=0;i<n;i++){\n if(ok){\n for(int j=0;j<n;j++){\n if(grid[i][j]==1){\n dfs(i,j,q,grid,n);\n ok =false;\n break;\n }\n }\n }\n }\n while(!q.empty()){\n int sz=q.size();\n ans++;\n int row[]={0,0,-1,1};\n int col[]={-1,1,0,0};\n for(int i=0;i<sz;i++){\n auto it=q.front();\n q.pop();\n int curr_row=it.first;\n int curr_col=it.second;\n for(int j=0;j<4;j++){\n int nr=curr_row+row[j];\n int nc=curr_col+col[j];\n if(nr>=0 and nc>=0 and nr<n and nc<n){\n if(grid[nr][nc]==0){\n q.push({nr,nc});\n grid[nr][nc]=-1;\n }else{\n if(grid[nr][nc]==1){\n return ans-1;}\n }\n \n }\n }\n }\n }\n return ans-1; \n }\n};\n```\n\n```Python3 []\nclass Solution:\n def shortestBridge(self, grid: List[List[int]]) -> int:\n n = len(grid)\n def neighbors(cell):\n i, j = cell\n if i > 0 and grid[i - 1][j] != -1:\n yield i - 1, j\n if i + 1 < n and grid[i + 1][j] != -1:\n yield i + 1, j\n if j > 0 and grid[i][j - 1] != -1:\n yield i, j - 1\n if j + 1 < n and grid[i][j + 1] != -1:\n yield i, j + 1\n \n def island():\n for i in range(n):\n for j in range(n):\n if grid[i][j]:\n grid[i][j] = -1\n return [(i, j)]\n\n q, q2, ans = island(), [], 1\n while q:\n q_next = []\n for cell in q:\n for i, j in neighbors(cell):\n (q_next if grid[i][j] else q2).append((i, j))\n grid[i][j] = -1\n q = q_next\n while q2:\n q_next = []\n for cell in q2:\n for i, j in neighbors(cell):\n if grid[i][j] == 1:\n return ans\n q_next.append((i, j))\n grid[i][j] = -1\n ans += 1\n q2 = q_next\n return ans\n```\n\n```Java []\nclass Solution {\n private static final int[][] DIRECTIONS = new int[][] { {1,0}, {-1,0}, {0,1} };\n private static final int[][] ALLDIRECTIONS = new int[][] { {1,0}, {-1,0}, {0,1} , {0, -1} };\n public int shortestBridge(int[][] grid) {\n int[] start = findLeftMostLandCoord(grid);\n grid[start[0]][start[1]] = 2;\n Queue<int[]> seed = new LinkedList<>();\n seed.offer(start);\n Queue<int[]> que = expand(grid, seed, false);\n int count = 0;\n while(!que.isEmpty()) {\n count++;\n que = expand(grid, que, true);\n }\n return count; \n }\n private int[] findLeftMostLandCoord(int[][] grid) {\n for (int c=0;c<grid[0].length;c++) {\n for (int r=0;r<grid.length;r++) {\n if (grid[r][c] == 1) {\n return new int[] {r, c};\n }\n }\n }\n return new int[] {-1, -1};\n }\n private Queue<int[]> expand(int[][] grid, Queue<int[]> seed, boolean shouldDrainOn1) {\n Queue<int[]> border = new LinkedList<>();\n while(!seed.isEmpty()) {\n int[] current = seed.poll();\n for (int[] direction : Solution.ALLDIRECTIONS) {\n int newR = current[0] + direction[0];\n int newC = current[1] + direction[1];\n if (withinBounds(grid, newR, newC)) {\n if (grid[newR][newC] == 1) {\n if (shouldDrainOn1) {\n return new LinkedList<int[]>();\n }\n seed.offer(new int[] { newR, newC});\n grid[newR][newC] = 2;\n } else if (grid[newR][newC] == 0) {\n grid[newR][newC] = 3;\n border.offer(new int[] { newR, newC});\n }\n }\n }\n }\n return border;\n }\n private boolean withinBounds(int[][] grid, int r, int c) {\n return r >=0 && r < grid.length && c >= 0 && c < grid[r].length;\n }\n}\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**.
Return _the smallest number of_ `0`_'s you must flip to connect the two islands_.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 1
**Example 2:**
**Input:** grid = \[\[0,1,0\],\[0,0,0\],\[0,0,1\]\]
**Output:** 2
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1\],\[1,0,0,0,1\],\[1,0,1,0,1\],\[1,0,0,0,1\],\[1,1,1,1,1\]\]
**Output:** 1
**Constraints:**
* `n == grid.length == grid[i].length`
* `2 <= n <= 100`
* `grid[i][j]` is either `0` or `1`.
* There are exactly two islands in `grid`. | 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,grid,n);\n dfs(r,c+1,q,grid,n);\n}\n int shortestBridge(vector<vector<int>>& grid) {\n queue<pair<int,int>>q;\n int ans=0;\n int n=grid.size();\n bool ok=true;\n for(int i=0;i<n;i++){\n if(ok){\n for(int j=0;j<n;j++){\n if(grid[i][j]==1){\n dfs(i,j,q,grid,n);\n ok =false;\n break;\n }\n }\n }\n }\n while(!q.empty()){\n int sz=q.size();\n ans++;\n int row[]={0,0,-1,1};\n int col[]={-1,1,0,0};\n for(int i=0;i<sz;i++){\n auto it=q.front();\n q.pop();\n int curr_row=it.first;\n int curr_col=it.second;\n for(int j=0;j<4;j++){\n int nr=curr_row+row[j];\n int nc=curr_col+col[j];\n if(nr>=0 and nc>=0 and nr<n and nc<n){\n if(grid[nr][nc]==0){\n q.push({nr,nc});\n grid[nr][nc]=-1;\n }else{\n if(grid[nr][nc]==1){\n return ans-1;}\n }\n \n }\n }\n }\n }\n return ans-1; \n }\n};\n```\n\n```Python3 []\nclass Solution:\n def shortestBridge(self, grid: List[List[int]]) -> int:\n n = len(grid)\n def neighbors(cell):\n i, j = cell\n if i > 0 and grid[i - 1][j] != -1:\n yield i - 1, j\n if i + 1 < n and grid[i + 1][j] != -1:\n yield i + 1, j\n if j > 0 and grid[i][j - 1] != -1:\n yield i, j - 1\n if j + 1 < n and grid[i][j + 1] != -1:\n yield i, j + 1\n \n def island():\n for i in range(n):\n for j in range(n):\n if grid[i][j]:\n grid[i][j] = -1\n return [(i, j)]\n\n q, q2, ans = island(), [], 1\n while q:\n q_next = []\n for cell in q:\n for i, j in neighbors(cell):\n (q_next if grid[i][j] else q2).append((i, j))\n grid[i][j] = -1\n q = q_next\n while q2:\n q_next = []\n for cell in q2:\n for i, j in neighbors(cell):\n if grid[i][j] == 1:\n return ans\n q_next.append((i, j))\n grid[i][j] = -1\n ans += 1\n q2 = q_next\n return ans\n```\n\n```Java []\nclass Solution {\n private static final int[][] DIRECTIONS = new int[][] { {1,0}, {-1,0}, {0,1} };\n private static final int[][] ALLDIRECTIONS = new int[][] { {1,0}, {-1,0}, {0,1} , {0, -1} };\n public int shortestBridge(int[][] grid) {\n int[] start = findLeftMostLandCoord(grid);\n grid[start[0]][start[1]] = 2;\n Queue<int[]> seed = new LinkedList<>();\n seed.offer(start);\n Queue<int[]> que = expand(grid, seed, false);\n int count = 0;\n while(!que.isEmpty()) {\n count++;\n que = expand(grid, que, true);\n }\n return count; \n }\n private int[] findLeftMostLandCoord(int[][] grid) {\n for (int c=0;c<grid[0].length;c++) {\n for (int r=0;r<grid.length;r++) {\n if (grid[r][c] == 1) {\n return new int[] {r, c};\n }\n }\n }\n return new int[] {-1, -1};\n }\n private Queue<int[]> expand(int[][] grid, Queue<int[]> seed, boolean shouldDrainOn1) {\n Queue<int[]> border = new LinkedList<>();\n while(!seed.isEmpty()) {\n int[] current = seed.poll();\n for (int[] direction : Solution.ALLDIRECTIONS) {\n int newR = current[0] + direction[0];\n int newC = current[1] + direction[1];\n if (withinBounds(grid, newR, newC)) {\n if (grid[newR][newC] == 1) {\n if (shouldDrainOn1) {\n return new LinkedList<int[]>();\n }\n seed.offer(new int[] { newR, newC});\n grid[newR][newC] = 2;\n } else if (grid[newR][newC] == 0) {\n grid[newR][newC] = 3;\n border.offer(new int[] { newR, newC});\n }\n }\n }\n }\n return border;\n }\n private boolean withinBounds(int[][] grid, int r, int c) {\n return r >=0 && r < grid.length && c >= 0 && c < grid[r].length;\n }\n}\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 binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect:
Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`.
Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`.
**Example 1:**
**Input:** root = \[1,2\], voyage = \[2,1\]
**Output:** \[-1\]
**Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage.
**Example 2:**
**Input:** root = \[1,2,3\], voyage = \[1,3,2\]
**Output:** \[1\]
**Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.
**Example 3:**
**Input:** root = \[1,2,3\], voyage = \[1,2,3\]
**Output:** \[\]
**Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.
**Constraints:**
* The number of nodes in the tree is `n`.
* `n == voyage.length`
* `1 <= n <= 100`
* `1 <= Node.val, voyage[i] <= n`
* All the values in the tree are **unique**.
* All the values in `voyage` are **unique**. | 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 \uD83D\uDC49 `Tech Wired Leetcode` to Subscribe\n\n\n# or\n\n\n# Click the Link in my Profile\n\n# Approach:\n\n- Perform a depth-first search (DFS) to find the first island in the grid. Mark the visited cells as you traverse through the island.\n- Start a breadth-first search (BFS) from the visited cells of the first island. Keep expanding to neighboring cells until you find the second island or exhaust all possible cells.\n- During the BFS, maintain the level (distance) from the first island. Return the level when you encounter the second island.\n- If no second island is found, return -1 to indicate that no bridge exists between the two islands.\n# Intuition:\n\n- We start by finding the first island using a DFS approach. We traverse the grid until we find the first cell with a value of 1, indicating the start of the island.\n- Once we find the first island, we mark all the visited cells in a set to keep track of them.\n- Next, we use a BFS approach starting from the visited cells of the first island. We explore the neighboring cells and check if they are part of the second island or not.\n- We continue BFS until we find the second island or exhaust all possible cells.\n- By using BFS, we can ensure that we find the shortest bridge between the two islands, as we traverse the grid layer by layer.\n- The distance (level) of each layer in the BFS represents the shortest path from the first island to the second island.\n- If we find the second island during BFS, we return the level as the shortest distance. Otherwise, if no second island is found, we return -1 to indicate that no bridge exists between the two islands.\n\n```Python []\nclass Solution:\n def shortestBridge(self, grid):\n m, n = len(grid), len(grid[0])\n start_i, start_j = next((i, j) for i in range(m) for j in range(n) if grid[i][j])\n \n \n stack = [(start_i, start_j)]\n visited = set(stack)\n while stack:\n i, j = stack.pop()\n visited.add((i, j)) \n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):\n if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] and (ii, jj) not in visited:\n stack.append((ii, jj))\n visited.add((ii, jj))\n \n \n ans = 0\n queue = list(visited)\n while queue:\n new_queue = []\n for i, j in queue:\n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):\n if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in visited:\n if grid[ii][jj] == 1:\n return ans\n new_queue.append((ii, jj))\n visited.add((ii, jj))\n queue = new_queue\n ans += 1\n\n```\n```Java []\n\nclass Solution {\n private int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n public int shortestBridge(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n\n int startI = -1;\n int startJ = -1;\n boolean found = false;\n\n // Step 1: Find the first island using DFS\n for (int i = 0; i < m; i++) {\n if (found) {\n break;\n }\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n startI = i;\n startJ = j;\n found = true;\n break;\n }\n }\n }\n\n Set<Integer> visited = new HashSet<>();\n dfs(grid, startI, startJ, visited);\n\n // Step 2: Perform BFS from the first island to find the shortest bridge\n Queue<Integer> queue = new ArrayDeque<>(visited);\n int level = 0;\n\n while (!queue.isEmpty()) {\n int size = queue.size();\n for (int i = 0; i < size; i++) {\n int curr = queue.poll();\n int currI = curr / n;\n int currJ = curr % n;\n\n for (int[] dir : directions) {\n int ni = currI + dir[0];\n int nj = currJ + dir[1];\n int neighbor = ni * n + nj;\n\n if (ni >= 0 && ni < m && nj >= 0 && nj < n && !visited.contains(neighbor)) {\n if (grid[ni][nj] == 1) {\n return level;\n }\n queue.offer(neighbor);\n visited.add(neighbor);\n }\n }\n }\n level++;\n }\n\n return -1; // No bridge found\n }\n\n private void dfs(int[][] grid, int i, int j, Set<Integer> visited) {\n int m = grid.length;\n int n = grid[0].length;\n int curr = i * n + j;\n\n if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != 1 || visited.contains(curr)) {\n return;\n }\n\n visited.add(curr);\n\n for (int[] dir : directions) {\n int ni = i + dir[0];\n int nj = j + dir[1];\n dfs(grid, ni, nj, visited);\n }\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n int shortestBridge(vector<vector<int>>& A) {\n int m = A.size();\n int n = A[0].size();\n\n // Step 1: Find the first island using DFS and mark its cells as visited\n bool found = false;\n unordered_set<int> visited;\n for (int i = 0; i < m; i++) {\n if (found) {\n break;\n }\n for (int j = 0; j < n; j++) {\n if (A[i][j] == 1) {\n dfs(A, i, j, visited);\n found = true;\n break;\n }\n }\n }\n\n // Step 2: Perform BFS to find the shortest bridge to the second island\n queue<int> q;\n for (int cell : visited) {\n q.push(cell);\n }\n\n vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n int level = 0;\n\n while (!q.empty()) {\n int size = q.size();\n for (int i = 0; i < size; i++) {\n int curr = q.front();\n q.pop();\n\n int currI = curr / n;\n int currJ = curr % n;\n\n for (auto dir : directions) {\n int ni = currI + dir[0];\n int nj = currJ + dir[1];\n int neighbor = ni * n + nj;\n\n if (ni >= 0 && ni < m && nj >= 0 && nj < n && visited.find(neighbor) == visited.end()) {\n if (A[ni][nj] == 1) {\n return level;\n }\n q.push(neighbor);\n visited.insert(neighbor);\n }\n }\n }\n level++;\n }\n\n return -1; // No bridge found\n }\n\nprivate:\n void dfs(vector<vector<int>>& A, int i, int j, unordered_set<int>& visited) {\n int m = A.size();\n int n = A[0].size();\n\n if (i < 0 || i >= m || j < 0 || j >= n || A[i][j] != 1 || visited.find(i * n + j) != visited.end()) {\n return;\n }\n\n visited.insert(i * n + j);\n vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n for (auto dir : directions) {\n int ni = i + dir[0];\n int nj = j + dir[1];\n dfs(A, ni, nj, visited);\n }\n }\n};\n```\n\n\n# An Upvote will be encouraging \uD83D\uDC4D | 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**.
Return _the smallest number of_ `0`_'s you must flip to connect the two islands_.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 1
**Example 2:**
**Input:** grid = \[\[0,1,0\],\[0,0,0\],\[0,0,1\]\]
**Output:** 2
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1\],\[1,0,0,0,1\],\[1,0,1,0,1\],\[1,0,0,0,1\],\[1,1,1,1,1\]\]
**Output:** 1
**Constraints:**
* `n == grid.length == grid[i].length`
* `2 <= n <= 100`
* `grid[i][j]` is either `0` or `1`.
* There are exactly two islands in `grid`. | 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 \uD83D\uDC49 `Tech Wired Leetcode` to Subscribe\n\n\n# or\n\n\n# Click the Link in my Profile\n\n# Approach:\n\n- Perform a depth-first search (DFS) to find the first island in the grid. Mark the visited cells as you traverse through the island.\n- Start a breadth-first search (BFS) from the visited cells of the first island. Keep expanding to neighboring cells until you find the second island or exhaust all possible cells.\n- During the BFS, maintain the level (distance) from the first island. Return the level when you encounter the second island.\n- If no second island is found, return -1 to indicate that no bridge exists between the two islands.\n# Intuition:\n\n- We start by finding the first island using a DFS approach. We traverse the grid until we find the first cell with a value of 1, indicating the start of the island.\n- Once we find the first island, we mark all the visited cells in a set to keep track of them.\n- Next, we use a BFS approach starting from the visited cells of the first island. We explore the neighboring cells and check if they are part of the second island or not.\n- We continue BFS until we find the second island or exhaust all possible cells.\n- By using BFS, we can ensure that we find the shortest bridge between the two islands, as we traverse the grid layer by layer.\n- The distance (level) of each layer in the BFS represents the shortest path from the first island to the second island.\n- If we find the second island during BFS, we return the level as the shortest distance. Otherwise, if no second island is found, we return -1 to indicate that no bridge exists between the two islands.\n\n```Python []\nclass Solution:\n def shortestBridge(self, grid):\n m, n = len(grid), len(grid[0])\n start_i, start_j = next((i, j) for i in range(m) for j in range(n) if grid[i][j])\n \n \n stack = [(start_i, start_j)]\n visited = set(stack)\n while stack:\n i, j = stack.pop()\n visited.add((i, j)) \n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):\n if 0 <= ii < m and 0 <= jj < n and grid[ii][jj] and (ii, jj) not in visited:\n stack.append((ii, jj))\n visited.add((ii, jj))\n \n \n ans = 0\n queue = list(visited)\n while queue:\n new_queue = []\n for i, j in queue:\n for ii, jj in (i-1, j), (i, j-1), (i, j+1), (i+1, j):\n if 0 <= ii < m and 0 <= jj < n and (ii, jj) not in visited:\n if grid[ii][jj] == 1:\n return ans\n new_queue.append((ii, jj))\n visited.add((ii, jj))\n queue = new_queue\n ans += 1\n\n```\n```Java []\n\nclass Solution {\n private int[][] directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n public int shortestBridge(int[][] grid) {\n int m = grid.length;\n int n = grid[0].length;\n\n int startI = -1;\n int startJ = -1;\n boolean found = false;\n\n // Step 1: Find the first island using DFS\n for (int i = 0; i < m; i++) {\n if (found) {\n break;\n }\n for (int j = 0; j < n; j++) {\n if (grid[i][j] == 1) {\n startI = i;\n startJ = j;\n found = true;\n break;\n }\n }\n }\n\n Set<Integer> visited = new HashSet<>();\n dfs(grid, startI, startJ, visited);\n\n // Step 2: Perform BFS from the first island to find the shortest bridge\n Queue<Integer> queue = new ArrayDeque<>(visited);\n int level = 0;\n\n while (!queue.isEmpty()) {\n int size = queue.size();\n for (int i = 0; i < size; i++) {\n int curr = queue.poll();\n int currI = curr / n;\n int currJ = curr % n;\n\n for (int[] dir : directions) {\n int ni = currI + dir[0];\n int nj = currJ + dir[1];\n int neighbor = ni * n + nj;\n\n if (ni >= 0 && ni < m && nj >= 0 && nj < n && !visited.contains(neighbor)) {\n if (grid[ni][nj] == 1) {\n return level;\n }\n queue.offer(neighbor);\n visited.add(neighbor);\n }\n }\n }\n level++;\n }\n\n return -1; // No bridge found\n }\n\n private void dfs(int[][] grid, int i, int j, Set<Integer> visited) {\n int m = grid.length;\n int n = grid[0].length;\n int curr = i * n + j;\n\n if (i < 0 || i >= m || j < 0 || j >= n || grid[i][j] != 1 || visited.contains(curr)) {\n return;\n }\n\n visited.add(curr);\n\n for (int[] dir : directions) {\n int ni = i + dir[0];\n int nj = j + dir[1];\n dfs(grid, ni, nj, visited);\n }\n }\n}\n\n```\n```C++ []\nclass Solution {\npublic:\n int shortestBridge(vector<vector<int>>& A) {\n int m = A.size();\n int n = A[0].size();\n\n // Step 1: Find the first island using DFS and mark its cells as visited\n bool found = false;\n unordered_set<int> visited;\n for (int i = 0; i < m; i++) {\n if (found) {\n break;\n }\n for (int j = 0; j < n; j++) {\n if (A[i][j] == 1) {\n dfs(A, i, j, visited);\n found = true;\n break;\n }\n }\n }\n\n // Step 2: Perform BFS to find the shortest bridge to the second island\n queue<int> q;\n for (int cell : visited) {\n q.push(cell);\n }\n\n vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n int level = 0;\n\n while (!q.empty()) {\n int size = q.size();\n for (int i = 0; i < size; i++) {\n int curr = q.front();\n q.pop();\n\n int currI = curr / n;\n int currJ = curr % n;\n\n for (auto dir : directions) {\n int ni = currI + dir[0];\n int nj = currJ + dir[1];\n int neighbor = ni * n + nj;\n\n if (ni >= 0 && ni < m && nj >= 0 && nj < n && visited.find(neighbor) == visited.end()) {\n if (A[ni][nj] == 1) {\n return level;\n }\n q.push(neighbor);\n visited.insert(neighbor);\n }\n }\n }\n level++;\n }\n\n return -1; // No bridge found\n }\n\nprivate:\n void dfs(vector<vector<int>>& A, int i, int j, unordered_set<int>& visited) {\n int m = A.size();\n int n = A[0].size();\n\n if (i < 0 || i >= m || j < 0 || j >= n || A[i][j] != 1 || visited.find(i * n + j) != visited.end()) {\n return;\n }\n\n visited.insert(i * n + j);\n vector<vector<int>> directions = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}};\n\n for (auto dir : directions) {\n int ni = i + dir[0];\n int nj = j + dir[1];\n dfs(A, ni, nj, visited);\n }\n }\n};\n```\n\n\n# An Upvote will be encouraging \uD83D\uDC4D | 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 binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect:
Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`.
Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`.
**Example 1:**
**Input:** root = \[1,2\], voyage = \[2,1\]
**Output:** \[-1\]
**Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage.
**Example 2:**
**Input:** root = \[1,2,3\], voyage = \[1,3,2\]
**Output:** \[1\]
**Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.
**Example 3:**
**Input:** root = \[1,2,3\], voyage = \[1,2,3\]
**Output:** \[\]
**Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.
**Constraints:**
* The number of nodes in the tree is `n`.
* `n == voyage.length`
* `1 <= n <= 100`
* `1 <= Node.val, voyage[i] <= n`
* All the values in the tree are **unique**.
* All the values in `voyage` are **unique**. | 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 are on the same level and make BFS until we get `Island 2`. \nSo the` number of moves` until we get `Island 2` is `SHORTEST BRIDGE`\n\n# Complexity\n- Time complexity: O(V + E)\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```\nclass Solution:\n def shortestBridge(self, grid: List[List[int]]) -> int:\n\n # step-1, get all components of island 1\n islandOne, q, visited = deque(), deque(), set()\n for r in range( len(grid)):\n for c in range( len(grid[0])):\n if grid[r][c] == 1:\n islandOne.append([r, c])\n q.append([r, c])\n visited.add((r,c))\n break\n if len(islandOne) == 1:\n break\n \n def isvalid(row, col):\n if 0 <= row < len(grid) and 0 <= col < len(grid):\n return True\n return False\n\n # make a BFS on the first land cell and get all cell in Islandone\n while q:\n size = len(q)\n for _ in range(size):\n row, col = q.popleft()\n for r, c in [ [0, 1], [0, -1], [1, 0], [-1, 0]]:\n newRow, newCol = row + r, col + c\n if (newRow,newCol) not in visited and isvalid(newRow, newCol) and grid[newRow][newCol] == 1:\n q.append([newRow, newCol])\n islandOne.append([newRow, newCol])\n visited.add((newRow, newCol))\n \n # step-2, make BFS on islandOne until we get Island-2\n numberOfMoves = 0\n while islandOne:\n size = len(islandOne)\n for _ in range( size ):\n row, col = islandOne.popleft()\n for r, c in [[0, 1],[0, -1],[1, 0], [-1, 0]]:\n newRow, newCol = row + r, col + c\n\n if (newRow,newCol) not in visited and isvalid(newRow, newCol):\n # there are exactly 2 islands, so terminate here since Island-2 is found\n if grid[newRow][newCol] == 1:\n return numberOfMoves\n\n islandOne.append([newRow, newCol])\n visited.add((newRow, newCol))\n numberOfMoves += 1\n``` | 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**.
Return _the smallest number of_ `0`_'s you must flip to connect the two islands_.
**Example 1:**
**Input:** grid = \[\[0,1\],\[1,0\]\]
**Output:** 1
**Example 2:**
**Input:** grid = \[\[0,1,0\],\[0,0,0\],\[0,0,1\]\]
**Output:** 2
**Example 3:**
**Input:** grid = \[\[1,1,1,1,1\],\[1,0,0,0,1\],\[1,0,1,0,1\],\[1,0,0,0,1\],\[1,1,1,1,1\]\]
**Output:** 1
**Constraints:**
* `n == grid.length == grid[i].length`
* `2 <= n <= 100`
* `grid[i][j]` is either `0` or `1`.
* There are exactly two islands in `grid`. | 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 are on the same level and make BFS until we get `Island 2`. \nSo the` number of moves` until we get `Island 2` is `SHORTEST BRIDGE`\n\n# Complexity\n- Time complexity: O(V + E)\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```\nclass Solution:\n def shortestBridge(self, grid: List[List[int]]) -> int:\n\n # step-1, get all components of island 1\n islandOne, q, visited = deque(), deque(), set()\n for r in range( len(grid)):\n for c in range( len(grid[0])):\n if grid[r][c] == 1:\n islandOne.append([r, c])\n q.append([r, c])\n visited.add((r,c))\n break\n if len(islandOne) == 1:\n break\n \n def isvalid(row, col):\n if 0 <= row < len(grid) and 0 <= col < len(grid):\n return True\n return False\n\n # make a BFS on the first land cell and get all cell in Islandone\n while q:\n size = len(q)\n for _ in range(size):\n row, col = q.popleft()\n for r, c in [ [0, 1], [0, -1], [1, 0], [-1, 0]]:\n newRow, newCol = row + r, col + c\n if (newRow,newCol) not in visited and isvalid(newRow, newCol) and grid[newRow][newCol] == 1:\n q.append([newRow, newCol])\n islandOne.append([newRow, newCol])\n visited.add((newRow, newCol))\n \n # step-2, make BFS on islandOne until we get Island-2\n numberOfMoves = 0\n while islandOne:\n size = len(islandOne)\n for _ in range( size ):\n row, col = islandOne.popleft()\n for r, c in [[0, 1],[0, -1],[1, 0], [-1, 0]]:\n newRow, newCol = row + r, col + c\n\n if (newRow,newCol) not in visited and isvalid(newRow, newCol):\n # there are exactly 2 islands, so terminate here since Island-2 is found\n if grid[newRow][newCol] == 1:\n return numberOfMoves\n\n islandOne.append([newRow, newCol])\n visited.add((newRow, newCol))\n numberOfMoves += 1\n``` | 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 binary tree can be **flipped** by swapping its left and right subtrees. For example, flipping node 1 will have the following effect:
Flip the **smallest** number of nodes so that the **pre-order traversal** of the tree **matches** `voyage`.
Return _a list of the values of all **flipped** nodes. You may return the answer in **any order**. If it is **impossible** to flip the nodes in the tree to make the pre-order traversal match_ `voyage`_, return the list_ `[-1]`.
**Example 1:**
**Input:** root = \[1,2\], voyage = \[2,1\]
**Output:** \[-1\]
**Explanation:** It is impossible to flip the nodes such that the pre-order traversal matches voyage.
**Example 2:**
**Input:** root = \[1,2,3\], voyage = \[1,3,2\]
**Output:** \[1\]
**Explanation:** Flipping node 1 swaps nodes 2 and 3, so the pre-order traversal matches voyage.
**Example 3:**
**Input:** root = \[1,2,3\], voyage = \[1,2,3\]
**Output:** \[\]
**Explanation:** The tree's pre-order traversal already matches voyage, so no nodes need to be flipped.
**Constraints:**
* The number of nodes in the tree is `n`.
* `n == voyage.length`
* `1 <= n <= 100`
* `1 <= Node.val, voyage[i] <= n`
* All the values in the tree are **unique**.
* All the values in `voyage` are **unique**. | 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 length `n`. The goal is to find the **count** of possible **distinct** phone numbers modulo $10^9 + 7$.\n\nThe valid knight jumps consist of moving **two** squares **vertically** and **one** square **horizontally**, **or** **two** squares **horizontally** and **one** square **vertically**. The phone pad layout is illustrated in the provided diagram, with the knight allowed to stand only on the blue, numeric cells.\n\n\n\n- **Constraints:**\n - $1 <= n <= 5000$\n - knight allowed to stand only on **numeric** cells\n\n\n---\n\n\n\n# Intuition\n\nHi There, \uD83D\uDC4B\n\nLet\'s deep dive\uD83E\uDD3F into our today\'s problem.\nThe task today is to calculate how many valid **distinct** phone numbers of length `n` can we have based on a **knight\'s** move on a phone dial\uD83D\uDCF1.\n\nOur first guy here is **Brute Force**, we can try to generate all possible numbers of length `n` and then **count** which one of them obey our rules but this will be inefficient since we have $10^n$ numbers of length `n`....actually so inefficient.\uD83D\uDE02\n\nHow can we approach this problem?\uD83E\uDD14\nI think that we can change our **perspective** a little bit.\uD83D\uDC40\nWhy don\'t we think it as a **graph** problem\uD83E\uDD28....Like we can think of the graph of depth `n` and we do something like `BFS` on it and in the end we calculate number of leaves\uD83C\uDF43 of that graph.\n\nLet\'s see what I am talking about\n\n\n\n- Based on the phone pad layout and the phone knight we can see that the **rules** in the above graph is:\n - From `0` knight can move to `4` and `6`.\n - From `1` knight can move to `6` and `8`.\n - From `2` knight can move to `7` and `9`.\n - From `3` knight can move to `4` and `8`.\n - From `4` knight can move to `0`, `3` and `9`.\n - Knight cannot move to or from position `5`.\n - From `6` knight can move to `0`, `1` and `7`.\n - From `7` knight can move to `2` and `6`.\n - From `8` knight can move to `1` and `3`.\n - From `9` knight can move to `2` and `4`.\n\nEach **edge** in the graph represents **valid** move of the knight so what we will do next is only extend the graph for each move the knight will do.\uD83E\uDD29\n\nSo if we are starting at number `1` and we have `3` moves then the graph would be like:\n\n\nAnd then we have `5` valid number starting with digit `1` and consists of `3` valid moves of the knight which are :\n181 - 183 - 160 - 161 - 167\nand their count is the number of the leaves.\n\nLet\'s try starting with digit `2` with length `4`:\n\n\nand then we have `10` valid number starting with digit `2` and consists of `4` valid moves of the knight.\n\nand this the **idea** of our problem we will **traverse** for each digit and calculate the number of valid leaves for each digit in the current depth.\n\n**Does this consider Dynamic Programming?**\n**Yes**, we canconsider this approach as DP since it has the core of DP which is caching the results that we will use it later instead of re-calculate it again. \uD83E\uDD29\n\n**Can we consider it as BFS?**\nFrom my perspective, When I saw the problem for the first time I thought of it as BFS problem and it gave the right answer. The main idea here is to understand the solution and get a valid approach based on your experience.\n\nAnd this is the solution for our today\'S problem I hope that you understood it\uD83D\uDE80\uD83D\uDE80\n\n\n\n\n\n\n---\n\n\n# Approach\n1. Initialize an array, `curPos`, with `10` elements, each set to `1`. This array represents the possible positions of the knight on the phone pad since with length one the knight can only stand on one number.\n2. **Iterative Calculation:**\n - Iterate from 2 to `n`, representing the number of jumps.\n - Inside the loop:\n - Create a new array, `newPos`, to store updated positions after each jump.\n - Calculate new positions based on valid knight moves:\n - From `0` knight can move to `4` and `6`.\n - From `1` knight can move to `6` and `8`.\n - From `2` knight can move to `7` and `9`.\n - From `3` knight can move to `4` and `8`.\n - From `4` knight can move to `0`, `3` and `9`.\n - Knight cannot move to or from position `5`.\n - From `6` knight can move to `0`, `1` and `7`.\n - From `7` knight can move to `2` and `6`.\n - From `8` knight can move to `1` and `3`.\n - From `9` knight can move to `2` and `4`.\n - Set `curPos` to `newPos` for the next iteration.\n5. After the loop, calculate the total count of distinct phone numbers using `totalCount`.\n6. **Return** Result\n\n# Complexity\n- **Time complexity:** $O(N)$\nSince we are looping for length `N` and update each posibble position for each digit so time complexity is `10 * N` which is `O(N)`.\n- **Space complexity:** $O(1)$\nSince we are only storing fixed size array of length `10` and each size is independent of the size of the input.\n\n\n---\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n static const int MOD = 1e9 + 7;\n int knightDialer(int n) {\n // Initialize an array to store the possible positions of the knight on the phone pad\n vector<long long> curPos(10, 1);\n\n // Loop through the number of jumps required\n for (int jump = 2; jump <= n; jump++) {\n // Create a new array to store the updated positions after each jump\n vector<long long> newPos(10);\n\n // Calculate the new positions based on the valid knight moves\n newPos[0] = (curPos[6] + curPos[4]) % MOD;\n newPos[1] = (curPos[6] + curPos[8]) % MOD;\n newPos[2] = (curPos[7] + curPos[9]) % MOD;\n newPos[3] = (curPos[4] + curPos[8]) % MOD;\n newPos[4] = (curPos[0] + curPos[3] + curPos[9]) % MOD;\n newPos[5] = 0; // Knight cannot move to position 5\n newPos[6] = (curPos[0] + curPos[1] + curPos[7]) % MOD;\n newPos[7] = (curPos[2] + curPos[6]) % MOD;\n newPos[8] = (curPos[1] + curPos[3]) % MOD;\n newPos[9] = (curPos[2] + curPos[4]) % MOD;\n\n // Update the current positions array for the next iteration\n curPos = newPos;\n }\n\n // Calculate the total count of distinct phone numbers\n long long totalCount = 0;\n for (int i = 0; i < 10; i++) {\n totalCount = (totalCount + curPos[i]) % MOD;\n }\n\n return totalCount;\n }\n};\n```\n```Java []\nclass Solution {\n static final int MOD = 1_000_000_007;\n\n public int knightDialer(int n) {\n // Initialize an array to store the possible positions of the knight on the phone pad\n long[] curPos = new long[10];\n Arrays.fill(curPos, 1);\n\n // Loop through the number of jumps required\n for (int jump = 2; jump <= n; jump++) {\n // Create a new array to store the updated positions after each jump\n long[] newPos = new long[10];\n\n // Calculate the new positions based on the valid knight moves\n newPos[0] = (curPos[6] + curPos[4]) % MOD;\n newPos[1] = (curPos[6] + curPos[8]) % MOD;\n newPos[2] = (curPos[7] + curPos[9]) % MOD;\n newPos[3] = (curPos[4] + curPos[8]) % MOD;\n newPos[4] = (curPos[0] + curPos[3] + curPos[9]) % MOD;\n newPos[5] = 0; // Knight cannot move to position 5\n newPos[6] = (curPos[0] + curPos[1] + curPos[7]) % MOD;\n newPos[7] = (curPos[2] + curPos[6]) % MOD;\n newPos[8] = (curPos[1] + curPos[3]) % MOD;\n newPos[9] = (curPos[2] + curPos[4]) % MOD;\n\n // Update the current positions array for the next iteration\n curPos = newPos;\n }\n\n // Calculate the total count of distinct phone numbers\n long totalCount = 0;\n for (int i = 0; i < 10; i++) {\n totalCount = (totalCount + curPos[i]) % MOD;\n }\n\n return (int) totalCount;\n }\n}\n```\n```Python []\nclass Solution:\n MOD = 10**9 + 7\n\n def knightDialer(self, n: int) -> int:\n # Initialize an array to store the possible positions of the knight on the phone pad\n cur_pos = [1] * 10\n\n # Loop through the number of jumps required\n for jump in range(2, n + 1):\n # Create a new list to store the updated positions after each jump\n new_pos = [0] * 10\n\n # Calculate the new positions based on the valid knight moves\n new_pos[0] = (cur_pos[6] + cur_pos[4]) % self.MOD\n new_pos[1] = (cur_pos[6] + cur_pos[8]) % self.MOD\n new_pos[2] = (cur_pos[7] + cur_pos[9]) % self.MOD\n new_pos[3] = (cur_pos[4] + cur_pos[8]) % self.MOD\n new_pos[4] = (cur_pos[0] + cur_pos[3] + cur_pos[9]) % self.MOD\n new_pos[5] = 0 # Knight cannot move to position 5\n new_pos[6] = (cur_pos[0] + cur_pos[1] + cur_pos[7]) % self.MOD\n new_pos[7] = (cur_pos[2] + cur_pos[6]) % self.MOD\n new_pos[8] = (cur_pos[1] + cur_pos[3]) % self.MOD\n new_pos[9] = (cur_pos[2] + cur_pos[4]) % self.MOD\n\n # Update the current positions list for the next iteration\n cur_pos = new_pos\n\n # Calculate the total count of distinct phone numbers\n total_count = sum(cur_pos) % self.MOD\n\n return total_count\n```\n```C []\n#define MOD 1000000007\n\nint knightDialer(int n) {\n // Initialize an array to store the possible positions of the knight on the phone pad\n long long cur_pos[10];\n for (int i = 0; i < 10; ++i) {\n cur_pos[i] = 1;\n }\n\n // Loop through the number of jumps required\n for (int jump = 2; jump <= n; ++jump) {\n // Create a new array to store the updated positions after each jump\n long long new_pos[10] = {0};\n\n // Calculate the new positions based on the valid knight moves\n new_pos[0] = (cur_pos[6] + cur_pos[4]) % MOD;\n new_pos[1] = (cur_pos[6] + cur_pos[8]) % MOD;\n new_pos[2] = (cur_pos[7] + cur_pos[9]) % MOD;\n new_pos[3] = (cur_pos[4] + cur_pos[8]) % MOD;\n new_pos[4] = (cur_pos[0] + cur_pos[3] + cur_pos[9]) % MOD;\n new_pos[5] = 0; // Knight cannot move to position 5\n new_pos[6] = (cur_pos[0] + cur_pos[1] + cur_pos[7]) % MOD;\n new_pos[7] = (cur_pos[2] + cur_pos[6]) % MOD;\n new_pos[8] = (cur_pos[1] + cur_pos[3]) % MOD;\n new_pos[9] = (cur_pos[2] + cur_pos[4]) % MOD;\n\n // Update the current positions array for the next iteration\n for (int i = 0; i < 10; ++i) {\n cur_pos[i] = new_pos[i];\n }\n }\n\n // Calculate the total count of distinct phone numbers\n long long total_count = 0;\n for (int i = 0; i < 10; ++i) {\n total_count = (total_count + cur_pos[i]) % MOD;\n }\n\n return (int)total_count;\n}\n```\n\n | 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 chess diagram below:
We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell).
Given an integer `n`, return how many distinct phone numbers of length `n` we can dial.
You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps.
As the answer may be very large, **return the answer modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 10
**Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
**Example 2:**
**Input:** n = 2
**Output:** 20
**Explanation:** All the valid number we can dial are \[04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94\]
**Example 3:**
**Input:** n = 3131
**Output:** 136006598
**Explanation:** Please take care of the mod.
**Constraints:**
* `1 <= n <= 5000` | 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 length `n`. The goal is to find the **count** of possible **distinct** phone numbers modulo $10^9 + 7$.\n\nThe valid knight jumps consist of moving **two** squares **vertically** and **one** square **horizontally**, **or** **two** squares **horizontally** and **one** square **vertically**. The phone pad layout is illustrated in the provided diagram, with the knight allowed to stand only on the blue, numeric cells.\n\n\n\n- **Constraints:**\n - $1 <= n <= 5000$\n - knight allowed to stand only on **numeric** cells\n\n\n---\n\n\n\n# Intuition\n\nHi There, \uD83D\uDC4B\n\nLet\'s deep dive\uD83E\uDD3F into our today\'s problem.\nThe task today is to calculate how many valid **distinct** phone numbers of length `n` can we have based on a **knight\'s** move on a phone dial\uD83D\uDCF1.\n\nOur first guy here is **Brute Force**, we can try to generate all possible numbers of length `n` and then **count** which one of them obey our rules but this will be inefficient since we have $10^n$ numbers of length `n`....actually so inefficient.\uD83D\uDE02\n\nHow can we approach this problem?\uD83E\uDD14\nI think that we can change our **perspective** a little bit.\uD83D\uDC40\nWhy don\'t we think it as a **graph** problem\uD83E\uDD28....Like we can think of the graph of depth `n` and we do something like `BFS` on it and in the end we calculate number of leaves\uD83C\uDF43 of that graph.\n\nLet\'s see what I am talking about\n\n\n\n- Based on the phone pad layout and the phone knight we can see that the **rules** in the above graph is:\n - From `0` knight can move to `4` and `6`.\n - From `1` knight can move to `6` and `8`.\n - From `2` knight can move to `7` and `9`.\n - From `3` knight can move to `4` and `8`.\n - From `4` knight can move to `0`, `3` and `9`.\n - Knight cannot move to or from position `5`.\n - From `6` knight can move to `0`, `1` and `7`.\n - From `7` knight can move to `2` and `6`.\n - From `8` knight can move to `1` and `3`.\n - From `9` knight can move to `2` and `4`.\n\nEach **edge** in the graph represents **valid** move of the knight so what we will do next is only extend the graph for each move the knight will do.\uD83E\uDD29\n\nSo if we are starting at number `1` and we have `3` moves then the graph would be like:\n\n\nAnd then we have `5` valid number starting with digit `1` and consists of `3` valid moves of the knight which are :\n181 - 183 - 160 - 161 - 167\nand their count is the number of the leaves.\n\nLet\'s try starting with digit `2` with length `4`:\n\n\nand then we have `10` valid number starting with digit `2` and consists of `4` valid moves of the knight.\n\nand this the **idea** of our problem we will **traverse** for each digit and calculate the number of valid leaves for each digit in the current depth.\n\n**Does this consider Dynamic Programming?**\n**Yes**, we canconsider this approach as DP since it has the core of DP which is caching the results that we will use it later instead of re-calculate it again. \uD83E\uDD29\n\n**Can we consider it as BFS?**\nFrom my perspective, When I saw the problem for the first time I thought of it as BFS problem and it gave the right answer. The main idea here is to understand the solution and get a valid approach based on your experience.\n\nAnd this is the solution for our today\'S problem I hope that you understood it\uD83D\uDE80\uD83D\uDE80\n\n\n\n\n\n\n---\n\n\n# Approach\n1. Initialize an array, `curPos`, with `10` elements, each set to `1`. This array represents the possible positions of the knight on the phone pad since with length one the knight can only stand on one number.\n2. **Iterative Calculation:**\n - Iterate from 2 to `n`, representing the number of jumps.\n - Inside the loop:\n - Create a new array, `newPos`, to store updated positions after each jump.\n - Calculate new positions based on valid knight moves:\n - From `0` knight can move to `4` and `6`.\n - From `1` knight can move to `6` and `8`.\n - From `2` knight can move to `7` and `9`.\n - From `3` knight can move to `4` and `8`.\n - From `4` knight can move to `0`, `3` and `9`.\n - Knight cannot move to or from position `5`.\n - From `6` knight can move to `0`, `1` and `7`.\n - From `7` knight can move to `2` and `6`.\n - From `8` knight can move to `1` and `3`.\n - From `9` knight can move to `2` and `4`.\n - Set `curPos` to `newPos` for the next iteration.\n5. After the loop, calculate the total count of distinct phone numbers using `totalCount`.\n6. **Return** Result\n\n# Complexity\n- **Time complexity:** $O(N)$\nSince we are looping for length `N` and update each posibble position for each digit so time complexity is `10 * N` which is `O(N)`.\n- **Space complexity:** $O(1)$\nSince we are only storing fixed size array of length `10` and each size is independent of the size of the input.\n\n\n---\n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n static const int MOD = 1e9 + 7;\n int knightDialer(int n) {\n // Initialize an array to store the possible positions of the knight on the phone pad\n vector<long long> curPos(10, 1);\n\n // Loop through the number of jumps required\n for (int jump = 2; jump <= n; jump++) {\n // Create a new array to store the updated positions after each jump\n vector<long long> newPos(10);\n\n // Calculate the new positions based on the valid knight moves\n newPos[0] = (curPos[6] + curPos[4]) % MOD;\n newPos[1] = (curPos[6] + curPos[8]) % MOD;\n newPos[2] = (curPos[7] + curPos[9]) % MOD;\n newPos[3] = (curPos[4] + curPos[8]) % MOD;\n newPos[4] = (curPos[0] + curPos[3] + curPos[9]) % MOD;\n newPos[5] = 0; // Knight cannot move to position 5\n newPos[6] = (curPos[0] + curPos[1] + curPos[7]) % MOD;\n newPos[7] = (curPos[2] + curPos[6]) % MOD;\n newPos[8] = (curPos[1] + curPos[3]) % MOD;\n newPos[9] = (curPos[2] + curPos[4]) % MOD;\n\n // Update the current positions array for the next iteration\n curPos = newPos;\n }\n\n // Calculate the total count of distinct phone numbers\n long long totalCount = 0;\n for (int i = 0; i < 10; i++) {\n totalCount = (totalCount + curPos[i]) % MOD;\n }\n\n return totalCount;\n }\n};\n```\n```Java []\nclass Solution {\n static final int MOD = 1_000_000_007;\n\n public int knightDialer(int n) {\n // Initialize an array to store the possible positions of the knight on the phone pad\n long[] curPos = new long[10];\n Arrays.fill(curPos, 1);\n\n // Loop through the number of jumps required\n for (int jump = 2; jump <= n; jump++) {\n // Create a new array to store the updated positions after each jump\n long[] newPos = new long[10];\n\n // Calculate the new positions based on the valid knight moves\n newPos[0] = (curPos[6] + curPos[4]) % MOD;\n newPos[1] = (curPos[6] + curPos[8]) % MOD;\n newPos[2] = (curPos[7] + curPos[9]) % MOD;\n newPos[3] = (curPos[4] + curPos[8]) % MOD;\n newPos[4] = (curPos[0] + curPos[3] + curPos[9]) % MOD;\n newPos[5] = 0; // Knight cannot move to position 5\n newPos[6] = (curPos[0] + curPos[1] + curPos[7]) % MOD;\n newPos[7] = (curPos[2] + curPos[6]) % MOD;\n newPos[8] = (curPos[1] + curPos[3]) % MOD;\n newPos[9] = (curPos[2] + curPos[4]) % MOD;\n\n // Update the current positions array for the next iteration\n curPos = newPos;\n }\n\n // Calculate the total count of distinct phone numbers\n long totalCount = 0;\n for (int i = 0; i < 10; i++) {\n totalCount = (totalCount + curPos[i]) % MOD;\n }\n\n return (int) totalCount;\n }\n}\n```\n```Python []\nclass Solution:\n MOD = 10**9 + 7\n\n def knightDialer(self, n: int) -> int:\n # Initialize an array to store the possible positions of the knight on the phone pad\n cur_pos = [1] * 10\n\n # Loop through the number of jumps required\n for jump in range(2, n + 1):\n # Create a new list to store the updated positions after each jump\n new_pos = [0] * 10\n\n # Calculate the new positions based on the valid knight moves\n new_pos[0] = (cur_pos[6] + cur_pos[4]) % self.MOD\n new_pos[1] = (cur_pos[6] + cur_pos[8]) % self.MOD\n new_pos[2] = (cur_pos[7] + cur_pos[9]) % self.MOD\n new_pos[3] = (cur_pos[4] + cur_pos[8]) % self.MOD\n new_pos[4] = (cur_pos[0] + cur_pos[3] + cur_pos[9]) % self.MOD\n new_pos[5] = 0 # Knight cannot move to position 5\n new_pos[6] = (cur_pos[0] + cur_pos[1] + cur_pos[7]) % self.MOD\n new_pos[7] = (cur_pos[2] + cur_pos[6]) % self.MOD\n new_pos[8] = (cur_pos[1] + cur_pos[3]) % self.MOD\n new_pos[9] = (cur_pos[2] + cur_pos[4]) % self.MOD\n\n # Update the current positions list for the next iteration\n cur_pos = new_pos\n\n # Calculate the total count of distinct phone numbers\n total_count = sum(cur_pos) % self.MOD\n\n return total_count\n```\n```C []\n#define MOD 1000000007\n\nint knightDialer(int n) {\n // Initialize an array to store the possible positions of the knight on the phone pad\n long long cur_pos[10];\n for (int i = 0; i < 10; ++i) {\n cur_pos[i] = 1;\n }\n\n // Loop through the number of jumps required\n for (int jump = 2; jump <= n; ++jump) {\n // Create a new array to store the updated positions after each jump\n long long new_pos[10] = {0};\n\n // Calculate the new positions based on the valid knight moves\n new_pos[0] = (cur_pos[6] + cur_pos[4]) % MOD;\n new_pos[1] = (cur_pos[6] + cur_pos[8]) % MOD;\n new_pos[2] = (cur_pos[7] + cur_pos[9]) % MOD;\n new_pos[3] = (cur_pos[4] + cur_pos[8]) % MOD;\n new_pos[4] = (cur_pos[0] + cur_pos[3] + cur_pos[9]) % MOD;\n new_pos[5] = 0; // Knight cannot move to position 5\n new_pos[6] = (cur_pos[0] + cur_pos[1] + cur_pos[7]) % MOD;\n new_pos[7] = (cur_pos[2] + cur_pos[6]) % MOD;\n new_pos[8] = (cur_pos[1] + cur_pos[3]) % MOD;\n new_pos[9] = (cur_pos[2] + cur_pos[4]) % MOD;\n\n // Update the current positions array for the next iteration\n for (int i = 0; i < 10; ++i) {\n cur_pos[i] = new_pos[i];\n }\n }\n\n // Calculate the total count of distinct phone numbers\n long long total_count = 0;\n for (int i = 0; i < 10; ++i) {\n total_count = (total_count + cur_pos[i]) % MOD;\n }\n\n return (int)total_count;\n}\n```\n\n | 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 number will be represented in one of the following three ways:
* * For example, `12`, `0`, and `123`.
* `**<.>**`
* For example, `0.5`, `1.`, `2.12`, and `123.0001`.
* `**<.>****<(>****<)>**`
* For example, `0.1(6)`, `1.(9)`, `123.00(1212)`.
The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:
* `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`.
**Example 1:**
**Input:** s = "0.(52) ", t = "0.5(25) "
**Output:** true
**Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number.
**Example 2:**
**Input:** s = "0.1666(6) ", t = "0.166(66) "
**Output:** true
**Example 3:**
**Input:** s = "0.9(9) ", t = "1. "
**Output:** true
**Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\]
"1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ".
**Constraints:**
* Each part consists only of digits.
* The does not have leading zeros (except for the zero itself).
* `1 <= .length <= 4`
* `0 <= .length <= 4`
* `1 <= .length <= 4` | 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 the goal is to find the total number of valid phone numbers of length `n`.\n\n#### Here\'s a step-by-step explanation of the approach:\n\n$$Initialization:$$\n\n- Initialize a 2D array `dp` of size `n x 10`, where `n` is the length of the phone number and `10` represents the possible digits.\n- Set the values in the first row of `dp` to 1 because there is only one way to reach each digit from the starting position (the knight is already there).\n\n$$Dynamic Programming Iteration:$$\n\n- Use a nested loop structure to iterate over the steps (`i`) and digits (`j`).\n- For each step and digit, iterate over the possible next moves from the current digit according to the valid knight moves.\n- Update the count in `dp[i][j]` by adding the counts from the previous step `(dp[i-1][next])`, considering all possible moves.\n- Take the result modulo `1_000_000_007` to handle large numbers.\n\n$$Result Calculation:$$\n- After completing the dynamic programming steps, calculate the final result by summing up the counts for each digit in the last row of `dp`.\n- Return the result modulo `1_000_000_007` as the answer may be very large.\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```java []\nclass Solution {\n public int knightDialer(int n) {\n final int MOD = 1_000_000_007;\n int[][] moves = {{4, 6}, {6, 8}, {7, 9}, {4, 8}, {0, 3, 9}, {}, {0, 1, 7}, {2, 6}, {1, 3}, {2, 4}};\n int[][] dp = new int[n][10];\n Arrays.fill(dp[0], 1);\n\n for (int i = 1; i < n; i++) {\n for (int j = 0; j < 10; j++) {\n for (int next : moves[j]) {\n dp[i][j] = (dp[i][j] + dp[i - 1][next]) % MOD;\n }\n }\n }\n\n int result = 0;\n for (int count : dp[n - 1]) {\n result = (result + count) % MOD;\n }\n\n return result;\n }\n}\n```\n```python []\nclass Solution:\n def knightDialer(self, n: int) -> int:\n MOD = 10**9 + 7\n moves = {0: [4, 6], 1: [6, 8], 2: [7, 9], 3: [4, 8], 4: [0, 3, 9], 5: [], 6: [0, 1, 7], 7: [2, 6], 8: [1, 3], 9: [2, 4]}\n dp = dict()\n \n # base cases\n for i in range(10):\n dp[(1, i)] = 1\n \n # bottom up\n for m in range(2, n+1): # calculate all subproblems of len m digits\n for currDigit in range(10): # calculate all subproblems of len m digits starting at currDigit\n dp[(m, currDigit)] = sum([dp[(m-1, nextDigit)] for nextDigit in moves[currDigit]]) % MOD\n return sum([dp[(n, i)] for i in range(10)]) % MOD\n```\n```python3 []\nclass Solution:\n def knightDialer(self, n: int) -> int:\n @lru_cache(None)\n def helper(n, row, col):\n if n==0:\n return 1\n ans=0\n for row_i, col_i in [[2,1], [1,2], [-2,1], [-1,2], [2,-1], [1,-2], [-2,-1], [-1,-2]]:\n new_row = row+row_i\n new_col = col+col_i\n if (-1<new_row<3 and -1<new_col<3) or (new_row==3 and new_col==1):\n ans+=helper(n-1, new_row, new_col)\n return ans%(10**9+7)\n \n ans = helper(n-1, 3, 1)\n for row in range(3):\n for col in range(3):\n ans += helper(n-1, row, col)\n return ans%(10**9+7)\n```\n```C++ []\nclass Solution {\npublic:\n int knightDialer(int n) {\n vector<vector<int>> keypad{{4,6},{6,8},{7,9},{4,8},{0,3,9},{},{1,7,0},{2,6},{1,3},{4,2}};\n vector<vector<int>> dp(10,vector<int>(n+1,0));\n for(int i=0;i<10;i++) {\n dp[i][1]=1;\n }\n if(n==1) return 10;\n for(int j=2;j<=n;j++) {\n for(int i=0;i<10;i++) {\n for(int k=0;k<keypad[i].size();k++) {\n dp[i][j]=(dp[i][j]+dp[ keypad[i][k] ][j-1])%1000000007;\n }\n }\n }\n int ans=0;\n for(int i=0;i<10;i++) {\n ans=(ans+dp[i][n])%1000000007;\n }\n return ans;\n }\n};\n```\n```C []\nclass Solution {\npublic:\n int knightDialer(int n) {\n vector<vector<int>> keypad{{4,6},{6,8},{7,9},{4,8},{0,3,9},{},{1,7,0},{2,6},{1,3},{4,2}};\n vector<vector<int>> dp(10,vector<int>(n+1,0));\n for(int i=0;i<10;i++) {\n dp[i][1]=1;\n }\n if(n==1) return 10;\n for(int j=2;j<=n;j++) {\n for(int i=0;i<10;i++) {\n for(int k=0;k<keypad[i].size();k++) {\n dp[i][j]=(dp[i][j]+dp[keypad[i][k] ][j-1])%1000000007;\n }\n }\n }\n int ans=0;\n for(int i=0;i<10;i++) {\n ans=(ans+dp[i][n])%1000000007;\n }\n return ans;\n }\n};\n```\n```Javacsript []\nvar knightDialer = function(moves) {\n const MOD = 1e9 + 7;\n const memo = new Map();\n const nextValidKeys = {\n 0: [4, 6],\n 1: [6, 8],\n 2: [7, 9],\n 3: [4, 8],\n 4: [0, 3, 9],\n 5: [],\n 6: [0, 1, 7],\n 7: [2, 6],\n 8: [1, 3],\n 9: [2, 4]\n }; \n \n let count = 0;\n \n for (let i = 0; i <= 9; i++) {\n count = (count + countDistinctWays(i, moves - 1)) % MOD;\n }\n \n return count;\n \n function countDistinctWays(currKey, n) {\n const key = `${currKey}#${n}`;\n \n\t\t// base case\n if (n == 0) return 1;\n if (memo.has(key)) return memo.get(key);\n \n let count = 0;\n \n for (const nextKey of nextValidKeys[currKey]) {\n count = (count + countDistinctWays(nextKey, n - 1)) % MOD;\n }\n \n memo.set(key, count);\n return count;\n }\n};\n```\n# If you like the solution please UPVOTE !!\n\n\n\n | 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 chess diagram below:
We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell).
Given an integer `n`, return how many distinct phone numbers of length `n` we can dial.
You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps.
As the answer may be very large, **return the answer modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 10
**Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
**Example 2:**
**Input:** n = 2
**Output:** 20
**Explanation:** All the valid number we can dial are \[04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94\]
**Example 3:**
**Input:** n = 3131
**Output:** 136006598
**Explanation:** Please take care of the mod.
**Constraints:**
* `1 <= n <= 5000` | 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 the goal is to find the total number of valid phone numbers of length `n`.\n\n#### Here\'s a step-by-step explanation of the approach:\n\n$$Initialization:$$\n\n- Initialize a 2D array `dp` of size `n x 10`, where `n` is the length of the phone number and `10` represents the possible digits.\n- Set the values in the first row of `dp` to 1 because there is only one way to reach each digit from the starting position (the knight is already there).\n\n$$Dynamic Programming Iteration:$$\n\n- Use a nested loop structure to iterate over the steps (`i`) and digits (`j`).\n- For each step and digit, iterate over the possible next moves from the current digit according to the valid knight moves.\n- Update the count in `dp[i][j]` by adding the counts from the previous step `(dp[i-1][next])`, considering all possible moves.\n- Take the result modulo `1_000_000_007` to handle large numbers.\n\n$$Result Calculation:$$\n- After completing the dynamic programming steps, calculate the final result by summing up the counts for each digit in the last row of `dp`.\n- Return the result modulo `1_000_000_007` as the answer may be very large.\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```java []\nclass Solution {\n public int knightDialer(int n) {\n final int MOD = 1_000_000_007;\n int[][] moves = {{4, 6}, {6, 8}, {7, 9}, {4, 8}, {0, 3, 9}, {}, {0, 1, 7}, {2, 6}, {1, 3}, {2, 4}};\n int[][] dp = new int[n][10];\n Arrays.fill(dp[0], 1);\n\n for (int i = 1; i < n; i++) {\n for (int j = 0; j < 10; j++) {\n for (int next : moves[j]) {\n dp[i][j] = (dp[i][j] + dp[i - 1][next]) % MOD;\n }\n }\n }\n\n int result = 0;\n for (int count : dp[n - 1]) {\n result = (result + count) % MOD;\n }\n\n return result;\n }\n}\n```\n```python []\nclass Solution:\n def knightDialer(self, n: int) -> int:\n MOD = 10**9 + 7\n moves = {0: [4, 6], 1: [6, 8], 2: [7, 9], 3: [4, 8], 4: [0, 3, 9], 5: [], 6: [0, 1, 7], 7: [2, 6], 8: [1, 3], 9: [2, 4]}\n dp = dict()\n \n # base cases\n for i in range(10):\n dp[(1, i)] = 1\n \n # bottom up\n for m in range(2, n+1): # calculate all subproblems of len m digits\n for currDigit in range(10): # calculate all subproblems of len m digits starting at currDigit\n dp[(m, currDigit)] = sum([dp[(m-1, nextDigit)] for nextDigit in moves[currDigit]]) % MOD\n return sum([dp[(n, i)] for i in range(10)]) % MOD\n```\n```python3 []\nclass Solution:\n def knightDialer(self, n: int) -> int:\n @lru_cache(None)\n def helper(n, row, col):\n if n==0:\n return 1\n ans=0\n for row_i, col_i in [[2,1], [1,2], [-2,1], [-1,2], [2,-1], [1,-2], [-2,-1], [-1,-2]]:\n new_row = row+row_i\n new_col = col+col_i\n if (-1<new_row<3 and -1<new_col<3) or (new_row==3 and new_col==1):\n ans+=helper(n-1, new_row, new_col)\n return ans%(10**9+7)\n \n ans = helper(n-1, 3, 1)\n for row in range(3):\n for col in range(3):\n ans += helper(n-1, row, col)\n return ans%(10**9+7)\n```\n```C++ []\nclass Solution {\npublic:\n int knightDialer(int n) {\n vector<vector<int>> keypad{{4,6},{6,8},{7,9},{4,8},{0,3,9},{},{1,7,0},{2,6},{1,3},{4,2}};\n vector<vector<int>> dp(10,vector<int>(n+1,0));\n for(int i=0;i<10;i++) {\n dp[i][1]=1;\n }\n if(n==1) return 10;\n for(int j=2;j<=n;j++) {\n for(int i=0;i<10;i++) {\n for(int k=0;k<keypad[i].size();k++) {\n dp[i][j]=(dp[i][j]+dp[ keypad[i][k] ][j-1])%1000000007;\n }\n }\n }\n int ans=0;\n for(int i=0;i<10;i++) {\n ans=(ans+dp[i][n])%1000000007;\n }\n return ans;\n }\n};\n```\n```C []\nclass Solution {\npublic:\n int knightDialer(int n) {\n vector<vector<int>> keypad{{4,6},{6,8},{7,9},{4,8},{0,3,9},{},{1,7,0},{2,6},{1,3},{4,2}};\n vector<vector<int>> dp(10,vector<int>(n+1,0));\n for(int i=0;i<10;i++) {\n dp[i][1]=1;\n }\n if(n==1) return 10;\n for(int j=2;j<=n;j++) {\n for(int i=0;i<10;i++) {\n for(int k=0;k<keypad[i].size();k++) {\n dp[i][j]=(dp[i][j]+dp[keypad[i][k] ][j-1])%1000000007;\n }\n }\n }\n int ans=0;\n for(int i=0;i<10;i++) {\n ans=(ans+dp[i][n])%1000000007;\n }\n return ans;\n }\n};\n```\n```Javacsript []\nvar knightDialer = function(moves) {\n const MOD = 1e9 + 7;\n const memo = new Map();\n const nextValidKeys = {\n 0: [4, 6],\n 1: [6, 8],\n 2: [7, 9],\n 3: [4, 8],\n 4: [0, 3, 9],\n 5: [],\n 6: [0, 1, 7],\n 7: [2, 6],\n 8: [1, 3],\n 9: [2, 4]\n }; \n \n let count = 0;\n \n for (let i = 0; i <= 9; i++) {\n count = (count + countDistinctWays(i, moves - 1)) % MOD;\n }\n \n return count;\n \n function countDistinctWays(currKey, n) {\n const key = `${currKey}#${n}`;\n \n\t\t// base case\n if (n == 0) return 1;\n if (memo.has(key)) return memo.get(key);\n \n let count = 0;\n \n for (const nextKey of nextValidKeys[currKey]) {\n count = (count + countDistinctWays(nextKey, n - 1)) % MOD;\n }\n \n memo.set(key, count);\n return count;\n }\n};\n```\n# If you like the solution please UPVOTE !!\n\n\n\n | 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 number will be represented in one of the following three ways:
* * For example, `12`, `0`, and `123`.
* `**<.>**`
* For example, `0.5`, `1.`, `2.12`, and `123.0001`.
* `**<.>****<(>****<)>**`
* For example, `0.1(6)`, `1.(9)`, `123.00(1212)`.
The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:
* `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`.
**Example 1:**
**Input:** s = "0.(52) ", t = "0.5(25) "
**Output:** true
**Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number.
**Example 2:**
**Input:** s = "0.1666(6) ", t = "0.166(66) "
**Output:** true
**Example 3:**
**Input:** s = "0.9(9) ", t = "1. "
**Output:** true
**Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\]
"1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ".
**Constraints:**
* Each part consists only of digits.
* The does not have leading zeros (except for the zero itself).
* `1 <= .length <= 4`
* `0 <= .length <= 4`
* `1 <= .length <= 4` | 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 _ in range(10)]\n \n for i in range(n-1):\n tmp = [\n arr[4]+arr[6],\n arr[6]+arr[8],\n arr[7]+arr[9],\n arr[4]+arr[8],\n arr[3]+arr[9]+arr[0],\n 0,\n arr[1]+arr[7]+arr[0],\n arr[2]+arr[6],\n arr[1]+arr[3],\n arr[2]+arr[4]\n ]\n \n arr = tmp\n \n return sum(arr)%(10**9+7)\n``` | 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 chess diagram below:
We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell).
Given an integer `n`, return how many distinct phone numbers of length `n` we can dial.
You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps.
As the answer may be very large, **return the answer modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 10
**Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
**Example 2:**
**Input:** n = 2
**Output:** 20
**Explanation:** All the valid number we can dial are \[04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94\]
**Example 3:**
**Input:** n = 3131
**Output:** 136006598
**Explanation:** Please take care of the mod.
**Constraints:**
* `1 <= n <= 5000` | 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 _ in range(10)]\n \n for i in range(n-1):\n tmp = [\n arr[4]+arr[6],\n arr[6]+arr[8],\n arr[7]+arr[9],\n arr[4]+arr[8],\n arr[3]+arr[9]+arr[0],\n 0,\n arr[1]+arr[7]+arr[0],\n arr[2]+arr[6],\n arr[1]+arr[3],\n arr[2]+arr[4]\n ]\n \n arr = tmp\n \n return sum(arr)%(10**9+7)\n``` | 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 number will be represented in one of the following three ways:
* * For example, `12`, `0`, and `123`.
* `**<.>**`
* For example, `0.5`, `1.`, `2.12`, and `123.0001`.
* `**<.>****<(>****<)>**`
* For example, `0.1(6)`, `1.(9)`, `123.00(1212)`.
The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:
* `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`.
**Example 1:**
**Input:** s = "0.(52) ", t = "0.5(25) "
**Output:** true
**Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number.
**Example 2:**
**Input:** s = "0.1666(6) ", t = "0.166(66) "
**Output:** true
**Example 3:**
**Input:** s = "0.9(9) ", t = "1. "
**Output:** true
**Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\]
"1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ".
**Constraints:**
* Each part consists only of digits.
* The does not have leading zeros (except for the zero itself).
* `1 <= .length <= 4`
* `0 <= .length <= 4`
* `1 <= .length <= 4` | 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]+arr[7]+arr[0],arr[2]+arr[6],arr[1]+arr[3],arr[2]+arr[4]]\n return sum(arr)%(10**9+7)\n```\n\n | 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 chess diagram below:
We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell).
Given an integer `n`, return how many distinct phone numbers of length `n` we can dial.
You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps.
As the answer may be very large, **return the answer modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 10
**Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
**Example 2:**
**Input:** n = 2
**Output:** 20
**Explanation:** All the valid number we can dial are \[04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94\]
**Example 3:**
**Input:** n = 3131
**Output:** 136006598
**Explanation:** Please take care of the mod.
**Constraints:**
* `1 <= n <= 5000` | 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]+arr[7]+arr[0],arr[2]+arr[6],arr[1]+arr[3],arr[2]+arr[4]]\n return sum(arr)%(10**9+7)\n```\n\n | 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 number will be represented in one of the following three ways:
* * For example, `12`, `0`, and `123`.
* `**<.>**`
* For example, `0.5`, `1.`, `2.12`, and `123.0001`.
* `**<.>****<(>****<)>**`
* For example, `0.1(6)`, `1.(9)`, `123.00(1212)`.
The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:
* `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`.
**Example 1:**
**Input:** s = "0.(52) ", t = "0.5(25) "
**Output:** true
**Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number.
**Example 2:**
**Input:** s = "0.1666(6) ", t = "0.166(66) "
**Output:** true
**Example 3:**
**Input:** s = "0.9(9) ", t = "1. "
**Output:** true
**Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\]
"1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ".
**Constraints:**
* Each part consists only of digits.
* The does not have leading zeros (except for the zero itself).
* `1 <= .length <= 4`
* `0 <= .length <= 4`
* `1 <= .length <= 4` | 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 dp[3]=old_dp[4]+old_dp[8]\n dp[4]=old_dp[3]+old_dp[9]+old_dp[0]\n dp[5]=0\n dp[6]=old_dp[1]+old_dp[7]+old_dp[0]\n dp[7]=old_dp[2]+old_dp[6]\n dp[8]=old_dp[1]+old_dp[3]\n dp[9]=old_dp[2]+old_dp[4]\n \n ans=sum(dp)%mod\n return ans\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 chess diagram below:
We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell).
Given an integer `n`, return how many distinct phone numbers of length `n` we can dial.
You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps.
As the answer may be very large, **return the answer modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 10
**Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
**Example 2:**
**Input:** n = 2
**Output:** 20
**Explanation:** All the valid number we can dial are \[04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94\]
**Example 3:**
**Input:** n = 3131
**Output:** 136006598
**Explanation:** Please take care of the mod.
**Constraints:**
* `1 <= n <= 5000` | 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 dp[3]=old_dp[4]+old_dp[8]\n dp[4]=old_dp[3]+old_dp[9]+old_dp[0]\n dp[5]=0\n dp[6]=old_dp[1]+old_dp[7]+old_dp[0]\n dp[7]=old_dp[2]+old_dp[6]\n dp[8]=old_dp[1]+old_dp[3]\n dp[9]=old_dp[2]+old_dp[4]\n \n ans=sum(dp)%mod\n return ans\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 number will be represented in one of the following three ways:
* * For example, `12`, `0`, and `123`.
* `**<.>**`
* For example, `0.5`, `1.`, `2.12`, and `123.0001`.
* `**<.>****<(>****<)>**`
* For example, `0.1(6)`, `1.(9)`, `123.00(1212)`.
The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:
* `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`.
**Example 1:**
**Input:** s = "0.(52) ", t = "0.5(25) "
**Output:** true
**Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number.
**Example 2:**
**Input:** s = "0.1666(6) ", t = "0.166(66) "
**Output:** true
**Example 3:**
**Input:** s = "0.9(9) ", t = "1. "
**Output:** true
**Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\]
"1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ".
**Constraints:**
* Each part consists only of digits.
* The does not have leading zeros (except for the zero itself).
* `1 <= .length <= 4`
* `0 <= .length <= 4`
* `1 <= .length <= 4` | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def knightDialer(self, n: int) -> int:\n @cache\n def dp(remain, square):\n if remain == 0:\n return 1\n \n ans = 0\n for next_square in jumps[square]:\n ans = (ans + dp(remain - 1, next_square)) % MOD\n \n return ans\n \n jumps = [\n [4, 6],\n [6, 8],\n [7, 9],\n [4, 8],\n [3, 9, 0],\n [],\n [1, 7, 0],\n [2, 6],\n [1, 3],\n [2, 4]\n ]\n\n ans = 0\n MOD = 10 ** 9 + 7\n for square in range(10):\n ans = (ans + dp(n - 1, square)) % MOD\n \n return ans\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 chess diagram below:
We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell).
Given an integer `n`, return how many distinct phone numbers of length `n` we can dial.
You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps.
As the answer may be very large, **return the answer modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 10
**Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
**Example 2:**
**Input:** n = 2
**Output:** 20
**Explanation:** All the valid number we can dial are \[04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94\]
**Example 3:**
**Input:** n = 3131
**Output:** 136006598
**Explanation:** Please take care of the mod.
**Constraints:**
* `1 <= n <= 5000` | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def knightDialer(self, n: int) -> int:\n @cache\n def dp(remain, square):\n if remain == 0:\n return 1\n \n ans = 0\n for next_square in jumps[square]:\n ans = (ans + dp(remain - 1, next_square)) % MOD\n \n return ans\n \n jumps = [\n [4, 6],\n [6, 8],\n [7, 9],\n [4, 8],\n [3, 9, 0],\n [],\n [1, 7, 0],\n [2, 6],\n [1, 3],\n [2, 4]\n ]\n\n ans = 0\n MOD = 10 ** 9 + 7\n for square in range(10):\n ans = (ans + dp(n - 1, square)) % MOD\n \n return ans\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 number will be represented in one of the following three ways:
* * For example, `12`, `0`, and `123`.
* `**<.>**`
* For example, `0.5`, `1.`, `2.12`, and `123.0001`.
* `**<.>****<(>****<)>**`
* For example, `0.1(6)`, `1.(9)`, `123.00(1212)`.
The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:
* `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`.
**Example 1:**
**Input:** s = "0.(52) ", t = "0.5(25) "
**Output:** true
**Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number.
**Example 2:**
**Input:** s = "0.1666(6) ", t = "0.166(66) "
**Output:** true
**Example 3:**
**Input:** s = "0.9(9) ", t = "1. "
**Output:** true
**Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\]
"1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ".
**Constraints:**
* Each part consists only of digits.
* The does not have leading zeros (except for the zero itself).
* `1 <= .length <= 4`
* `0 <= .length <= 4`
* `1 <= .length <= 4` | 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 knight makes valid moves based on these buttons.\n1. For each digit (`key`), there are specific other digits (buttons) the knight can move to.\n1. The algorithm uses dynamic programming to calculate the number of possible paths the knight can take in `n` steps.\n1. It iterates through each step, updating the count of possible positions based on the available moves for each `key`.\n1. Finally, it returns the total count of possible positions after `n` steps.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\n\n\nclass Solution {\npublic:\n int knightDialer(int n) {\n if(n == 1) return 10; // If n is 1, there are 10 possible starting positions for the knight.\n\n unordered_map<int, vector<int>> mp; // Map to store the possible moves for each key/button on the dial pad.\n int MOD = 1000000007; // Modulo value for handling large numbers.\n\n // Assigning possible moves for each key/button on the dial pad.\n mp[0] = {4, 6};\n mp[1] = {6, 8};\n mp[2] = {7, 9};\n mp[3] = {4, 8};\n mp[4] = {0, 3, 9};\n mp[6] = {0, 1, 7};\n mp[7] = {2, 6};\n mp[8] = {1, 3};\n mp[9] = {2, 4};\n\n vector<int> v(10, 1); // Initializing a vector to store counts of possible positions.\n for(int i = 2; i <= n; i++) { // Looping from 2 to n to calculate the count of possible positions for each step.\n vector<int> temp(10); // Temporary vector to store updated counts for each key/button.\n for(auto [key, val] : mp) { // Iterating through the dial pad keys.\n for(auto j : val) { // Iterating through possible moves for each key.\n temp[key] = (temp[key] + v[j]) % MOD; // Updating counts for each key/button based on possible moves.\n }\n }\n v = temp; // Updating the counts after each step.\n }\n\n int ans = 0;\n for(auto a : v) {\n ans = (ans + a) % MOD; // Calculating the total count of possible positions after n steps.\n }\n return ans;\n }\n};\n\n\n\n```\n```C []\n\n\n#define MOD 1000000007\n\nint knightDialer(int n) {\n if (n == 1) return 10; // If n is 1, there are 10 possible starting positions for the knight.\n\n int moves[10][2] = { {4, 6}, {6, 8}, {7, 9}, {4, 8}, {0, 3, 9}, {-1, -1}, {0, 1, 7}, {2, 6}, {1, 3}, {2, 4} }; // Array to store the possible moves for each key/button on the dial pad.\n int v[10] = {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}; // Array to store counts of possible positions.\n int i, j, k;\n\n for (i = 2; i <= n; i++) { // Looping from 2 to n to calculate the count of possible positions for each step.\n int temp[10] = {0}; // Temporary array to store updated counts for each key/button.\n\n for (j = 0; j < 10; j++) { // Iterating through the dial pad keys.\n if (moves[j][0] != -1) {\n for (k = 0; moves[j][k] != -1; k++) { // Iterating through possible moves for each key.\n temp[j] = (temp[j] + v[moves[j][k]]) % MOD; // Updating counts for each key/button based on possible moves.\n }\n }\n }\n\n for (j = 0; j < 10; j++) {\n v[j] = temp[j]; // Updating the counts after each step.\n }\n }\n\n int ans = 0;\n for (i = 0; i < 10; i++) {\n ans = (ans + v[i]) % MOD; // Calculating the total count of possible positions after n steps.\n }\n return ans;\n}\n\n\n```\n\n```Java []\n\nclass Solution {\n public int knightDialer(int n) {\n if (n == 1) {\n return 10; // If n is 1, there are 10 possible starting positions for the knight.\n }\n\n // Map to store the possible moves for each key/button on the dial pad.\n Map<Integer, List<Integer>> mp = new HashMap<>();\n mp.put(0, Arrays.asList(4, 6));\n mp.put(1, Arrays.asList(6, 8));\n mp.put(2, Arrays.asList(7, 9));\n mp.put(3, Arrays.asList(4, 8));\n mp.put(4, Arrays.asList(0, 3, 9));\n mp.put(6, Arrays.asList(0, 1, 7));\n mp.put(7, Arrays.asList(2, 6));\n mp.put(8, Arrays.asList(1, 3));\n mp.put(9, Arrays.asList(2, 4));\n\n int MOD = 1000000007; // Modulo value for handling large numbers.\n int[] v = new int[10]; // Initializing an array to store counts of possible positions.\n Arrays.fill(v, 1);\n\n for (int i = 2; i <= n; i++) {\n int[] temp = new int[10]; // Temporary array to store updated counts for each key/button.\n for (Map.Entry<Integer, List<Integer>> entry : mp.entrySet()) {\n int key = entry.getKey();\n List<Integer> val = entry.getValue();\n for (int j : val) {\n temp[key] = (temp[key] + v[j]) % MOD; // Updating counts for each key/button based on possible moves.\n }\n }\n v = temp; // Updating the counts after each step.\n }\n\n int ans = 0;\n for (int a : v) {\n ans = (ans + a) % MOD; // Calculating the total count of possible positions after n steps.\n }\n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def knightDialer(self, n: int) -> int:\n if n == 1:\n return 10 # If n is 1, there are 10 possible starting positions for the knight.\n\n # Map to store possible moves for each key/button on the dial pad.\n mp = {\n 0: [4, 6],\n 1: [6, 8],\n 2: [7, 9],\n 3: [4, 8],\n 4: [0, 3, 9],\n 6: [0, 1, 7],\n 7: [2, 6],\n 8: [1, 3],\n 9: [2, 4]\n }\n \n MOD = 10**9 + 7 # Modulo value for handling large numbers.\n v = [1] * 10 # Initializing a list to store counts of possible positions.\n\n for i in range(2, n + 1):\n temp = [0] * 10 # Temporary list to store updated counts for each key/button.\n for key, val in mp.items():\n for j in val:\n temp[key] = (temp[key] + v[j]) % MOD # Updating counts for each key/button based on possible moves.\n v = temp # Updating the counts after each step.\n\n return sum(v) % MOD # Calculating the total count of possible positions after n steps.\n\n\n\n```\n```javascript []\nvar knightDialer = function(n) {\n if (n === 1) return 10; // If n is 1, there are 10 possible starting positions for the knight.\n\n const mp = new Map(); // Map to store the possible moves for each key/button on the dial pad.\n const MOD = 1000000007; // Modulo value for handling large numbers.\n\n // Assigning possible moves for each key/button on the dial pad.\n mp.set(0, [4, 6]);\n mp.set(1, [6, 8]);\n mp.set(2, [7, 9]);\n mp.set(3, [4, 8]);\n mp.set(4, [0, 3, 9]);\n mp.set(6, [0, 1, 7]);\n mp.set(7, [2, 6]);\n mp.set(8, [1, 3]);\n mp.set(9, [2, 4]);\n\n let v = Array(10).fill(1); // Initializing an array to store counts of possible positions.\n for (let i = 2; i <= n; i++) { // Looping from 2 to n to calculate the count of possible positions for each step.\n const temp = Array(10).fill(0); // Temporary array to store updated counts for each key/button.\n for (const [key, val] of mp) { // Iterating through the dial pad keys.\n for (const j of val) { // Iterating through possible moves for each key.\n temp[key] = (temp[key] + v[j]) % MOD; // Updating counts for each key/button based on possible moves.\n }\n }\n v = [...temp]; // Updating the counts after each step.\n }\n\n let ans = 0;\n for (const a of v) {\n ans = (ans + a) % MOD; // Calculating the total count of possible positions after n steps.\n }\n return ans;\n};\n\n\n```\n\n---\n#### ***Approach 2(Top-Down DP)***\n1. The code uses a recursive approach with memoization to count the number of possible moves a knight can make on a phone dial pad in `n` steps.\n1. The `jumps` array holds the possible moves for each digit on the dial pad (representing a square).\n1. The `dp` function performs a recursive depth-first search (DFS) to calculate the number of moves remaining from a specific square, considering all possible next squares based on valid knight moves.\n1. `memo` is a memoization table used to store and retrieve already computed results to avoid redundant calculations.\n1. The `knightDialer` function initializes the memoization array and iterates through each starting square, computing the total number of moves for `n` steps.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\n\n\nclass Solution {\npublic:\n // Memoization array to store computed results\n vector<vector<int>> memo;\n int n; // Input value \'n\'\n int MOD = 1e9 + 7; // Modulo value for handling large numbers\n // Possible jumps for each digit (representing a square on the dial pad)\n vector<vector<int>> jumps = {\n {4, 6},\n {6, 8},\n {7, 9},\n {4, 8},\n {3, 9, 0},\n {},\n {1, 7, 0},\n {2, 6},\n {1, 3},\n {2, 4}\n };\n \n // Recursive function to calculate the number of moves\n int dp(int remain, int square) {\n if (remain == 0) {\n return 1; // If no more steps remain, return 1 (indicating a valid path)\n }\n \n if (memo[remain][square] != 0) {\n return memo[remain][square]; // If the value is already calculated, return it\n }\n \n int ans = 0;\n // Recursively calculate the number of moves for each next square\n for (int nextSquare : jumps[square]) {\n ans = (ans + dp(remain - 1, nextSquare)) % MOD; // Add the count of possible moves\n }\n \n memo[remain][square] = ans; // Store the computed result in the memoization array\n return ans; // Return the total count of possible moves\n }\n \n // Main function to calculate the number of possible moves for \'n\' steps\n int knightDialer(int n) {\n this->n = n;\n memo = vector(n + 1, vector<int>(10, 0)); // Initialize memoization array\n int ans = 0;\n // Calculate the total number of moves for each starting square\n for (int square = 0; square < 10; square++) {\n ans = (ans + dp(n - 1, square)) % MOD; // Add the count of possible moves for each starting square\n }\n \n return ans; // Return the total count of possible moves after \'n\' steps\n }\n};\n\n\n\n```\n```C []\n#define MOD 1000000007\n\nint memo[501][10] = {{0}};\nint n;\nint jumps[10][3] = {\n {4, 6, -1},\n {6, 8, -1},\n {7, 9, -1},\n {4, 8, -1},\n {3, 9, 0},\n {-1, -1, -1},\n {1, 7, 0},\n {2, 6, -1},\n {1, 3, -1},\n {2, 4, -1}\n};\n\nint dp(int remain, int square) {\n if (remain == 0) {\n return 1;\n }\n \n if (memo[remain][square] != 0) {\n return memo[remain][square];\n }\n \n int ans = 0;\n for (int i = 0; jumps[square][i] != -1; i++) {\n int nextSquare = jumps[square][i];\n ans = (ans + dp(remain - 1, nextSquare)) % MOD;\n }\n \n memo[remain][square] = ans;\n return ans;\n}\n\nint knightDialer(int n) {\n int ans = 0;\n for (int square = 0; square < 10; square++) {\n ans = (ans + dp(n - 1, square)) % MOD;\n }\n \n return ans;\n}\n\n\n```\n\n```Java []\nclass Solution {\n int[][] memo;\n int n;\n int MOD = (int) 1e9 + 7;\n int[][] jumps = {\n {4, 6},\n {6, 8},\n {7, 9},\n {4, 8},\n {3, 9, 0},\n {},\n {1, 7, 0},\n {2, 6},\n {1, 3},\n {2, 4}\n };\n \n public int dp(int remain, int square) {\n if (remain == 0) {\n return 1;\n }\n \n if (memo[remain][square] != 0) {\n return memo[remain][square];\n }\n \n int ans = 0;\n for (int nextSquare : jumps[square]) {\n ans = (ans + dp(remain - 1, nextSquare)) % MOD;\n }\n \n memo[remain][square] = ans;\n return ans;\n }\n \n public int knightDialer(int n) {\n this.n = n;\n memo = new int[n + 1][10];\n int ans = 0;\n for (int square = 0; square < 10; square++) {\n ans = (ans + dp(n - 1, square)) % MOD;\n }\n \n return ans;\n }\n}\n\n\n```\n```python3 []\n\nclass Solution:\n def knightDialer(self, n: int) -> int:\n @cache\n def dp(remain, square):\n if remain == 0:\n return 1\n \n ans = 0\n for next_square in jumps[square]:\n ans = (ans + dp(remain - 1, next_square)) % MOD\n \n return ans\n \n jumps = [\n [4, 6],\n [6, 8],\n [7, 9],\n [4, 8],\n [3, 9, 0],\n [],\n [1, 7, 0],\n [2, 6],\n [1, 3],\n [2, 4]\n ]\n\n ans = 0\n MOD = 10 ** 9 + 7\n for square in range(10):\n ans = (ans + dp(n - 1, square)) % MOD\n \n return ans\n\n```\n```javascript []\nlet memo = [];\nlet n;\nconst MOD = 1000000007;\nconst jumps = [\n [4, 6],\n [6, 8],\n [7, 9],\n [4, 8],\n [3, 9, 0],\n [],\n [1, 7, 0],\n [2, 6],\n [1, 3],\n [2, 4]\n];\n\nfunction dp(remain, square) {\n if (remain === 0) {\n return 1;\n }\n \n if (memo[remain][square] !== undefined) {\n return memo[remain][square];\n }\n \n let ans = 0;\n for (let i = 0; i < jumps[square].length; i++) {\n let nextSquare = jumps[square][i];\n ans = (ans + dp(remain - 1, nextSquare)) % MOD;\n }\n \n memo[remain][square] = ans;\n return ans;\n}\n\nfunction knightDialer(n) {\n memo = new Array(n + 1).fill(null).map(() => new Array(10).fill(undefined));\n let ans = 0;\n for (let square = 0; square < 10; square++) {\n ans = (ans + dp(n - 1, square)) % MOD;\n }\n \n return ans;\n}\n\n\n\n```\n\n---\n#### ***Approach 3(Bottom-Up DP)***\n1. The problem considers a knight placed on a phone dial pad and aims to find the number of distinct numbers the knight can dial in \'n\' steps.\n1. The dial pad positions are represented as digits 0 to 9, and each digit has specific moves to other digits.\n1. The jumps vector represents the possible moves from each digit on the dial pad.\n1. The dp vector (dynamic programming) is used to store the counts of possible paths for each position and step.\n1. For each step from 1 to \'n\', it calculates the count of possible paths based on the previous step\'s counts and updates the dp vector accordingly.\n1. Finally, it sums up the counts of possible paths for all positions after \'n\' steps and returns the total count as the answer.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\n\n\nclass Solution {\npublic:\n int knightDialer(int n) {\n // Define the possible moves from each digit on the dial pad\n vector<vector<int>> jumps = {\n {4, 6},\n {6, 8},\n {7, 9},\n {4, 8},\n {3, 9, 0},\n {},\n {1, 7, 0},\n {2, 6},\n {1, 3},\n {2, 4}\n };\n\n int MOD = 1e9 + 7;\n vector<vector<int>> dp(n, vector<int>(10, 0)); // Initialize a 2D vector to store counts of possible paths for each position and step\n \n // For the first step (remain = 0), initialize all positions to 1\n for (int square = 0; square < 10; square++) {\n dp[0][square] = 1;\n }\n\n // Loop through each remaining step from step 1 to n - 1\n for (int remain = 1; remain < n; remain++) {\n for (int square = 0; square < 10; square++) {\n int ans = 0;\n // Calculate the count of possible paths for each position based on the previous step\'s counts\n for (int nextSquare : jumps[square]) {\n ans = (ans + dp[remain - 1][nextSquare]) % MOD;\n }\n\n dp[remain][square] = ans; // Store the count of possible paths for the current position and step\n }\n }\n\n int ans = 0;\n // Sum up the counts of possible paths for all positions after n steps\n for (int square = 0; square < 10; square++) {\n ans = (ans + dp[n - 1][square]) % MOD;\n }\n\n return ans; // Return the total count of possible paths after n steps\n }\n};\n\n\n\n```\n```C []\n\n\n#define MOD 1000000007\n\nint knightDialer(int n) {\n int jumps[10][3] = {\n {4, 6, -1},\n {6, 8, -1},\n {7, 9, -1},\n {4, 8, -1},\n {3, 9, 0},\n {-1, -1, -1},\n {1, 7, 0},\n {2, 6, -1},\n {1, 3, -1},\n {2, 4, -1}\n };\n\n int dp[n][10];\n for (int square = 0; square < 10; square++) {\n dp[0][square] = 1;\n }\n\n for (int remain = 1; remain < n; remain++) {\n for (int square = 0; square < 10; square++) {\n int ans = 0;\n for (int i = 0; jumps[square][i] != -1; i++) {\n int nextSquare = jumps[square][i];\n ans = (ans + dp[remain - 1][nextSquare]) % MOD;\n }\n\n dp[remain][square] = ans;\n }\n }\n\n int ans = 0;\n for (int square = 0; square < 10; square++) {\n ans = (ans + dp[n - 1][square]) % MOD;\n }\n\n return ans;\n}\n\n\n\n\n\n```\n\n```Java []\nclass Solution { \n public int knightDialer(int n) {\n int[][] jumps = {\n {4, 6},\n {6, 8},\n {7, 9},\n {4, 8},\n {3, 9, 0},\n {},\n {1, 7, 0},\n {2, 6},\n {1, 3},\n {2, 4}\n };\n \n int MOD = (int) 1e9 + 7;\n int[][] dp = new int[n][10];\n for (int square = 0; square < 10; square++) {\n dp[0][square] = 1;\n }\n \n for (int remain = 1; remain < n; remain++) {\n for (int square = 0; square < 10; square++) {\n int ans = 0;\n for (int nextSquare : jumps[square]) {\n ans = (ans + dp[remain - 1][nextSquare]) % MOD;\n }\n\n dp[remain][square] = ans;\n }\n }\n \n int ans = 0;\n for (int square = 0; square < 10; square++) {\n ans = (ans + dp[n - 1][square]) % MOD;\n }\n \n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def knightDialer(self, n: int) -> int:\n jumps = [\n [4, 6],\n [6, 8],\n [7, 9],\n [4, 8],\n [3, 9, 0],\n [],\n [1, 7, 0],\n [2, 6],\n [1, 3],\n [2, 4]\n ]\n \n MOD = 10 ** 9 + 7\n dp = [[0] * 10 for _ in range(n + 1)]\n for square in range(10):\n dp[0][square] = 1\n\n for remain in range(1, n):\n for square in range(10):\n ans = 0\n for next_square in jumps[square]:\n ans = (ans + dp[remain - 1][next_square]) % MOD\n \n dp[remain][square] = ans\n\n ans = 0\n for square in range(10):\n ans = (ans + dp[n - 1][square]) % MOD\n \n return ans\n\n\n```\n```javascript []\nfunction knightDialer(n) {\n const jumps = [\n [4, 6],\n [6, 8],\n [7, 9],\n [4, 8],\n [3, 9, 0],\n [],\n [1, 7, 0],\n [2, 6],\n [1, 3],\n [2, 4]\n ];\n\n const MOD = 1000000007;\n let dp = new Array(n).fill(null).map(() => new Array(10).fill(0));\n\n for (let square = 0; square < 10; square++) {\n dp[0][square] = 1;\n }\n\n for (let remain = 1; remain < n; remain++) {\n for (let square = 0; square < 10; square++) {\n let ans = 0;\n for (let i = 0; i < jumps[square].length; i++) {\n let nextSquare = jumps[square][i];\n ans = (ans + dp[remain - 1][nextSquare]) % MOD;\n }\n\n dp[remain][square] = ans;\n }\n }\n\n let ans = 0;\n for (let square = 0; square < 10; square++) {\n ans = (ans + dp[n - 1][square]) % MOD;\n }\n\n return ans;\n}\n\n\n```\n\n---\n#### ***Approach 4(Space Optimized DP)***\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 knight makes valid moves based on these buttons.\n1. The algorithm uses dynamic programming to calculate the number of possible paths the knight can take in \'n\' steps.\n1. It iterates through each step, updating the count of possible positions for each key/button based on the previous counts.\n1. At each step, it calculates the number of possible positions reachable from each key/button by summing the counts from its valid moves (as defined in the \'jumps\' vector).\n1. The \'dp\' array stores the counts for the current step, and \'prevDp\' stores the counts from the previous step to update for the next iteration.\n1. Finally, it returns the total count of possible positions after \'n\' steps by summing up the counts of all keys/buttons.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int knightDialer(int n) {\n // Define possible jumps for each key/button on the dial pad\n vector<vector<int>> jumps = {\n {4, 6},\n {6, 8},\n {7, 9},\n {4, 8},\n {3, 9, 0},\n {}, // Key \'5\' has no valid jumps\n {1, 7, 0},\n {2, 6},\n {1, 3},\n {2, 4}\n };\n\n int MOD = 1e9 + 7; // Modulo value for handling large numbers\n vector<int> dp(10, 0); // Array to store counts of possible positions for each key/button\n vector<int> prevDp(10, 1); // Array to store previous counts of possible positions\n\n for (int remain = 1; remain < n; remain++) {\n dp = vector<int>(10, 0); // Reset dp for each iteration\n // Calculate new counts for each key/button based on previous counts\n for (int square = 0; square < 10; square++) {\n int ans = 0;\n // Calculate the total number of possible positions for the current key/button\n for (int nextSquare : jumps[square]) {\n ans = (ans + prevDp[nextSquare]) % MOD;\n }\n dp[square] = ans; // Update the count of possible positions for the current key/button\n }\n prevDp = dp; // Update previous counts for the next iteration\n }\n\n int ans = 0;\n // Calculate the total count of possible positions after \'n\' steps\n for (int square = 0; square < 10; square++) {\n ans = (ans + prevDp[square]) % MOD;\n }\n\n return ans;\n }\n};\n\n\n\n```\n```C []\n\n\n#define MOD 1000000007\n\nint knightDialer(int n) {\n int jumps[10][3] = {\n {4, 6, -1},\n {6, 8, -1},\n {7, 9, -1},\n {4, 8, -1},\n {3, 9, 0},\n {-1, -1, -1},\n {1, 7, 0},\n {2, 6, -1},\n {1, 3, -1},\n {2, 4, -1}\n };\n\n int MOD = 1000000007;\n int dp[10] = {0};\n int prevDp[10] = {1};\n\n for (int remain = 1; remain < n; remain++) {\n int tempDp[10] = {0};\n for (int square = 0; square < 10; square++) {\n int ans = 0;\n for (int i = 0; jumps[square][i] != -1; i++) {\n int nextSquare = jumps[square][i];\n ans = (ans + prevDp[nextSquare]) % MOD;\n }\n\n tempDp[square] = ans;\n }\n \n for (int i = 0; i < 10; i++) {\n prevDp[i] = tempDp[i];\n }\n }\n\n int ans = 0;\n for (int square = 0; square < 10; square++) {\n ans = (ans + prevDp[square]) % MOD;\n }\n\n return ans;\n}\n\n\n\n\n\n```\n\n```Java []\nclass Solution { \n public int knightDialer(int n) {\n int[][] jumps = {\n {4, 6},\n {6, 8},\n {7, 9},\n {4, 8},\n {3, 9, 0},\n {},\n {1, 7, 0},\n {2, 6},\n {1, 3},\n {2, 4}\n };\n\n int MOD = (int) 1e9 + 7;\n int[] dp = new int[10];\n int[] prevDp = new int[10];\n Arrays.fill(prevDp, 1);\n\n for (int remain = 1; remain < n; remain++) {\n dp = new int[10];\n for (int square = 0; square < 10; square++) {\n int ans = 0;\n for (int nextSquare : jumps[square]) {\n ans = (ans + prevDp[nextSquare]) % MOD;\n }\n\n dp[square] = ans;\n }\n\n prevDp = dp;\n }\n\n int ans = 0;\n for (int square = 0; square < 10; square++) {\n ans = (ans + prevDp[square]) % MOD;\n }\n\n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def knightDialer(self, n: int) -> int:\n jumps = [\n [4, 6],\n [6, 8],\n [7, 9],\n [4, 8],\n [3, 9, 0],\n [],\n [1, 7, 0],\n [2, 6],\n [1, 3],\n [2, 4]\n ]\n \n MOD = 10 ** 9 + 7\n dp = [0] * 10\n prev_dp = [1] * 10\n \n for remain in range(1, n):\n dp = [0] * 10\n for square in range(10):\n ans = 0\n for next_square in jumps[square]:\n ans = (ans + prev_dp[next_square]) % MOD\n \n dp[square] = ans\n \n prev_dp = dp\n\n ans = 0\n for square in range(10):\n ans = (ans + prev_dp[square]) % MOD\n \n return ans\n\n\n```\n```javascript []\nfunction knightDialer(n) {\n const jumps = [\n [4, 6],\n [6, 8],\n [7, 9],\n [4, 8],\n [3, 9, 0],\n [],\n [1, 7, 0],\n [2, 6],\n [1, 3],\n [2, 4]\n ];\n\n const MOD = 1000000007;\n let dp = new Array(10).fill(0);\n let prevDp = new Array(10).fill(1);\n\n for (let remain = 1; remain < n; remain++) {\n let tempDp = new Array(10).fill(0);\n for (let square = 0; square < 10; square++) {\n let ans = 0;\n for (let i = 0; i < jumps[square].length; i++) {\n let nextSquare = jumps[square][i];\n ans = (ans + prevDp[nextSquare]) % MOD;\n }\n tempDp[square] = ans;\n }\n prevDp = tempDp;\n }\n\n let ans = 0;\n for (let square = 0; square < 10; square++) {\n ans = (ans + prevDp[square]) % MOD;\n }\n\n return ans;\n}\n\n\n\n```\n\n---\n#### ***Approach 5(Efficient Iteration On States Intuition)***\n1. **Initialization:** The code initially sets up the counts for each group of possible moves from different keys on the dial pad.\n1. **Loop:** It runs a loop \'n - 1\' times to update these counts based on previous counts.\n1. **Update Counts:** Each iteration updates the counts for groups A, B, C, and D according to the rules specified:\n - A is updated based on previous B and C counts.\n - B is updated using the previous count of A.\n - C is updated using previous counts of A and D.\n - D is updated using the previous count of C.\n1. **Final Calculation:** After the loop, it calculates the total count of possible positions by summing up the counts of all groups and applies modulo to handle large numbers.\n1. **Return:** The final count of possible positions after \'n\' steps is returned.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int knightDialer(int n) {\n // If n is 1, there are 10 possible starting positions for the knight.\n if (n == 1) {\n return 10;\n }\n \n // Define the initial counts for each of the four groups of possible moves.\n int A = 4; // Possible moves from keys 1, 3, 7, 9\n int B = 2; // Possible moves from keys 2, 8\n int C = 2; // Possible moves from keys 4, 6\n int D = 1; // Possible move from key 5\n int MOD = 1e9 + 7; // Modulo value for handling large numbers.\n \n // Iterate \'n - 1\' times to update the counts for each group of moves.\n for (int i = 0; i < n - 1; i++) {\n // Store temporary values for each group to update counts.\n int tempA = A;\n int tempB = B;\n int tempC = C;\n int tempD = D;\n \n // Update counts for each group based on previous counts.\n A = ((2 * tempB) % MOD + (2 * tempC) % MOD) % MOD;\n B = tempA;\n C = (tempA + (2 * tempD) % MOD) % MOD;\n D = tempC;\n }\n \n // Calculate the total count of possible positions by summing up all groups.\n int ans = (A + B) % MOD;\n ans = (ans + C) % MOD;\n return (ans + D) % MOD;\n }\n};\n\n\n\n```\n```C []\nint knightDialer(int n) {\n if (n == 1) {\n return 10;\n }\n \n int A = 4;\n int B = 2;\n int C = 2;\n int D = 1;\n int MOD = 1000000007;\n \n for (int i = 0; i < n - 1; i++) {\n int tempA = A;\n int tempB = B;\n int tempC = C;\n int tempD = D;\n \n A = ((2 * tempB) % MOD + (2 * tempC) % MOD) % MOD;\n B = tempA;\n C = (tempA + (2 * tempD) % MOD) % MOD;\n D = tempC;\n }\n \n int ans = (A + B) % MOD;\n ans = (ans + C) % MOD;\n return (ans + D) % MOD;\n}\n\n\n```\n\n```Java []\n\nclass Solution {\n public int knightDialer(int n) {\n if (n == 1) {\n return 10;\n }\n \n int A = 4;\n int B = 2;\n int C = 2;\n int D = 1;\n int MOD = (int) 1e9 + 7;\n \n for (int i = 0; i < n - 1; i++) {\n int tempA = A;\n int tempB = B;\n int tempC = C;\n int tempD = D;\n \n A = ((2 * tempB) % MOD + (2 * tempC) % MOD) % MOD;\n B = tempA;\n C = (tempA + (2 * tempD) % MOD) % MOD;\n D = tempC;\n }\n \n int ans = (A + B) % MOD;\n ans = (ans + C) % MOD;\n return (ans + D) % MOD;\n }\n}\n\n```\n```python3 []\nclass Solution:\n def knightDialer(self, n: int) -> int:\n if n == 1:\n return 10\n \n A = 4\n B = 2\n C = 2\n D = 1\n MOD = 10 ** 9 + 7\n \n for _ in range(n - 1):\n A, B, C, D = (2 * (B + C)) % MOD, A, (A + 2 * D) % MOD, C \n \n return (A + B + C + D) % MOD\n\n\n```\n```javascript []\nfunction knightDialer(n) {\n if (n === 1) {\n return 10;\n }\n \n let A = 4;\n let B = 2;\n let C = 2;\n let D = 1;\n const MOD = 1000000007;\n \n for (let i = 0; i < n - 1; i++) {\n let tempA = A;\n let tempB = B;\n let tempC = C;\n let tempD = D;\n \n A = ((2 * tempB) % MOD + (2 * tempC) % MOD) % MOD;\n B = tempA;\n C = (tempA + (2 * tempD) % MOD) % MOD;\n D = tempC;\n }\n \n let ans = (A + B) % MOD;\n ans = (ans + C) % MOD;\n return (ans + D) % MOD;\n}\n\n\n\n```\n\n---\n#### ***Approach 6(Linear Algebra)***\n\n1. This code aims to find the number of unique paths a knight can take on a phone dial pad in \'n\' steps using matrix exponentiation.\n1. The `knightDialer` function initializes the transition matrix `A` representing movements from one position on the dial pad to another.\n1. The vector `v` represents the count of paths for each position initially.\n1. It uses matrix exponentiation to efficiently compute the count of paths after `n` steps. The `multiply` function performs matrix multiplication to update the path count.\n1. Finally, it calculates the total count of paths after `n` steps and returns the result.\n\n\n\n\n\n# Complexity\n- *Time complexity:*\n $$O(logn)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int MOD = 1e9 + 7; // Constant value for modulo arithmetic\n \n // Function to compute the number of paths for a knight dialer\n int knightDialer(int n) {\n if (n == 1) {\n return 10; // If n is 1, there are 10 possible starting positions for the knight.\n }\n \n // Matrix representing the transitions between positions on the dial pad\n vector<vector<long>> A = {\n {0, 0, 0, 0, 1, 0, 1, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 1, 0, 1, 0},\n {0, 0, 0, 0, 0, 0, 0, 1, 0, 1},\n {0, 0, 0, 0, 1, 0, 0, 0, 1, 0},\n {1, 0, 0, 1, 0, 0, 0, 0, 0, 1},\n {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n {1, 1, 0, 0, 0, 0, 0, 1, 0, 0},\n {0, 0, 1, 0, 0, 0, 1, 0, 0, 0},\n {0, 1, 0, 1, 0, 0, 0, 0, 0, 0},\n {0, 0, 1, 0, 1, 0, 0, 0, 0, 0}\n };\n \n // Initial vector representing the count of paths for each position on the dial pad\n vector<vector<long>> v = {\n {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} // For the first step (n = 1)\n };\n \n n--; // Decrementing n since we already accounted for n = 1\n \n // Applying matrix exponentiation to compute the count of paths after n steps\n while (n > 0) {\n if ((n & 1) != 0) {\n v = multiply(v, A); // Multiply the matrix v with matrix A\n }\n \n A = multiply(A, A); // Square matrix A for the next step\n n >>= 1; // Right shift n to prepare for the next step\n }\n \n int ans = 0;\n // Calculating the total count of paths after n steps\n for (long num : v[0]) {\n ans = (ans + num) % MOD;\n }\n \n return ans;\n }\n \n // Function to perform matrix multiplication\n vector<vector<long>> multiply(vector<vector<long>>& A, vector<vector<long>>& B) {\n vector<vector<long>> result(A.size(), vector<long>(B[0].size(), 0));\n \n for (int i = 0; i < A.size(); i++) {\n for (int j = 0; j < B[0].size(); j++) {\n for (int k = 0; k < B.size(); k++) {\n result[i][j] = (result[i][j] + A[i][k] * B[k][j]) % MOD;\n }\n }\n }\n \n return result;\n }\n};\n\n\n\n```\n```C []\n#define MOD 1000000007\n\nint knightDialer(int n) {\n if (n == 1) {\n return 10;\n }\n \n long A[10][10] = {\n {0, 0, 0, 0, 1, 0, 1, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 1, 0, 1, 0},\n {0, 0, 0, 0, 0, 0, 0, 1, 0, 1},\n {0, 0, 0, 0, 1, 0, 0, 0, 1, 0},\n {1, 0, 0, 1, 0, 0, 0, 0, 0, 1},\n {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n {1, 1, 0, 0, 0, 0, 0, 1, 0, 0},\n {0, 0, 1, 0, 0, 0, 1, 0, 0, 0},\n {0, 1, 0, 1, 0, 0, 0, 0, 0, 0},\n {0, 0, 1, 0, 1, 0, 0, 0, 0, 0}\n };\n \n long v[1][10] = {\n {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}\n };\n \n n--;\n while (n > 0) {\n if ((n & 1) != 0) {\n long temp[1][10];\n for (int i = 0; i < 10; i++) {\n temp[0][i] = 0;\n for (int j = 0; j < 10; j++) {\n temp[0][i] = (temp[0][i] + v[0][j] * A[j][i]) % MOD;\n }\n }\n for (int i = 0; i < 10; i++) {\n v[0][i] = temp[0][i];\n }\n }\n \n long temp[10][10];\n for (int i = 0; i < 10; i++) {\n for (int j = 0; j < 10; j++) {\n temp[i][j] = 0;\n for (int k = 0; k < 10; k++) {\n temp[i][j] = (temp[i][j] + A[i][k] * A[k][j]) % MOD;\n }\n }\n }\n for (int i = 0; i < 10; i++) {\n for (int j = 0; j < 10; j++) {\n A[i][j] = temp[i][j];\n }\n }\n n >>= 1;\n }\n \n int ans = 0;\n for (int i = 0; i < 10; i++) {\n ans = (ans + v[0][i]) % MOD;\n }\n \n return ans;\n}\n\n\n```\n\n```Java []\npublic class Solution {\n\n static final int MOD = 1000000007;\n\n public int knightDialer(int n) {\n if (n == 1) {\n return 10;\n }\n\n int[][] A = {\n {0, 0, 0, 0, 1, 0, 1, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 1, 0, 1, 0},\n {0, 0, 0, 0, 0, 0, 0, 1, 0, 1},\n {0, 0, 0, 0, 1, 0, 0, 0, 1, 0},\n {1, 0, 0, 1, 0, 0, 0, 0, 0, 1},\n {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n {1, 1, 0, 0, 0, 0, 0, 1, 0, 0},\n {0, 0, 1, 0, 0, 0, 1, 0, 0, 0},\n {0, 1, 0, 1, 0, 0, 0, 0, 0, 0},\n {0, 0, 1, 0, 1, 0, 0, 0, 0, 0}\n };\n\n int[] v = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};\n\n n--;\n while (n > 0) {\n if ((n & 1) != 0) {\n int[] temp = new int[10];\n for (int i = 0; i < 10; i++) {\n for (int j = 0; j < 10; j++) {\n temp[i] = (int)((temp[i] + (long)v[j] * A[j][i]) % MOD);\n }\n }\n v = temp.clone();\n }\n\n int[][] temp = new int[10][10];\n for (int i = 0; i < 10; i++) {\n for (int j = 0; j < 10; j++) {\n for (int k = 0; k < 10; k++) {\n temp[i][j] = (int)((temp[i][j] + (long)A[i][k] * A[k][j]) % MOD);\n }\n }\n }\n A = temp.clone();\n n >>= 1;\n }\n\n int ans = 0;\n for (int i = 0; i < 10; i++) {\n ans = (ans + v[i]) % MOD;\n }\n\n return ans;\n }\n\n public static void main(String[] args) {\n int n = 4; // Example: calculating for n = 4\n Solution solution = new Solution();\n int result = solution.knightDialer(n);\n System.out.println(result); // Printing the result\n }\n}\n\n\n\n```\n```python3 []\nclass Solution:\n def knightDialer(self, n: int) -> int:\n if n == 1:\n return 10\n \n def multiply(A, B):\n result = [[0] * len(B[0]) for _ in range(len(A))]\n \n for i in range(len(A)):\n for j in range(len(B[0])):\n for k in range(len(B)):\n result[i][j] = (result[i][j] + A[i][k] * B[k][j]) % MOD\n \n return result\n\n A = [\n [0, 0, 0, 0, 1, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0, 1, 0],\n [0, 0, 0, 0, 0, 0, 0, 1, 0, 1],\n [0, 0, 0, 0, 1, 0, 0, 0, 1, 0],\n [1, 0, 0, 1, 0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 1, 0, 0, 0, 1, 0, 0, 0],\n [0, 1, 0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 1, 0, 0, 0, 0, 0]\n ]\n \n v = [[1] * 10]\n MOD = 10 ** 9 + 7\n\n n -= 1\n while n:\n if n & 1:\n v = multiply(v, A)\n \n A = multiply(A, A)\n n >>= 1\n\n return sum(v[0]) % MOD\n\n\n```\n```javascript []\nfunction knightDialer(n) {\n if (n === 1) {\n return 10;\n }\n\n const MOD = 1000000007;\n const A = [\n [0, 0, 0, 0, 1, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0, 1, 0],\n [0, 0, 0, 0, 0, 0, 0, 1, 0, 1],\n [0, 0, 0, 0, 1, 0, 0, 0, 1, 0],\n [1, 0, 0, 1, 0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 1, 0, 0, 0, 1, 0, 0, 0],\n [0, 1, 0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 1, 0, 0, 0, 0, 0]\n ];\n\n let v = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1];\n\n n--;\n while (n > 0) {\n if ((n & 1) !== 0) {\n const temp = Array(10).fill(0);\n for (let i = 0; i < 10; i++) {\n for (let j = 0; j < 10; j++) {\n temp[i] = (temp[i] + v[j] * A[j][i]) % MOD;\n }\n }\n for (let i = 0; i < 10; i++) {\n v[i] = temp[i];\n }\n }\n\n const temp = Array.from(Array(10), () => Array(10).fill(0));\n for (let i = 0; i < 10; i++) {\n for (let j = 0; j < 10; j++) {\n for (let k = 0; k < 10; k++) {\n temp[i][j] = (temp[i][j] + A[i][k] * A[k][j]) % MOD;\n }\n }\n }\n for (let i = 0; i < 10; i++) {\n for (let j = 0; j < 10; j++) {\n A[i][j] = temp[i][j];\n }\n }\n n >>= 1;\n }\n\n let ans = 0;\n for (let i = 0; i < 10; i++) {\n ans = (ans + v[i]) % MOD;\n }\n\n return ans;\n}\n\n\n\n```\n\n---\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n--- | 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 chess diagram below:
We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell).
Given an integer `n`, return how many distinct phone numbers of length `n` we can dial.
You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps.
As the answer may be very large, **return the answer modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 10
**Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
**Example 2:**
**Input:** n = 2
**Output:** 20
**Explanation:** All the valid number we can dial are \[04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94\]
**Example 3:**
**Input:** n = 3131
**Output:** 136006598
**Explanation:** Please take care of the mod.
**Constraints:**
* `1 <= n <= 5000` | 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 knight makes valid moves based on these buttons.\n1. For each digit (`key`), there are specific other digits (buttons) the knight can move to.\n1. The algorithm uses dynamic programming to calculate the number of possible paths the knight can take in `n` steps.\n1. It iterates through each step, updating the count of possible positions based on the available moves for each `key`.\n1. Finally, it returns the total count of possible positions after `n` steps.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\n\n\nclass Solution {\npublic:\n int knightDialer(int n) {\n if(n == 1) return 10; // If n is 1, there are 10 possible starting positions for the knight.\n\n unordered_map<int, vector<int>> mp; // Map to store the possible moves for each key/button on the dial pad.\n int MOD = 1000000007; // Modulo value for handling large numbers.\n\n // Assigning possible moves for each key/button on the dial pad.\n mp[0] = {4, 6};\n mp[1] = {6, 8};\n mp[2] = {7, 9};\n mp[3] = {4, 8};\n mp[4] = {0, 3, 9};\n mp[6] = {0, 1, 7};\n mp[7] = {2, 6};\n mp[8] = {1, 3};\n mp[9] = {2, 4};\n\n vector<int> v(10, 1); // Initializing a vector to store counts of possible positions.\n for(int i = 2; i <= n; i++) { // Looping from 2 to n to calculate the count of possible positions for each step.\n vector<int> temp(10); // Temporary vector to store updated counts for each key/button.\n for(auto [key, val] : mp) { // Iterating through the dial pad keys.\n for(auto j : val) { // Iterating through possible moves for each key.\n temp[key] = (temp[key] + v[j]) % MOD; // Updating counts for each key/button based on possible moves.\n }\n }\n v = temp; // Updating the counts after each step.\n }\n\n int ans = 0;\n for(auto a : v) {\n ans = (ans + a) % MOD; // Calculating the total count of possible positions after n steps.\n }\n return ans;\n }\n};\n\n\n\n```\n```C []\n\n\n#define MOD 1000000007\n\nint knightDialer(int n) {\n if (n == 1) return 10; // If n is 1, there are 10 possible starting positions for the knight.\n\n int moves[10][2] = { {4, 6}, {6, 8}, {7, 9}, {4, 8}, {0, 3, 9}, {-1, -1}, {0, 1, 7}, {2, 6}, {1, 3}, {2, 4} }; // Array to store the possible moves for each key/button on the dial pad.\n int v[10] = {1, 1, 1, 1, 1, 0, 1, 1, 1, 1}; // Array to store counts of possible positions.\n int i, j, k;\n\n for (i = 2; i <= n; i++) { // Looping from 2 to n to calculate the count of possible positions for each step.\n int temp[10] = {0}; // Temporary array to store updated counts for each key/button.\n\n for (j = 0; j < 10; j++) { // Iterating through the dial pad keys.\n if (moves[j][0] != -1) {\n for (k = 0; moves[j][k] != -1; k++) { // Iterating through possible moves for each key.\n temp[j] = (temp[j] + v[moves[j][k]]) % MOD; // Updating counts for each key/button based on possible moves.\n }\n }\n }\n\n for (j = 0; j < 10; j++) {\n v[j] = temp[j]; // Updating the counts after each step.\n }\n }\n\n int ans = 0;\n for (i = 0; i < 10; i++) {\n ans = (ans + v[i]) % MOD; // Calculating the total count of possible positions after n steps.\n }\n return ans;\n}\n\n\n```\n\n```Java []\n\nclass Solution {\n public int knightDialer(int n) {\n if (n == 1) {\n return 10; // If n is 1, there are 10 possible starting positions for the knight.\n }\n\n // Map to store the possible moves for each key/button on the dial pad.\n Map<Integer, List<Integer>> mp = new HashMap<>();\n mp.put(0, Arrays.asList(4, 6));\n mp.put(1, Arrays.asList(6, 8));\n mp.put(2, Arrays.asList(7, 9));\n mp.put(3, Arrays.asList(4, 8));\n mp.put(4, Arrays.asList(0, 3, 9));\n mp.put(6, Arrays.asList(0, 1, 7));\n mp.put(7, Arrays.asList(2, 6));\n mp.put(8, Arrays.asList(1, 3));\n mp.put(9, Arrays.asList(2, 4));\n\n int MOD = 1000000007; // Modulo value for handling large numbers.\n int[] v = new int[10]; // Initializing an array to store counts of possible positions.\n Arrays.fill(v, 1);\n\n for (int i = 2; i <= n; i++) {\n int[] temp = new int[10]; // Temporary array to store updated counts for each key/button.\n for (Map.Entry<Integer, List<Integer>> entry : mp.entrySet()) {\n int key = entry.getKey();\n List<Integer> val = entry.getValue();\n for (int j : val) {\n temp[key] = (temp[key] + v[j]) % MOD; // Updating counts for each key/button based on possible moves.\n }\n }\n v = temp; // Updating the counts after each step.\n }\n\n int ans = 0;\n for (int a : v) {\n ans = (ans + a) % MOD; // Calculating the total count of possible positions after n steps.\n }\n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def knightDialer(self, n: int) -> int:\n if n == 1:\n return 10 # If n is 1, there are 10 possible starting positions for the knight.\n\n # Map to store possible moves for each key/button on the dial pad.\n mp = {\n 0: [4, 6],\n 1: [6, 8],\n 2: [7, 9],\n 3: [4, 8],\n 4: [0, 3, 9],\n 6: [0, 1, 7],\n 7: [2, 6],\n 8: [1, 3],\n 9: [2, 4]\n }\n \n MOD = 10**9 + 7 # Modulo value for handling large numbers.\n v = [1] * 10 # Initializing a list to store counts of possible positions.\n\n for i in range(2, n + 1):\n temp = [0] * 10 # Temporary list to store updated counts for each key/button.\n for key, val in mp.items():\n for j in val:\n temp[key] = (temp[key] + v[j]) % MOD # Updating counts for each key/button based on possible moves.\n v = temp # Updating the counts after each step.\n\n return sum(v) % MOD # Calculating the total count of possible positions after n steps.\n\n\n\n```\n```javascript []\nvar knightDialer = function(n) {\n if (n === 1) return 10; // If n is 1, there are 10 possible starting positions for the knight.\n\n const mp = new Map(); // Map to store the possible moves for each key/button on the dial pad.\n const MOD = 1000000007; // Modulo value for handling large numbers.\n\n // Assigning possible moves for each key/button on the dial pad.\n mp.set(0, [4, 6]);\n mp.set(1, [6, 8]);\n mp.set(2, [7, 9]);\n mp.set(3, [4, 8]);\n mp.set(4, [0, 3, 9]);\n mp.set(6, [0, 1, 7]);\n mp.set(7, [2, 6]);\n mp.set(8, [1, 3]);\n mp.set(9, [2, 4]);\n\n let v = Array(10).fill(1); // Initializing an array to store counts of possible positions.\n for (let i = 2; i <= n; i++) { // Looping from 2 to n to calculate the count of possible positions for each step.\n const temp = Array(10).fill(0); // Temporary array to store updated counts for each key/button.\n for (const [key, val] of mp) { // Iterating through the dial pad keys.\n for (const j of val) { // Iterating through possible moves for each key.\n temp[key] = (temp[key] + v[j]) % MOD; // Updating counts for each key/button based on possible moves.\n }\n }\n v = [...temp]; // Updating the counts after each step.\n }\n\n let ans = 0;\n for (const a of v) {\n ans = (ans + a) % MOD; // Calculating the total count of possible positions after n steps.\n }\n return ans;\n};\n\n\n```\n\n---\n#### ***Approach 2(Top-Down DP)***\n1. The code uses a recursive approach with memoization to count the number of possible moves a knight can make on a phone dial pad in `n` steps.\n1. The `jumps` array holds the possible moves for each digit on the dial pad (representing a square).\n1. The `dp` function performs a recursive depth-first search (DFS) to calculate the number of moves remaining from a specific square, considering all possible next squares based on valid knight moves.\n1. `memo` is a memoization table used to store and retrieve already computed results to avoid redundant calculations.\n1. The `knightDialer` function initializes the memoization array and iterates through each starting square, computing the total number of moves for `n` steps.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\n\n\nclass Solution {\npublic:\n // Memoization array to store computed results\n vector<vector<int>> memo;\n int n; // Input value \'n\'\n int MOD = 1e9 + 7; // Modulo value for handling large numbers\n // Possible jumps for each digit (representing a square on the dial pad)\n vector<vector<int>> jumps = {\n {4, 6},\n {6, 8},\n {7, 9},\n {4, 8},\n {3, 9, 0},\n {},\n {1, 7, 0},\n {2, 6},\n {1, 3},\n {2, 4}\n };\n \n // Recursive function to calculate the number of moves\n int dp(int remain, int square) {\n if (remain == 0) {\n return 1; // If no more steps remain, return 1 (indicating a valid path)\n }\n \n if (memo[remain][square] != 0) {\n return memo[remain][square]; // If the value is already calculated, return it\n }\n \n int ans = 0;\n // Recursively calculate the number of moves for each next square\n for (int nextSquare : jumps[square]) {\n ans = (ans + dp(remain - 1, nextSquare)) % MOD; // Add the count of possible moves\n }\n \n memo[remain][square] = ans; // Store the computed result in the memoization array\n return ans; // Return the total count of possible moves\n }\n \n // Main function to calculate the number of possible moves for \'n\' steps\n int knightDialer(int n) {\n this->n = n;\n memo = vector(n + 1, vector<int>(10, 0)); // Initialize memoization array\n int ans = 0;\n // Calculate the total number of moves for each starting square\n for (int square = 0; square < 10; square++) {\n ans = (ans + dp(n - 1, square)) % MOD; // Add the count of possible moves for each starting square\n }\n \n return ans; // Return the total count of possible moves after \'n\' steps\n }\n};\n\n\n\n```\n```C []\n#define MOD 1000000007\n\nint memo[501][10] = {{0}};\nint n;\nint jumps[10][3] = {\n {4, 6, -1},\n {6, 8, -1},\n {7, 9, -1},\n {4, 8, -1},\n {3, 9, 0},\n {-1, -1, -1},\n {1, 7, 0},\n {2, 6, -1},\n {1, 3, -1},\n {2, 4, -1}\n};\n\nint dp(int remain, int square) {\n if (remain == 0) {\n return 1;\n }\n \n if (memo[remain][square] != 0) {\n return memo[remain][square];\n }\n \n int ans = 0;\n for (int i = 0; jumps[square][i] != -1; i++) {\n int nextSquare = jumps[square][i];\n ans = (ans + dp(remain - 1, nextSquare)) % MOD;\n }\n \n memo[remain][square] = ans;\n return ans;\n}\n\nint knightDialer(int n) {\n int ans = 0;\n for (int square = 0; square < 10; square++) {\n ans = (ans + dp(n - 1, square)) % MOD;\n }\n \n return ans;\n}\n\n\n```\n\n```Java []\nclass Solution {\n int[][] memo;\n int n;\n int MOD = (int) 1e9 + 7;\n int[][] jumps = {\n {4, 6},\n {6, 8},\n {7, 9},\n {4, 8},\n {3, 9, 0},\n {},\n {1, 7, 0},\n {2, 6},\n {1, 3},\n {2, 4}\n };\n \n public int dp(int remain, int square) {\n if (remain == 0) {\n return 1;\n }\n \n if (memo[remain][square] != 0) {\n return memo[remain][square];\n }\n \n int ans = 0;\n for (int nextSquare : jumps[square]) {\n ans = (ans + dp(remain - 1, nextSquare)) % MOD;\n }\n \n memo[remain][square] = ans;\n return ans;\n }\n \n public int knightDialer(int n) {\n this.n = n;\n memo = new int[n + 1][10];\n int ans = 0;\n for (int square = 0; square < 10; square++) {\n ans = (ans + dp(n - 1, square)) % MOD;\n }\n \n return ans;\n }\n}\n\n\n```\n```python3 []\n\nclass Solution:\n def knightDialer(self, n: int) -> int:\n @cache\n def dp(remain, square):\n if remain == 0:\n return 1\n \n ans = 0\n for next_square in jumps[square]:\n ans = (ans + dp(remain - 1, next_square)) % MOD\n \n return ans\n \n jumps = [\n [4, 6],\n [6, 8],\n [7, 9],\n [4, 8],\n [3, 9, 0],\n [],\n [1, 7, 0],\n [2, 6],\n [1, 3],\n [2, 4]\n ]\n\n ans = 0\n MOD = 10 ** 9 + 7\n for square in range(10):\n ans = (ans + dp(n - 1, square)) % MOD\n \n return ans\n\n```\n```javascript []\nlet memo = [];\nlet n;\nconst MOD = 1000000007;\nconst jumps = [\n [4, 6],\n [6, 8],\n [7, 9],\n [4, 8],\n [3, 9, 0],\n [],\n [1, 7, 0],\n [2, 6],\n [1, 3],\n [2, 4]\n];\n\nfunction dp(remain, square) {\n if (remain === 0) {\n return 1;\n }\n \n if (memo[remain][square] !== undefined) {\n return memo[remain][square];\n }\n \n let ans = 0;\n for (let i = 0; i < jumps[square].length; i++) {\n let nextSquare = jumps[square][i];\n ans = (ans + dp(remain - 1, nextSquare)) % MOD;\n }\n \n memo[remain][square] = ans;\n return ans;\n}\n\nfunction knightDialer(n) {\n memo = new Array(n + 1).fill(null).map(() => new Array(10).fill(undefined));\n let ans = 0;\n for (let square = 0; square < 10; square++) {\n ans = (ans + dp(n - 1, square)) % MOD;\n }\n \n return ans;\n}\n\n\n\n```\n\n---\n#### ***Approach 3(Bottom-Up DP)***\n1. The problem considers a knight placed on a phone dial pad and aims to find the number of distinct numbers the knight can dial in \'n\' steps.\n1. The dial pad positions are represented as digits 0 to 9, and each digit has specific moves to other digits.\n1. The jumps vector represents the possible moves from each digit on the dial pad.\n1. The dp vector (dynamic programming) is used to store the counts of possible paths for each position and step.\n1. For each step from 1 to \'n\', it calculates the count of possible paths based on the previous step\'s counts and updates the dp vector accordingly.\n1. Finally, it sums up the counts of possible paths for all positions after \'n\' steps and returns the total count as the answer.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(n)$$\n \n\n\n# Code\n```C++ []\n\n\nclass Solution {\npublic:\n int knightDialer(int n) {\n // Define the possible moves from each digit on the dial pad\n vector<vector<int>> jumps = {\n {4, 6},\n {6, 8},\n {7, 9},\n {4, 8},\n {3, 9, 0},\n {},\n {1, 7, 0},\n {2, 6},\n {1, 3},\n {2, 4}\n };\n\n int MOD = 1e9 + 7;\n vector<vector<int>> dp(n, vector<int>(10, 0)); // Initialize a 2D vector to store counts of possible paths for each position and step\n \n // For the first step (remain = 0), initialize all positions to 1\n for (int square = 0; square < 10; square++) {\n dp[0][square] = 1;\n }\n\n // Loop through each remaining step from step 1 to n - 1\n for (int remain = 1; remain < n; remain++) {\n for (int square = 0; square < 10; square++) {\n int ans = 0;\n // Calculate the count of possible paths for each position based on the previous step\'s counts\n for (int nextSquare : jumps[square]) {\n ans = (ans + dp[remain - 1][nextSquare]) % MOD;\n }\n\n dp[remain][square] = ans; // Store the count of possible paths for the current position and step\n }\n }\n\n int ans = 0;\n // Sum up the counts of possible paths for all positions after n steps\n for (int square = 0; square < 10; square++) {\n ans = (ans + dp[n - 1][square]) % MOD;\n }\n\n return ans; // Return the total count of possible paths after n steps\n }\n};\n\n\n\n```\n```C []\n\n\n#define MOD 1000000007\n\nint knightDialer(int n) {\n int jumps[10][3] = {\n {4, 6, -1},\n {6, 8, -1},\n {7, 9, -1},\n {4, 8, -1},\n {3, 9, 0},\n {-1, -1, -1},\n {1, 7, 0},\n {2, 6, -1},\n {1, 3, -1},\n {2, 4, -1}\n };\n\n int dp[n][10];\n for (int square = 0; square < 10; square++) {\n dp[0][square] = 1;\n }\n\n for (int remain = 1; remain < n; remain++) {\n for (int square = 0; square < 10; square++) {\n int ans = 0;\n for (int i = 0; jumps[square][i] != -1; i++) {\n int nextSquare = jumps[square][i];\n ans = (ans + dp[remain - 1][nextSquare]) % MOD;\n }\n\n dp[remain][square] = ans;\n }\n }\n\n int ans = 0;\n for (int square = 0; square < 10; square++) {\n ans = (ans + dp[n - 1][square]) % MOD;\n }\n\n return ans;\n}\n\n\n\n\n\n```\n\n```Java []\nclass Solution { \n public int knightDialer(int n) {\n int[][] jumps = {\n {4, 6},\n {6, 8},\n {7, 9},\n {4, 8},\n {3, 9, 0},\n {},\n {1, 7, 0},\n {2, 6},\n {1, 3},\n {2, 4}\n };\n \n int MOD = (int) 1e9 + 7;\n int[][] dp = new int[n][10];\n for (int square = 0; square < 10; square++) {\n dp[0][square] = 1;\n }\n \n for (int remain = 1; remain < n; remain++) {\n for (int square = 0; square < 10; square++) {\n int ans = 0;\n for (int nextSquare : jumps[square]) {\n ans = (ans + dp[remain - 1][nextSquare]) % MOD;\n }\n\n dp[remain][square] = ans;\n }\n }\n \n int ans = 0;\n for (int square = 0; square < 10; square++) {\n ans = (ans + dp[n - 1][square]) % MOD;\n }\n \n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def knightDialer(self, n: int) -> int:\n jumps = [\n [4, 6],\n [6, 8],\n [7, 9],\n [4, 8],\n [3, 9, 0],\n [],\n [1, 7, 0],\n [2, 6],\n [1, 3],\n [2, 4]\n ]\n \n MOD = 10 ** 9 + 7\n dp = [[0] * 10 for _ in range(n + 1)]\n for square in range(10):\n dp[0][square] = 1\n\n for remain in range(1, n):\n for square in range(10):\n ans = 0\n for next_square in jumps[square]:\n ans = (ans + dp[remain - 1][next_square]) % MOD\n \n dp[remain][square] = ans\n\n ans = 0\n for square in range(10):\n ans = (ans + dp[n - 1][square]) % MOD\n \n return ans\n\n\n```\n```javascript []\nfunction knightDialer(n) {\n const jumps = [\n [4, 6],\n [6, 8],\n [7, 9],\n [4, 8],\n [3, 9, 0],\n [],\n [1, 7, 0],\n [2, 6],\n [1, 3],\n [2, 4]\n ];\n\n const MOD = 1000000007;\n let dp = new Array(n).fill(null).map(() => new Array(10).fill(0));\n\n for (let square = 0; square < 10; square++) {\n dp[0][square] = 1;\n }\n\n for (let remain = 1; remain < n; remain++) {\n for (let square = 0; square < 10; square++) {\n let ans = 0;\n for (let i = 0; i < jumps[square].length; i++) {\n let nextSquare = jumps[square][i];\n ans = (ans + dp[remain - 1][nextSquare]) % MOD;\n }\n\n dp[remain][square] = ans;\n }\n }\n\n let ans = 0;\n for (let square = 0; square < 10; square++) {\n ans = (ans + dp[n - 1][square]) % MOD;\n }\n\n return ans;\n}\n\n\n```\n\n---\n#### ***Approach 4(Space Optimized DP)***\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 knight makes valid moves based on these buttons.\n1. The algorithm uses dynamic programming to calculate the number of possible paths the knight can take in \'n\' steps.\n1. It iterates through each step, updating the count of possible positions for each key/button based on the previous counts.\n1. At each step, it calculates the number of possible positions reachable from each key/button by summing the counts from its valid moves (as defined in the \'jumps\' vector).\n1. The \'dp\' array stores the counts for the current step, and \'prevDp\' stores the counts from the previous step to update for the next iteration.\n1. Finally, it returns the total count of possible positions after \'n\' steps by summing up the counts of all keys/buttons.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int knightDialer(int n) {\n // Define possible jumps for each key/button on the dial pad\n vector<vector<int>> jumps = {\n {4, 6},\n {6, 8},\n {7, 9},\n {4, 8},\n {3, 9, 0},\n {}, // Key \'5\' has no valid jumps\n {1, 7, 0},\n {2, 6},\n {1, 3},\n {2, 4}\n };\n\n int MOD = 1e9 + 7; // Modulo value for handling large numbers\n vector<int> dp(10, 0); // Array to store counts of possible positions for each key/button\n vector<int> prevDp(10, 1); // Array to store previous counts of possible positions\n\n for (int remain = 1; remain < n; remain++) {\n dp = vector<int>(10, 0); // Reset dp for each iteration\n // Calculate new counts for each key/button based on previous counts\n for (int square = 0; square < 10; square++) {\n int ans = 0;\n // Calculate the total number of possible positions for the current key/button\n for (int nextSquare : jumps[square]) {\n ans = (ans + prevDp[nextSquare]) % MOD;\n }\n dp[square] = ans; // Update the count of possible positions for the current key/button\n }\n prevDp = dp; // Update previous counts for the next iteration\n }\n\n int ans = 0;\n // Calculate the total count of possible positions after \'n\' steps\n for (int square = 0; square < 10; square++) {\n ans = (ans + prevDp[square]) % MOD;\n }\n\n return ans;\n }\n};\n\n\n\n```\n```C []\n\n\n#define MOD 1000000007\n\nint knightDialer(int n) {\n int jumps[10][3] = {\n {4, 6, -1},\n {6, 8, -1},\n {7, 9, -1},\n {4, 8, -1},\n {3, 9, 0},\n {-1, -1, -1},\n {1, 7, 0},\n {2, 6, -1},\n {1, 3, -1},\n {2, 4, -1}\n };\n\n int MOD = 1000000007;\n int dp[10] = {0};\n int prevDp[10] = {1};\n\n for (int remain = 1; remain < n; remain++) {\n int tempDp[10] = {0};\n for (int square = 0; square < 10; square++) {\n int ans = 0;\n for (int i = 0; jumps[square][i] != -1; i++) {\n int nextSquare = jumps[square][i];\n ans = (ans + prevDp[nextSquare]) % MOD;\n }\n\n tempDp[square] = ans;\n }\n \n for (int i = 0; i < 10; i++) {\n prevDp[i] = tempDp[i];\n }\n }\n\n int ans = 0;\n for (int square = 0; square < 10; square++) {\n ans = (ans + prevDp[square]) % MOD;\n }\n\n return ans;\n}\n\n\n\n\n\n```\n\n```Java []\nclass Solution { \n public int knightDialer(int n) {\n int[][] jumps = {\n {4, 6},\n {6, 8},\n {7, 9},\n {4, 8},\n {3, 9, 0},\n {},\n {1, 7, 0},\n {2, 6},\n {1, 3},\n {2, 4}\n };\n\n int MOD = (int) 1e9 + 7;\n int[] dp = new int[10];\n int[] prevDp = new int[10];\n Arrays.fill(prevDp, 1);\n\n for (int remain = 1; remain < n; remain++) {\n dp = new int[10];\n for (int square = 0; square < 10; square++) {\n int ans = 0;\n for (int nextSquare : jumps[square]) {\n ans = (ans + prevDp[nextSquare]) % MOD;\n }\n\n dp[square] = ans;\n }\n\n prevDp = dp;\n }\n\n int ans = 0;\n for (int square = 0; square < 10; square++) {\n ans = (ans + prevDp[square]) % MOD;\n }\n\n return ans;\n }\n}\n\n\n```\n```python3 []\nclass Solution:\n def knightDialer(self, n: int) -> int:\n jumps = [\n [4, 6],\n [6, 8],\n [7, 9],\n [4, 8],\n [3, 9, 0],\n [],\n [1, 7, 0],\n [2, 6],\n [1, 3],\n [2, 4]\n ]\n \n MOD = 10 ** 9 + 7\n dp = [0] * 10\n prev_dp = [1] * 10\n \n for remain in range(1, n):\n dp = [0] * 10\n for square in range(10):\n ans = 0\n for next_square in jumps[square]:\n ans = (ans + prev_dp[next_square]) % MOD\n \n dp[square] = ans\n \n prev_dp = dp\n\n ans = 0\n for square in range(10):\n ans = (ans + prev_dp[square]) % MOD\n \n return ans\n\n\n```\n```javascript []\nfunction knightDialer(n) {\n const jumps = [\n [4, 6],\n [6, 8],\n [7, 9],\n [4, 8],\n [3, 9, 0],\n [],\n [1, 7, 0],\n [2, 6],\n [1, 3],\n [2, 4]\n ];\n\n const MOD = 1000000007;\n let dp = new Array(10).fill(0);\n let prevDp = new Array(10).fill(1);\n\n for (let remain = 1; remain < n; remain++) {\n let tempDp = new Array(10).fill(0);\n for (let square = 0; square < 10; square++) {\n let ans = 0;\n for (let i = 0; i < jumps[square].length; i++) {\n let nextSquare = jumps[square][i];\n ans = (ans + prevDp[nextSquare]) % MOD;\n }\n tempDp[square] = ans;\n }\n prevDp = tempDp;\n }\n\n let ans = 0;\n for (let square = 0; square < 10; square++) {\n ans = (ans + prevDp[square]) % MOD;\n }\n\n return ans;\n}\n\n\n\n```\n\n---\n#### ***Approach 5(Efficient Iteration On States Intuition)***\n1. **Initialization:** The code initially sets up the counts for each group of possible moves from different keys on the dial pad.\n1. **Loop:** It runs a loop \'n - 1\' times to update these counts based on previous counts.\n1. **Update Counts:** Each iteration updates the counts for groups A, B, C, and D according to the rules specified:\n - A is updated based on previous B and C counts.\n - B is updated using the previous count of A.\n - C is updated using previous counts of A and D.\n - D is updated using the previous count of C.\n1. **Final Calculation:** After the loop, it calculates the total count of possible positions by summing up the counts of all groups and applies modulo to handle large numbers.\n1. **Return:** The final count of possible positions after \'n\' steps is returned.\n\n# Complexity\n- *Time complexity:*\n $$O(n)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int knightDialer(int n) {\n // If n is 1, there are 10 possible starting positions for the knight.\n if (n == 1) {\n return 10;\n }\n \n // Define the initial counts for each of the four groups of possible moves.\n int A = 4; // Possible moves from keys 1, 3, 7, 9\n int B = 2; // Possible moves from keys 2, 8\n int C = 2; // Possible moves from keys 4, 6\n int D = 1; // Possible move from key 5\n int MOD = 1e9 + 7; // Modulo value for handling large numbers.\n \n // Iterate \'n - 1\' times to update the counts for each group of moves.\n for (int i = 0; i < n - 1; i++) {\n // Store temporary values for each group to update counts.\n int tempA = A;\n int tempB = B;\n int tempC = C;\n int tempD = D;\n \n // Update counts for each group based on previous counts.\n A = ((2 * tempB) % MOD + (2 * tempC) % MOD) % MOD;\n B = tempA;\n C = (tempA + (2 * tempD) % MOD) % MOD;\n D = tempC;\n }\n \n // Calculate the total count of possible positions by summing up all groups.\n int ans = (A + B) % MOD;\n ans = (ans + C) % MOD;\n return (ans + D) % MOD;\n }\n};\n\n\n\n```\n```C []\nint knightDialer(int n) {\n if (n == 1) {\n return 10;\n }\n \n int A = 4;\n int B = 2;\n int C = 2;\n int D = 1;\n int MOD = 1000000007;\n \n for (int i = 0; i < n - 1; i++) {\n int tempA = A;\n int tempB = B;\n int tempC = C;\n int tempD = D;\n \n A = ((2 * tempB) % MOD + (2 * tempC) % MOD) % MOD;\n B = tempA;\n C = (tempA + (2 * tempD) % MOD) % MOD;\n D = tempC;\n }\n \n int ans = (A + B) % MOD;\n ans = (ans + C) % MOD;\n return (ans + D) % MOD;\n}\n\n\n```\n\n```Java []\n\nclass Solution {\n public int knightDialer(int n) {\n if (n == 1) {\n return 10;\n }\n \n int A = 4;\n int B = 2;\n int C = 2;\n int D = 1;\n int MOD = (int) 1e9 + 7;\n \n for (int i = 0; i < n - 1; i++) {\n int tempA = A;\n int tempB = B;\n int tempC = C;\n int tempD = D;\n \n A = ((2 * tempB) % MOD + (2 * tempC) % MOD) % MOD;\n B = tempA;\n C = (tempA + (2 * tempD) % MOD) % MOD;\n D = tempC;\n }\n \n int ans = (A + B) % MOD;\n ans = (ans + C) % MOD;\n return (ans + D) % MOD;\n }\n}\n\n```\n```python3 []\nclass Solution:\n def knightDialer(self, n: int) -> int:\n if n == 1:\n return 10\n \n A = 4\n B = 2\n C = 2\n D = 1\n MOD = 10 ** 9 + 7\n \n for _ in range(n - 1):\n A, B, C, D = (2 * (B + C)) % MOD, A, (A + 2 * D) % MOD, C \n \n return (A + B + C + D) % MOD\n\n\n```\n```javascript []\nfunction knightDialer(n) {\n if (n === 1) {\n return 10;\n }\n \n let A = 4;\n let B = 2;\n let C = 2;\n let D = 1;\n const MOD = 1000000007;\n \n for (let i = 0; i < n - 1; i++) {\n let tempA = A;\n let tempB = B;\n let tempC = C;\n let tempD = D;\n \n A = ((2 * tempB) % MOD + (2 * tempC) % MOD) % MOD;\n B = tempA;\n C = (tempA + (2 * tempD) % MOD) % MOD;\n D = tempC;\n }\n \n let ans = (A + B) % MOD;\n ans = (ans + C) % MOD;\n return (ans + D) % MOD;\n}\n\n\n\n```\n\n---\n#### ***Approach 6(Linear Algebra)***\n\n1. This code aims to find the number of unique paths a knight can take on a phone dial pad in \'n\' steps using matrix exponentiation.\n1. The `knightDialer` function initializes the transition matrix `A` representing movements from one position on the dial pad to another.\n1. The vector `v` represents the count of paths for each position initially.\n1. It uses matrix exponentiation to efficiently compute the count of paths after `n` steps. The `multiply` function performs matrix multiplication to update the path count.\n1. Finally, it calculates the total count of paths after `n` steps and returns the result.\n\n\n\n\n\n# Complexity\n- *Time complexity:*\n $$O(logn)$$\n \n\n- *Space complexity:*\n $$O(1)$$\n \n\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int MOD = 1e9 + 7; // Constant value for modulo arithmetic\n \n // Function to compute the number of paths for a knight dialer\n int knightDialer(int n) {\n if (n == 1) {\n return 10; // If n is 1, there are 10 possible starting positions for the knight.\n }\n \n // Matrix representing the transitions between positions on the dial pad\n vector<vector<long>> A = {\n {0, 0, 0, 0, 1, 0, 1, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 1, 0, 1, 0},\n {0, 0, 0, 0, 0, 0, 0, 1, 0, 1},\n {0, 0, 0, 0, 1, 0, 0, 0, 1, 0},\n {1, 0, 0, 1, 0, 0, 0, 0, 0, 1},\n {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n {1, 1, 0, 0, 0, 0, 0, 1, 0, 0},\n {0, 0, 1, 0, 0, 0, 1, 0, 0, 0},\n {0, 1, 0, 1, 0, 0, 0, 0, 0, 0},\n {0, 0, 1, 0, 1, 0, 0, 0, 0, 0}\n };\n \n // Initial vector representing the count of paths for each position on the dial pad\n vector<vector<long>> v = {\n {1, 1, 1, 1, 1, 1, 1, 1, 1, 1} // For the first step (n = 1)\n };\n \n n--; // Decrementing n since we already accounted for n = 1\n \n // Applying matrix exponentiation to compute the count of paths after n steps\n while (n > 0) {\n if ((n & 1) != 0) {\n v = multiply(v, A); // Multiply the matrix v with matrix A\n }\n \n A = multiply(A, A); // Square matrix A for the next step\n n >>= 1; // Right shift n to prepare for the next step\n }\n \n int ans = 0;\n // Calculating the total count of paths after n steps\n for (long num : v[0]) {\n ans = (ans + num) % MOD;\n }\n \n return ans;\n }\n \n // Function to perform matrix multiplication\n vector<vector<long>> multiply(vector<vector<long>>& A, vector<vector<long>>& B) {\n vector<vector<long>> result(A.size(), vector<long>(B[0].size(), 0));\n \n for (int i = 0; i < A.size(); i++) {\n for (int j = 0; j < B[0].size(); j++) {\n for (int k = 0; k < B.size(); k++) {\n result[i][j] = (result[i][j] + A[i][k] * B[k][j]) % MOD;\n }\n }\n }\n \n return result;\n }\n};\n\n\n\n```\n```C []\n#define MOD 1000000007\n\nint knightDialer(int n) {\n if (n == 1) {\n return 10;\n }\n \n long A[10][10] = {\n {0, 0, 0, 0, 1, 0, 1, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 1, 0, 1, 0},\n {0, 0, 0, 0, 0, 0, 0, 1, 0, 1},\n {0, 0, 0, 0, 1, 0, 0, 0, 1, 0},\n {1, 0, 0, 1, 0, 0, 0, 0, 0, 1},\n {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n {1, 1, 0, 0, 0, 0, 0, 1, 0, 0},\n {0, 0, 1, 0, 0, 0, 1, 0, 0, 0},\n {0, 1, 0, 1, 0, 0, 0, 0, 0, 0},\n {0, 0, 1, 0, 1, 0, 0, 0, 0, 0}\n };\n \n long v[1][10] = {\n {1, 1, 1, 1, 1, 1, 1, 1, 1, 1}\n };\n \n n--;\n while (n > 0) {\n if ((n & 1) != 0) {\n long temp[1][10];\n for (int i = 0; i < 10; i++) {\n temp[0][i] = 0;\n for (int j = 0; j < 10; j++) {\n temp[0][i] = (temp[0][i] + v[0][j] * A[j][i]) % MOD;\n }\n }\n for (int i = 0; i < 10; i++) {\n v[0][i] = temp[0][i];\n }\n }\n \n long temp[10][10];\n for (int i = 0; i < 10; i++) {\n for (int j = 0; j < 10; j++) {\n temp[i][j] = 0;\n for (int k = 0; k < 10; k++) {\n temp[i][j] = (temp[i][j] + A[i][k] * A[k][j]) % MOD;\n }\n }\n }\n for (int i = 0; i < 10; i++) {\n for (int j = 0; j < 10; j++) {\n A[i][j] = temp[i][j];\n }\n }\n n >>= 1;\n }\n \n int ans = 0;\n for (int i = 0; i < 10; i++) {\n ans = (ans + v[0][i]) % MOD;\n }\n \n return ans;\n}\n\n\n```\n\n```Java []\npublic class Solution {\n\n static final int MOD = 1000000007;\n\n public int knightDialer(int n) {\n if (n == 1) {\n return 10;\n }\n\n int[][] A = {\n {0, 0, 0, 0, 1, 0, 1, 0, 0, 0},\n {0, 0, 0, 0, 0, 0, 1, 0, 1, 0},\n {0, 0, 0, 0, 0, 0, 0, 1, 0, 1},\n {0, 0, 0, 0, 1, 0, 0, 0, 1, 0},\n {1, 0, 0, 1, 0, 0, 0, 0, 0, 1},\n {0, 0, 0, 0, 0, 0, 0, 0, 0, 0},\n {1, 1, 0, 0, 0, 0, 0, 1, 0, 0},\n {0, 0, 1, 0, 0, 0, 1, 0, 0, 0},\n {0, 1, 0, 1, 0, 0, 0, 0, 0, 0},\n {0, 0, 1, 0, 1, 0, 0, 0, 0, 0}\n };\n\n int[] v = {1, 1, 1, 1, 1, 1, 1, 1, 1, 1};\n\n n--;\n while (n > 0) {\n if ((n & 1) != 0) {\n int[] temp = new int[10];\n for (int i = 0; i < 10; i++) {\n for (int j = 0; j < 10; j++) {\n temp[i] = (int)((temp[i] + (long)v[j] * A[j][i]) % MOD);\n }\n }\n v = temp.clone();\n }\n\n int[][] temp = new int[10][10];\n for (int i = 0; i < 10; i++) {\n for (int j = 0; j < 10; j++) {\n for (int k = 0; k < 10; k++) {\n temp[i][j] = (int)((temp[i][j] + (long)A[i][k] * A[k][j]) % MOD);\n }\n }\n }\n A = temp.clone();\n n >>= 1;\n }\n\n int ans = 0;\n for (int i = 0; i < 10; i++) {\n ans = (ans + v[i]) % MOD;\n }\n\n return ans;\n }\n\n public static void main(String[] args) {\n int n = 4; // Example: calculating for n = 4\n Solution solution = new Solution();\n int result = solution.knightDialer(n);\n System.out.println(result); // Printing the result\n }\n}\n\n\n\n```\n```python3 []\nclass Solution:\n def knightDialer(self, n: int) -> int:\n if n == 1:\n return 10\n \n def multiply(A, B):\n result = [[0] * len(B[0]) for _ in range(len(A))]\n \n for i in range(len(A)):\n for j in range(len(B[0])):\n for k in range(len(B)):\n result[i][j] = (result[i][j] + A[i][k] * B[k][j]) % MOD\n \n return result\n\n A = [\n [0, 0, 0, 0, 1, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0, 1, 0],\n [0, 0, 0, 0, 0, 0, 0, 1, 0, 1],\n [0, 0, 0, 0, 1, 0, 0, 0, 1, 0],\n [1, 0, 0, 1, 0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 1, 0, 0, 0, 1, 0, 0, 0],\n [0, 1, 0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 1, 0, 0, 0, 0, 0]\n ]\n \n v = [[1] * 10]\n MOD = 10 ** 9 + 7\n\n n -= 1\n while n:\n if n & 1:\n v = multiply(v, A)\n \n A = multiply(A, A)\n n >>= 1\n\n return sum(v[0]) % MOD\n\n\n```\n```javascript []\nfunction knightDialer(n) {\n if (n === 1) {\n return 10;\n }\n\n const MOD = 1000000007;\n const A = [\n [0, 0, 0, 0, 1, 0, 1, 0, 0, 0],\n [0, 0, 0, 0, 0, 0, 1, 0, 1, 0],\n [0, 0, 0, 0, 0, 0, 0, 1, 0, 1],\n [0, 0, 0, 0, 1, 0, 0, 0, 1, 0],\n [1, 0, 0, 1, 0, 0, 0, 0, 0, 1],\n [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],\n [1, 1, 0, 0, 0, 0, 0, 1, 0, 0],\n [0, 0, 1, 0, 0, 0, 1, 0, 0, 0],\n [0, 1, 0, 1, 0, 0, 0, 0, 0, 0],\n [0, 0, 1, 0, 1, 0, 0, 0, 0, 0]\n ];\n\n let v = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1];\n\n n--;\n while (n > 0) {\n if ((n & 1) !== 0) {\n const temp = Array(10).fill(0);\n for (let i = 0; i < 10; i++) {\n for (let j = 0; j < 10; j++) {\n temp[i] = (temp[i] + v[j] * A[j][i]) % MOD;\n }\n }\n for (let i = 0; i < 10; i++) {\n v[i] = temp[i];\n }\n }\n\n const temp = Array.from(Array(10), () => Array(10).fill(0));\n for (let i = 0; i < 10; i++) {\n for (let j = 0; j < 10; j++) {\n for (let k = 0; k < 10; k++) {\n temp[i][j] = (temp[i][j] + A[i][k] * A[k][j]) % MOD;\n }\n }\n }\n for (let i = 0; i < 10; i++) {\n for (let j = 0; j < 10; j++) {\n A[i][j] = temp[i][j];\n }\n }\n n >>= 1;\n }\n\n let ans = 0;\n for (let i = 0; i < 10; i++) {\n ans = (ans + v[i]) % MOD;\n }\n\n return ans;\n}\n\n\n\n```\n\n---\n\n\n# PLEASE UPVOTE IF IT HELPED\n\n---\n---\n\n\n--- | 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 number will be represented in one of the following three ways:
* * For example, `12`, `0`, and `123`.
* `**<.>**`
* For example, `0.5`, `1.`, `2.12`, and `123.0001`.
* `**<.>****<(>****<)>**`
* For example, `0.1(6)`, `1.(9)`, `123.00(1212)`.
The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:
* `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`.
**Example 1:**
**Input:** s = "0.(52) ", t = "0.5(25) "
**Output:** true
**Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number.
**Example 2:**
**Input:** s = "0.1666(6) ", t = "0.166(66) "
**Output:** true
**Example 3:**
**Input:** s = "0.9(9) ", t = "1. "
**Output:** true
**Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\]
"1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ".
**Constraints:**
* Each part consists only of digits.
* The does not have leading zeros (except for the zero itself).
* `1 <= .length <= 4`
* `0 <= .length <= 4`
* `1 <= .length <= 4` | 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, from 4 and 6.\nSo if i can get to 4 in `x` ways at n == 1 and 6 in `y` ways at n == 1, how many ways can i get to 0 at n == 2, hmmmm `x + y`, right?\n\nSo can generalize and say,\nTo get to `a` we will find all `b0, b1, b2, ...` from where we can come to `a` and add the ways we needed to come to each of these `b0, b1, b2, ...` and set it as the number of ways we can get to `a` at n == `n`.\n\nAlso note that even if one digit in a phone number is different we have 2 unique numbers. And our logic only finds unqiue numbers as at one or the other point there will a different digit in two similar seeming numbers\n\n```python\nConvention : dp[234] means dp[2] + dp[3] + dp[4]\nI\'ll be using this convention in the visualization below\nn == 1\ndp = [1 1 1 1 1 1 1 1 1 1]\n\nn == 2\ndp = [dp[46] dp[68] dp[79] dp[48] dp[039] dp[] dp[017] dp[26] dp[13] dp[24]]\n```\n\nNote for n == 3, the dp is updated and we will be using the dp obtained at n == 2\n\n# Original Approach\nI had initially used list to solve the dp which required copying list to maintain niceness of code which took some time more as compared to same logic implemented without list\n```python\nclass Solution:\n def knightDialer(self, n: int) -> int:\n last = ["46", "68", "79", "48", "039", "", "017", "26", "13", "24"]\n\n dp = [1, 1, 1, 1, 1, 0, 1, 1, 1, 1]\n\n for _ in range(n - 1):\n temp = dp.copy()\n for i in range(10):\n dp[i] = sum([temp[int(j)] for j in last[i]])\n\n return sum(dp, n == 1) % (10 ** 9 + 7) \n```\n\n### Time Complexity : `O(n)`\n### Space Complexity : `O(1)`\n\n# Code\n```python\nclass Solution:\n def knightDialer(self, n: int) -> int:\n x0 = x1 = x2 = x3 = x4 = x6 = x7 = x8 = x9 = 1\n\n for _ in range(n - 1):\n x0, x1, x2, x3, x4, x6, x7, x8, x9 = (\n x4 + x6,\n x6 + x8,\n x7 + x9,\n x4 + x8,\n x0 + x3 + x9,\n x0 + x1 + x7,\n x2 + x6,\n x1 + x3,\n x2 + x4,\n )\n\n return (x0 + x1 + x2 + x3 + x4 + (n == 1) + x6 + x7 + x8 + x9) % (10**9 + 7)\n\n```\nThe above code is a updated version of Lee\'s naive [Code](https://leetcode.com/problems/knight-dialer/solutions/189252/o-logn/?envType=daily-question&envId=2023-11-27). You can also find the most optimized `O(log n)` solution there which is mind blowing but hard to understand and explain.\n\nI removed `x5` variable as it is only valued `1` when `n == 1`.\n\nAnd the good thing about python is, if we add booleans it evaluates `True` as `1` and `False` as `0`.\n\nSo we add `(n == 1)` in the final summation equation to take care of `x5`. | 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 chess diagram below:
We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell).
Given an integer `n`, return how many distinct phone numbers of length `n` we can dial.
You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps.
As the answer may be very large, **return the answer modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 10
**Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
**Example 2:**
**Input:** n = 2
**Output:** 20
**Explanation:** All the valid number we can dial are \[04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94\]
**Example 3:**
**Input:** n = 3131
**Output:** 136006598
**Explanation:** Please take care of the mod.
**Constraints:**
* `1 <= n <= 5000` | 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, from 4 and 6.\nSo if i can get to 4 in `x` ways at n == 1 and 6 in `y` ways at n == 1, how many ways can i get to 0 at n == 2, hmmmm `x + y`, right?\n\nSo can generalize and say,\nTo get to `a` we will find all `b0, b1, b2, ...` from where we can come to `a` and add the ways we needed to come to each of these `b0, b1, b2, ...` and set it as the number of ways we can get to `a` at n == `n`.\n\nAlso note that even if one digit in a phone number is different we have 2 unique numbers. And our logic only finds unqiue numbers as at one or the other point there will a different digit in two similar seeming numbers\n\n```python\nConvention : dp[234] means dp[2] + dp[3] + dp[4]\nI\'ll be using this convention in the visualization below\nn == 1\ndp = [1 1 1 1 1 1 1 1 1 1]\n\nn == 2\ndp = [dp[46] dp[68] dp[79] dp[48] dp[039] dp[] dp[017] dp[26] dp[13] dp[24]]\n```\n\nNote for n == 3, the dp is updated and we will be using the dp obtained at n == 2\n\n# Original Approach\nI had initially used list to solve the dp which required copying list to maintain niceness of code which took some time more as compared to same logic implemented without list\n```python\nclass Solution:\n def knightDialer(self, n: int) -> int:\n last = ["46", "68", "79", "48", "039", "", "017", "26", "13", "24"]\n\n dp = [1, 1, 1, 1, 1, 0, 1, 1, 1, 1]\n\n for _ in range(n - 1):\n temp = dp.copy()\n for i in range(10):\n dp[i] = sum([temp[int(j)] for j in last[i]])\n\n return sum(dp, n == 1) % (10 ** 9 + 7) \n```\n\n### Time Complexity : `O(n)`\n### Space Complexity : `O(1)`\n\n# Code\n```python\nclass Solution:\n def knightDialer(self, n: int) -> int:\n x0 = x1 = x2 = x3 = x4 = x6 = x7 = x8 = x9 = 1\n\n for _ in range(n - 1):\n x0, x1, x2, x3, x4, x6, x7, x8, x9 = (\n x4 + x6,\n x6 + x8,\n x7 + x9,\n x4 + x8,\n x0 + x3 + x9,\n x0 + x1 + x7,\n x2 + x6,\n x1 + x3,\n x2 + x4,\n )\n\n return (x0 + x1 + x2 + x3 + x4 + (n == 1) + x6 + x7 + x8 + x9) % (10**9 + 7)\n\n```\nThe above code is a updated version of Lee\'s naive [Code](https://leetcode.com/problems/knight-dialer/solutions/189252/o-logn/?envType=daily-question&envId=2023-11-27). You can also find the most optimized `O(log n)` solution there which is mind blowing but hard to understand and explain.\n\nI removed `x5` variable as it is only valued `1` when `n == 1`.\n\nAnd the good thing about python is, if we add booleans it evaluates `True` as `1` and `False` as `0`.\n\nSo we add `(n == 1)` in the final summation equation to take care of `x5`. | 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 number will be represented in one of the following three ways:
* * For example, `12`, `0`, and `123`.
* `**<.>**`
* For example, `0.5`, `1.`, `2.12`, and `123.0001`.
* `**<.>****<(>****<)>**`
* For example, `0.1(6)`, `1.(9)`, `123.00(1212)`.
The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:
* `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`.
**Example 1:**
**Input:** s = "0.(52) ", t = "0.5(25) "
**Output:** true
**Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number.
**Example 2:**
**Input:** s = "0.1666(6) ", t = "0.166(66) "
**Output:** true
**Example 3:**
**Input:** s = "0.9(9) ", t = "1. "
**Output:** true
**Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\]
"1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ".
**Constraints:**
* Each part consists only of digits.
* The does not have leading zeros (except for the zero itself).
* `1 <= .length <= 4`
* `0 <= .length <= 4`
* `1 <= .length <= 4` | 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 steps of the knight (**so in shape L**).\n# Approach\nOkay, let\'s look at this problem from the other side - every combination of numbers must end with some kind of number - logical, right? That is, ultimately we must end up with the knight on this number, and before that we must end up on a number from which we can get to the last number - in other words, we should consider the process in reverse order. Then now we will consider as the starting point not the one at which we will begin, but the one at which we will finish. However, the number of ways to get to different numbers on the keyboard is different, let\'s take a closer look:\n\nLet\'s consider the number 1 as an example - obviously from the figure below, you can get to it in 2 ways - from the number 8 and the number 6, that is, the number of ways to end the line with 1 is the number of ways to get to cell 8 + the number of ways to get to cell 6 The situation is similar with 2, 3, 7, 8, 9.\n<img src="https://assets.leetcode.com/users/images/c877b3ee-bf65-4560-a37a-f9f47a353c71_1701077892.7563167.png" alt="drawing" width="200"/>\n\nWith numbers 4 and 6 the situation is a little different, because now we can get here from cell 0, so now, for example, for 4 it will be a sum of ways to get to 3, to 9 and to 0.\n<img src="https://assets.leetcode.com/users/images/ad67573e-a895-42bf-87f4-74cd2eeb3cba_1701078239.2617447.png" alt="drawing" width="200"/>\n\nAnd the extreme case is 5, if n is not equal to one, we do not have the opportunity to somehow get to cell 5, therefore for n not equal 1 the number of ways to create combination with 5 at the end is 0.\n<img src="https://assets.leetcode.com/users/images/d913efdc-2930-4c46-bf9e-d64b9003a2d2_1701078264.7531633.png" alt="drawing" width="200"/>\n\n# Code explanation\nWe declare a mod variable - it\u2019s just a number, the remainder of which needs to be returned so that the number is not too large. Next, we declare the list dp - in fact, you can make a standard dp n of n cells, but this does not make sense, since we are only interested in the last row. Our \u201Cstandard\u201D case is for n == 1, that is, 1 for each digit. Next, each step we simply sum up the quantity in the same way as discussed above, after which we simply return the result\n# Complexity\n- Time complexity:\n We use one loop with n iterations, so the time complexity is O(n) \n- Space complexity:\n In each of n step we create new array of constant length 9, so the space complexity is O(n)\n\n\n**Feel free to ask whatever you want if you didn\'t understand something, I would be glad to answer you.**\nIf you like my effort you can award me with upvote, it will be a good motivation for me to write such posts in future, thanks and good luck, happy coding! <3\n\n\n\n\n\n\n# Code\n```\nclass Solution:\n def knightDialer(self, n: int) -> int:\n mod = 10 ** 9 + 7\n dp = [1 for _ in range(10)]\n\n for steps in range(0, n - 1):\n n = dp[:]\n dp[0] = n[4] + n[6]\n dp[1] = n[6] + n[8]\n dp[2] = n[7] + n[9]\n dp[3] = n[4] + n[8]\n dp[4] = n[3] + n[9] + n[0]\n dp[5] = 0\n dp[6] = n[1] + n[7] + n[0]\n dp[7] = n[2] + n[6]\n dp[8] = n[1] + n[3]\n dp[9] = n[2] + n[4]\n dp = [num % mod for num in dp]\n \n return sum(dp) % mod\n``` | 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 chess diagram below:
We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell).
Given an integer `n`, return how many distinct phone numbers of length `n` we can dial.
You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps.
As the answer may be very large, **return the answer modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 10
**Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
**Example 2:**
**Input:** n = 2
**Output:** 20
**Explanation:** All the valid number we can dial are \[04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94\]
**Example 3:**
**Input:** n = 3131
**Output:** 136006598
**Explanation:** Please take care of the mod.
**Constraints:**
* `1 <= n <= 5000` | 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 steps of the knight (**so in shape L**).\n# Approach\nOkay, let\'s look at this problem from the other side - every combination of numbers must end with some kind of number - logical, right? That is, ultimately we must end up with the knight on this number, and before that we must end up on a number from which we can get to the last number - in other words, we should consider the process in reverse order. Then now we will consider as the starting point not the one at which we will begin, but the one at which we will finish. However, the number of ways to get to different numbers on the keyboard is different, let\'s take a closer look:\n\nLet\'s consider the number 1 as an example - obviously from the figure below, you can get to it in 2 ways - from the number 8 and the number 6, that is, the number of ways to end the line with 1 is the number of ways to get to cell 8 + the number of ways to get to cell 6 The situation is similar with 2, 3, 7, 8, 9.\n<img src="https://assets.leetcode.com/users/images/c877b3ee-bf65-4560-a37a-f9f47a353c71_1701077892.7563167.png" alt="drawing" width="200"/>\n\nWith numbers 4 and 6 the situation is a little different, because now we can get here from cell 0, so now, for example, for 4 it will be a sum of ways to get to 3, to 9 and to 0.\n<img src="https://assets.leetcode.com/users/images/ad67573e-a895-42bf-87f4-74cd2eeb3cba_1701078239.2617447.png" alt="drawing" width="200"/>\n\nAnd the extreme case is 5, if n is not equal to one, we do not have the opportunity to somehow get to cell 5, therefore for n not equal 1 the number of ways to create combination with 5 at the end is 0.\n<img src="https://assets.leetcode.com/users/images/d913efdc-2930-4c46-bf9e-d64b9003a2d2_1701078264.7531633.png" alt="drawing" width="200"/>\n\n# Code explanation\nWe declare a mod variable - it\u2019s just a number, the remainder of which needs to be returned so that the number is not too large. Next, we declare the list dp - in fact, you can make a standard dp n of n cells, but this does not make sense, since we are only interested in the last row. Our \u201Cstandard\u201D case is for n == 1, that is, 1 for each digit. Next, each step we simply sum up the quantity in the same way as discussed above, after which we simply return the result\n# Complexity\n- Time complexity:\n We use one loop with n iterations, so the time complexity is O(n) \n- Space complexity:\n In each of n step we create new array of constant length 9, so the space complexity is O(n)\n\n\n**Feel free to ask whatever you want if you didn\'t understand something, I would be glad to answer you.**\nIf you like my effort you can award me with upvote, it will be a good motivation for me to write such posts in future, thanks and good luck, happy coding! <3\n\n\n\n\n\n\n# Code\n```\nclass Solution:\n def knightDialer(self, n: int) -> int:\n mod = 10 ** 9 + 7\n dp = [1 for _ in range(10)]\n\n for steps in range(0, n - 1):\n n = dp[:]\n dp[0] = n[4] + n[6]\n dp[1] = n[6] + n[8]\n dp[2] = n[7] + n[9]\n dp[3] = n[4] + n[8]\n dp[4] = n[3] + n[9] + n[0]\n dp[5] = 0\n dp[6] = n[1] + n[7] + n[0]\n dp[7] = n[2] + n[6]\n dp[8] = n[1] + n[3]\n dp[9] = n[2] + n[4]\n dp = [num % mod for num in dp]\n \n return sum(dp) % mod\n``` | 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 number will be represented in one of the following three ways:
* * For example, `12`, `0`, and `123`.
* `**<.>**`
* For example, `0.5`, `1.`, `2.12`, and `123.0001`.
* `**<.>****<(>****<)>**`
* For example, `0.1(6)`, `1.(9)`, `123.00(1212)`.
The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:
* `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`.
**Example 1:**
**Input:** s = "0.(52) ", t = "0.5(25) "
**Output:** true
**Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number.
**Example 2:**
**Input:** s = "0.1666(6) ", t = "0.166(66) "
**Output:** true
**Example 3:**
**Input:** s = "0.9(9) ", t = "1. "
**Output:** true
**Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\]
"1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ".
**Constraints:**
* Each part consists only of digits.
* The does not have leading zeros (except for the zero itself).
* `1 <= .length <= 4`
* `0 <= .length <= 4`
* `1 <= .length <= 4` | 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. $$O(n)$$ -->\n\n# Code\n```\nMOD = 1_000_000_007\n\nIDENTITY_MATRIX = [\n [4, 0, 0, 0],\n [0, 2, 0, 0],\n [0, 0, 2, 0],\n [0, 0, 0, 1],\n]\n\nPERMUTATION_MATRIX = [\n [0, 1, 1, 0],\n [2, 0, 0, 0],\n [2, 0, 0, 1],\n [0, 0, 2, 0],\n]\n\nclass Solution:\n def knightDialer(self, n: int) -> int:\n return dynamic_knight_dialer(n) if n < 512 else matrix_knight_dialer(n)\n\n\ndef dynamic_knight_dialer(n: int) -> int:\n if n == 1:\n return 10\n \n a = 4\n b = 2\n c = 2\n d = 1\n \n for _ in range(1, n):\n a, b, c, d = (2 * (b + c)) % MOD, a, (a + d + d) % MOD, c\n \n return (a + b + c+ d) % MOD\n\n\ndef matrix_knight_dialer(n: int) -> int:\n return sum(map(sum, matrix_power(PERMUTATION_MATRIX, n - 1))) % MOD\n \n\ndef matrix_power(matrix, power):\n result = IDENTITY_MATRIX\n base = PERMUTATION_MATRIX\n while power:\n if power & 1:\n result = multiply_matrices(result, base)\n base = multiply_matrices(base, base)\n power >>= 1\n return result\n\n\ndef multiply_matrices(mat1, mat2):\n return [[sum(map(mul, row, col)) % MOD for col in zip(*mat2)] for row in mat1]\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 chess diagram below:
We have a chess knight and a phone pad as shown below, the knight **can only stand on a numeric cell** (i.e. blue cell).
Given an integer `n`, return how many distinct phone numbers of length `n` we can dial.
You are allowed to place the knight **on any numeric cell** initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be **valid** knight jumps.
As the answer may be very large, **return the answer modulo** `109 + 7`.
**Example 1:**
**Input:** n = 1
**Output:** 10
**Explanation:** We need to dial a number of length 1, so placing the knight over any numeric cell of the 10 cells is sufficient.
**Example 2:**
**Input:** n = 2
**Output:** 20
**Explanation:** All the valid number we can dial are \[04, 06, 16, 18, 27, 29, 34, 38, 40, 43, 49, 60, 61, 67, 72, 76, 81, 83, 92, 94\]
**Example 3:**
**Input:** n = 3131
**Output:** 136006598
**Explanation:** Please take care of the mod.
**Constraints:**
* `1 <= n <= 5000` | 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. $$O(n)$$ -->\n\n# Code\n```\nMOD = 1_000_000_007\n\nIDENTITY_MATRIX = [\n [4, 0, 0, 0],\n [0, 2, 0, 0],\n [0, 0, 2, 0],\n [0, 0, 0, 1],\n]\n\nPERMUTATION_MATRIX = [\n [0, 1, 1, 0],\n [2, 0, 0, 0],\n [2, 0, 0, 1],\n [0, 0, 2, 0],\n]\n\nclass Solution:\n def knightDialer(self, n: int) -> int:\n return dynamic_knight_dialer(n) if n < 512 else matrix_knight_dialer(n)\n\n\ndef dynamic_knight_dialer(n: int) -> int:\n if n == 1:\n return 10\n \n a = 4\n b = 2\n c = 2\n d = 1\n \n for _ in range(1, n):\n a, b, c, d = (2 * (b + c)) % MOD, a, (a + d + d) % MOD, c\n \n return (a + b + c+ d) % MOD\n\n\ndef matrix_knight_dialer(n: int) -> int:\n return sum(map(sum, matrix_power(PERMUTATION_MATRIX, n - 1))) % MOD\n \n\ndef matrix_power(matrix, power):\n result = IDENTITY_MATRIX\n base = PERMUTATION_MATRIX\n while power:\n if power & 1:\n result = multiply_matrices(result, base)\n base = multiply_matrices(base, base)\n power >>= 1\n return result\n\n\ndef multiply_matrices(mat1, mat2):\n return [[sum(map(mul, row, col)) % MOD for col in zip(*mat2)] for row in mat1]\n``` | 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 number will be represented in one of the following three ways:
* * For example, `12`, `0`, and `123`.
* `**<.>**`
* For example, `0.5`, `1.`, `2.12`, and `123.0001`.
* `**<.>****<(>****<)>**`
* For example, `0.1(6)`, `1.(9)`, `123.00(1212)`.
The repeating portion of a decimal expansion is conventionally denoted within a pair of round brackets. For example:
* `1/6 = 0.16666666... = 0.1(6) = 0.1666(6) = 0.166(66)`.
**Example 1:**
**Input:** s = "0.(52) ", t = "0.5(25) "
**Output:** true
**Explanation:** Because "0.(52) " represents 0.52525252..., and "0.5(25) " represents 0.52525252525..... , the strings represent the same number.
**Example 2:**
**Input:** s = "0.1666(6) ", t = "0.166(66) "
**Output:** true
**Example 3:**
**Input:** s = "0.9(9) ", t = "1. "
**Output:** true
**Explanation:** "0.9(9) " represents 0.999999999... repeated forever, which equals 1. \[[See this link for an explanation.](https://en.wikipedia.org/wiki/0.999...)\]
"1. " represents the number 1, which is formed correctly: (IntegerPart) = "1 " and (NonRepeatingPart) = " ".
**Constraints:**
* Each part consists only of digits.
* The does not have leading zeros (except for the zero itself).
* `1 <= .length <= 4`
* `0 <= .length <= 4`
* `1 <= .length <= 4` | 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 (; i < szt, p < szsp; p++) {\n if (target[i] == stamp[p]) {\n i++;\n continue;\n }\n if (i == idx)\n continue;\n int backward = -1;\n while (backward++ < p && i-backward >= idx) {\n if (backward == p) {\n if (!st.size()) {\n break;\n }\n i -= backward;\n backward = 0;\n p = i - st.back();\n st.pop_back();\n continue;\n }\n if (target[i-backward] == stamp[0]) {\n if (i-p < 0) return {};\n st.push_back(i-p);\n i -= backward;\n p = -1;\n break;\n }\n }\n if (!st.size()) {\n p -= i - idx;\n i = idx;\n }\n }\n if (i-p < 0 || (p == szsp && i == idx)) return {};\n res.push_back(i-p);\n for (auto p = st.rbegin(); p != st.rend(); p++) res.push_back(*p);\n st.clear();\n idx = i;\n }\n reverse(res.begin(), res.end());\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def movesToStamp(self, stamp: str, target: str) -> List[int]:\n m = len(stamp)\n n = len(target)\n\n i = 0\n while i < m and stamp[i] == target[i]:\n i += 1\n top_end = i\n bot_end = m if i == m else 0\n\n parent = {}\n if top_end > 0:\n parent[(0, top_end)] = ((0, 0), (0, 0))\n if bot_end > 0:\n parent[(1, bot_end)] = ((0, 0), (0, 0))\n \n for i in range(1, n - m + 1):\n # print("i:", i, "top_end:", top_end, "bot_end:", bot_end)\n if bot_end < i and top_end < i:\n return []\n\n j = 0\n while j < m and stamp[j] == target[i + j]:\n j += 1\n if i + j > top_end:\n s = (0, i + j)\n prev_s = (0, top_end) if top_end >= i else (1, bot_end)\n move = (0, i)\n parent[s] = (prev_s, move)\n top_end = i + j\n if j == m:\n parent[(1, i + j)] = parent[(0, i + j)]\n bot_end = i + j\n elif bot_end >= i:\n j = bot_end - i\n while j < m and stamp[j] == target[i + j]:\n j += 1\n if j == m:\n s = (1, i + j)\n prev_s = (1, bot_end)\n move = (1, i)\n parent[s] = (prev_s, move)\n bot_end = i + j\n elif i + j > top_end:\n s = (0, i + j)\n prev_s = (1, bot_end)\n move = (1, i)\n parent[s] = (prev_s, move)\n top_end = i + j\n if bot_end != n:\n return []\n\n s = (1, n)\n moves = []\n while s in parent:\n prev_s, move = parent[s]\n moves.append(move)\n s = prev_s\n moves = list(reversed(moves))\n\n ans = [i for t, i in reversed(moves) if t == 1] + [i for t, i in moves if t == 0]\n return ans\n```\n\n```Java []\nclass Solution {\n public int[] movesToStamp(String stamp, String target) {\n char[] S = stamp.toCharArray();\n char[] T = target.toCharArray();\n List<Integer> res = new ArrayList<>();\n boolean[] visited = new boolean[T.length];\n int stars = 0;\n \n while (stars < T.length) {\n boolean doneReplace = false;\n for (int i = 0; i <= T.length - S.length; i++) {\n if (!visited[i] && canReplace(T, i, S)) {\n stars = doReplace(T, i, S.length, stars);\n doneReplace = true;\n visited[i] = true;\n res.add(i);\n if (stars == T.length) {\n break;\n }\n }\n }\n if (!doneReplace) {\n return new int[0];\n }\n }\n int[] resArray = new int[res.size()];\n for (int i = 0; i < res.size(); i++) {\n resArray[i] = res.get(res.size() - i - 1);\n }\n return resArray;\n }\n private boolean canReplace(char[] T, int p, char[] S) {\n for (int i = 0; i < S.length; i++) {\n if (T[i + p] != \'*\' && T[i + p] != S[i]) {\n return false;\n }\n }\n return true;\n }\n private int doReplace(char[] T, int p, int len, int count) {\n for (int i = 0; i < len; i++) {\n if (T[i + p] != \'*\') {\n T[i + p] = \'*\';\n count++;\n }\n }\n return count;\n } \n}\n```\n | 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 "`, then `s` is `"????? "` initially. In one turn you can:
* place `stamp` at index `0` of `s` to obtain `"abc?? "`,
* place `stamp` at index `1` of `s` to obtain `"?abc? "`, or
* place `stamp` at index `2` of `s` to obtain `"??abc "`.
Note that `stamp` must be fully contained in the boundaries of `s` in order to stamp (i.e., you cannot place `stamp` at index `3` of `s`).
We want to convert `s` to `target` using **at most** `10 * target.length` turns.
Return _an array of the index of the left-most letter being stamped at each turn_. If we cannot obtain `target` from `s` within `10 * target.length` turns, return an empty array.
**Example 1:**
**Input:** stamp = "abc ", target = "ababc "
**Output:** \[0,2\]
**Explanation:** Initially s = "????? ".
- Place stamp at index 0 to get "abc?? ".
- Place stamp at index 2 to get "ababc ".
\[1,0,2\] would also be accepted as an answer, as well as some other answers.
**Example 2:**
**Input:** stamp = "abca ", target = "aabcaca "
**Output:** \[3,0,1\]
**Explanation:** Initially s = "??????? ".
- Place stamp at index 3 to get "???abca ".
- Place stamp at index 0 to get "abcabca ".
- Place stamp at index 1 to get "aabcaca ".
**Constraints:**
* `1 <= stamp.length <= target.length <= 1000`
* `stamp` and `target` consist of lowercase English letters. | 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 (; i < szt, p < szsp; p++) {\n if (target[i] == stamp[p]) {\n i++;\n continue;\n }\n if (i == idx)\n continue;\n int backward = -1;\n while (backward++ < p && i-backward >= idx) {\n if (backward == p) {\n if (!st.size()) {\n break;\n }\n i -= backward;\n backward = 0;\n p = i - st.back();\n st.pop_back();\n continue;\n }\n if (target[i-backward] == stamp[0]) {\n if (i-p < 0) return {};\n st.push_back(i-p);\n i -= backward;\n p = -1;\n break;\n }\n }\n if (!st.size()) {\n p -= i - idx;\n i = idx;\n }\n }\n if (i-p < 0 || (p == szsp && i == idx)) return {};\n res.push_back(i-p);\n for (auto p = st.rbegin(); p != st.rend(); p++) res.push_back(*p);\n st.clear();\n idx = i;\n }\n reverse(res.begin(), res.end());\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def movesToStamp(self, stamp: str, target: str) -> List[int]:\n m = len(stamp)\n n = len(target)\n\n i = 0\n while i < m and stamp[i] == target[i]:\n i += 1\n top_end = i\n bot_end = m if i == m else 0\n\n parent = {}\n if top_end > 0:\n parent[(0, top_end)] = ((0, 0), (0, 0))\n if bot_end > 0:\n parent[(1, bot_end)] = ((0, 0), (0, 0))\n \n for i in range(1, n - m + 1):\n # print("i:", i, "top_end:", top_end, "bot_end:", bot_end)\n if bot_end < i and top_end < i:\n return []\n\n j = 0\n while j < m and stamp[j] == target[i + j]:\n j += 1\n if i + j > top_end:\n s = (0, i + j)\n prev_s = (0, top_end) if top_end >= i else (1, bot_end)\n move = (0, i)\n parent[s] = (prev_s, move)\n top_end = i + j\n if j == m:\n parent[(1, i + j)] = parent[(0, i + j)]\n bot_end = i + j\n elif bot_end >= i:\n j = bot_end - i\n while j < m and stamp[j] == target[i + j]:\n j += 1\n if j == m:\n s = (1, i + j)\n prev_s = (1, bot_end)\n move = (1, i)\n parent[s] = (prev_s, move)\n bot_end = i + j\n elif i + j > top_end:\n s = (0, i + j)\n prev_s = (1, bot_end)\n move = (1, i)\n parent[s] = (prev_s, move)\n top_end = i + j\n if bot_end != n:\n return []\n\n s = (1, n)\n moves = []\n while s in parent:\n prev_s, move = parent[s]\n moves.append(move)\n s = prev_s\n moves = list(reversed(moves))\n\n ans = [i for t, i in reversed(moves) if t == 1] + [i for t, i in moves if t == 0]\n return ans\n```\n\n```Java []\nclass Solution {\n public int[] movesToStamp(String stamp, String target) {\n char[] S = stamp.toCharArray();\n char[] T = target.toCharArray();\n List<Integer> res = new ArrayList<>();\n boolean[] visited = new boolean[T.length];\n int stars = 0;\n \n while (stars < T.length) {\n boolean doneReplace = false;\n for (int i = 0; i <= T.length - S.length; i++) {\n if (!visited[i] && canReplace(T, i, S)) {\n stars = doReplace(T, i, S.length, stars);\n doneReplace = true;\n visited[i] = true;\n res.add(i);\n if (stars == T.length) {\n break;\n }\n }\n }\n if (!doneReplace) {\n return new int[0];\n }\n }\n int[] resArray = new int[res.size()];\n for (int i = 0; i < res.size(); i++) {\n resArray[i] = res.get(res.size() - i - 1);\n }\n return resArray;\n }\n private boolean canReplace(char[] T, int p, char[] S) {\n for (int i = 0; i < S.length; i++) {\n if (T[i + p] != \'*\' && T[i + p] != S[i]) {\n return false;\n }\n }\n return true;\n }\n private int doReplace(char[] T, int p, int len, int count) {\n for (int i = 0; i < len; i++) {\n if (T[i + p] != \'*\') {\n T[i + p] = \'*\';\n count++;\n }\n }\n return count;\n } \n}\n```\n | 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 **any order**. The answer is **guaranteed** to be **unique** (except for the order that it is in).
**Example 1:**
**Input:** points = \[\[1,3\],\[-2,2\]\], k = 1
**Output:** \[\[-2,2\]\]
**Explanation:**
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just \[\[-2,2\]\].
**Example 2:**
**Input:** points = \[\[3,3\],\[5,-1\],\[-2,4\]\], k = 2
**Output:** \[\[3,3\],\[-2,4\]\]
**Explanation:** The answer \[\[-2,4\],\[3,3\]\] would also be accepted.
**Constraints:**
* `1 <= k <= points.length <= 104`
* `-104 < xi, yi < 104` | 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\nNow when we start from our target let\'s take an example\n\ntarget: a b a b a b c b c b a b a b c b c\nstamp = a b c\n\n target: a b a b a b c b c b a b a b c b c\nN = len(target)\nM = len(stamp)\n Now we try to traverse the target and check if substring from index i to index i + M is == our stamp \n \n Now for checking equality between string = target[i:i+M] and stamp\n if string[index] == stamp[index] : since they are same check index+1\n elif string[index] == "?" : we have solved for this place alredy means even if we write anything here ( since we are doing in reverse order ) in the next step it will solve for the ?\n else : they aren\'t same\n So we will need to iterate through T a number of times, finding and removing any full instances of S. Once we are past the initial pass, we can use character masks to find partial matches for S on each remaining pass.\n \n \n pass 1: a b a b a b c b c b a b a b c b c\n ^ ^ ^ ^ ^ ^\n\n pass 2: a b a b * * * b c b a b * * * b c\n ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^\n\n pass 3: a b * * * * * * * b * * * * * * *\n ^ ^ ^ ^ ^ ^\n\n pass 4: * * * * * * * * * * * * * * * * *\n \n \n See carefully what we are doing everytime we are finding stamp in our target and making it "????" \n \n Now the key concept is whenever we find our target and stamp like this\n target = "???ab??"\n stamp = dabc\n \n then "?ab?" == "dabc"\n why ??\n See we are going reverse so the steps we are taking is also reverse\n Since we have put ? anywhere means that we got it right !\n so once we put "dabc" in place of "?ab?" we know that our previous turn is going to solve for the two ? marks any way\n \n```\n\n# CODE\n```\nclass Solution:\n def movesToStamp(self, stamp: str, target: str) -> List[int]:\n N,M = len(target),len(stamp)\n move = 0\n maxmove = 10*N\n ans = []\n def check(string):\n for i in range(M):\n if string[i] == stamp[i] or string[i] == \'?\':\n continue\n else:\n return False\n return True\n \n while move < maxmove:\n premove = move\n for i in range(N-M+1):\n if check(target[i:i+M]):\n move += 1\n ans.append(i)\n target = target[:i] + "?"*M + target[i+M:]\n if target == "?"*N : return ans[::-1]\n if premove == move:return []\n return []\n``` | 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 "`, then `s` is `"????? "` initially. In one turn you can:
* place `stamp` at index `0` of `s` to obtain `"abc?? "`,
* place `stamp` at index `1` of `s` to obtain `"?abc? "`, or
* place `stamp` at index `2` of `s` to obtain `"??abc "`.
Note that `stamp` must be fully contained in the boundaries of `s` in order to stamp (i.e., you cannot place `stamp` at index `3` of `s`).
We want to convert `s` to `target` using **at most** `10 * target.length` turns.
Return _an array of the index of the left-most letter being stamped at each turn_. If we cannot obtain `target` from `s` within `10 * target.length` turns, return an empty array.
**Example 1:**
**Input:** stamp = "abc ", target = "ababc "
**Output:** \[0,2\]
**Explanation:** Initially s = "????? ".
- Place stamp at index 0 to get "abc?? ".
- Place stamp at index 2 to get "ababc ".
\[1,0,2\] would also be accepted as an answer, as well as some other answers.
**Example 2:**
**Input:** stamp = "abca ", target = "aabcaca "
**Output:** \[3,0,1\]
**Explanation:** Initially s = "??????? ".
- Place stamp at index 3 to get "???abca ".
- Place stamp at index 0 to get "abcabca ".
- Place stamp at index 1 to get "aabcaca ".
**Constraints:**
* `1 <= stamp.length <= target.length <= 1000`
* `stamp` and `target` consist of lowercase English letters. | 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\nNow when we start from our target let\'s take an example\n\ntarget: a b a b a b c b c b a b a b c b c\nstamp = a b c\n\n target: a b a b a b c b c b a b a b c b c\nN = len(target)\nM = len(stamp)\n Now we try to traverse the target and check if substring from index i to index i + M is == our stamp \n \n Now for checking equality between string = target[i:i+M] and stamp\n if string[index] == stamp[index] : since they are same check index+1\n elif string[index] == "?" : we have solved for this place alredy means even if we write anything here ( since we are doing in reverse order ) in the next step it will solve for the ?\n else : they aren\'t same\n So we will need to iterate through T a number of times, finding and removing any full instances of S. Once we are past the initial pass, we can use character masks to find partial matches for S on each remaining pass.\n \n \n pass 1: a b a b a b c b c b a b a b c b c\n ^ ^ ^ ^ ^ ^\n\n pass 2: a b a b * * * b c b a b * * * b c\n ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^ ^\n\n pass 3: a b * * * * * * * b * * * * * * *\n ^ ^ ^ ^ ^ ^\n\n pass 4: * * * * * * * * * * * * * * * * *\n \n \n See carefully what we are doing everytime we are finding stamp in our target and making it "????" \n \n Now the key concept is whenever we find our target and stamp like this\n target = "???ab??"\n stamp = dabc\n \n then "?ab?" == "dabc"\n why ??\n See we are going reverse so the steps we are taking is also reverse\n Since we have put ? anywhere means that we got it right !\n so once we put "dabc" in place of "?ab?" we know that our previous turn is going to solve for the two ? marks any way\n \n```\n\n# CODE\n```\nclass Solution:\n def movesToStamp(self, stamp: str, target: str) -> List[int]:\n N,M = len(target),len(stamp)\n move = 0\n maxmove = 10*N\n ans = []\n def check(string):\n for i in range(M):\n if string[i] == stamp[i] or string[i] == \'?\':\n continue\n else:\n return False\n return True\n \n while move < maxmove:\n premove = move\n for i in range(N-M+1):\n if check(target[i:i+M]):\n move += 1\n ans.append(i)\n target = target[:i] + "?"*M + target[i+M:]\n if target == "?"*N : return ans[::-1]\n if premove == move:return []\n return []\n``` | 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 **any order**. The answer is **guaranteed** to be **unique** (except for the order that it is in).
**Example 1:**
**Input:** points = \[\[1,3\],\[-2,2\]\], k = 1
**Output:** \[\[-2,2\]\]
**Explanation:**
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just \[\[-2,2\]\].
**Example 2:**
**Input:** points = \[\[3,3\],\[5,-1\],\[-2,4\]\], k = 2
**Output:** \[\[3,3\],\[-2,4\]\]
**Explanation:** The answer \[\[-2,4\],\[3,3\]\] would also be accepted.
**Constraints:**
* `1 <= k <= points.length <= 104`
* `-104 < xi, yi < 104` | 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 solution with the smallest number of turns and where the indexes are as much as possible in increasing order.\n\n- The comment in the problem description about "*at most 10 * `target.length` turns*" makes absolutely no sense, as if solutions exist then there is at least one with at most `target.length-stamp.length+1` turns...\n\n- The code I present here is not the most concise but:\n - I wanted an iterative solution and to avoid auxiliary function calls.\n - I haven\'t had the time to try and make it nicer.\n\n# Approach\n- We move backward in time, identifying turns from the last one to the first one.\n\n- If we split the target by all the occurrences of the full stamp, then:\n - For the left-most part, the stamp can only spread further to the right.\n - For the right-most part, the stamp can only spread further to the left.\n - For all the middle parts, the stamp can spread further on both sides.\n\n- Based on the objective mentioned in the second note above, our backward analysis:\n - Starts with the right-most occurrence of the full stamp.\n - Then processes its right part, which is the right-most part with no occurrences of the full stamp.\n We reduce it from its end by repeatedly trying to find the largest trailing part of the stamp that matches it.\n - Then iteratively, until there are no more occurrences of the full stamp:\n - Finds the next right-most occurrence of the full stamp.\n - And processes the part between it and the occurrence of the full stamp previously processed:\n - In the case it is shorter than the stamp, we use the right-most occurrence of it in the stamp if any.\n - Otherwise, we repeatedly try to reduce it as much as possible from its end first (as described above) and then from its start (as described below).\n - Finally processes the left part of the last found occurrence, which is the left-most part with no occurrences of the full stamp.\n We reduce it from its start by repeatedly trying to find the largest leading part of the stamp that matches it.\n- At the end, we reverse the list of indexes built along the way.\n\n# Complexity\n\n- Time: `O(T*S)`, assuming string slicing to be `O(1)`\n where `S` and `T` are the numbers of characters in `stamp` and `target` respectively\n- Space: `O(T)`\n\n# Code\n\nThe code below gave me: `Runtime: 36 ms, faster than 100.00% of Python3 online submissions`\n\n```\nfrom typing import List\n\n\nclass Solution:\n def movesToStamp(self, stamp: str, target: str) -> List[int]:\n # The stamp and target must start with the same letter and end with the same letter\n if stamp[0] != target[0] or stamp[-1] != target[-1]:\n return []\n\n # The target must contain at least one occurrence of the full stamp\n idx = target.rfind(stamp)\n if idx == -1:\n return []\n\n res = [idx]\n stampSize = len(stamp)\n rightTargetOffset = idx + stampSize\n leftTarget, rightTarget = target[:idx], target[rightTargetOffset:]\n\n # Handle the right-most part that doesn\'t contain the full stamp; for it, the stamp can only spread further to the left\n while rightTarget:\n # Try reduction by the left\n rightTargetSize = len(rightTarget)\n for stampStartIdx in range(max(1, stampSize - rightTargetSize), stampSize):\n if rightTarget.startswith(stamp[stampStartIdx:]):\n res.append(rightTargetOffset - stampStartIdx)\n subStampSize = stampSize - stampStartIdx\n rightTargetOffset += subStampSize\n rightTarget = rightTarget[subStampSize:]\n break\n else:\n # No reduction possible, so the problem is impossible\n return []\n\n while True:\n # Find the next right-most occurrence of the full stamp, if any\n idx = leftTarget.rfind(stamp)\n if idx == -1:\n break\n\n res.append(idx)\n rightTargetOffset = idx + stampSize\n leftTarget, rightTarget = leftTarget[:idx], leftTarget[rightTargetOffset:]\n\n # Handle a middle part that doesn\'t contain the full stamp; for it, the stamp can spread further both to the left and to the right\n while rightTarget:\n rightTargetSize = len(rightTarget)\n\n # If the part is shorter than the stamp, then we can check whether the stamp contains it\n if rightTargetSize < stampSize:\n idx = stamp.rfind(rightTarget)\n if idx != -1:\n res.append(rightTargetOffset - idx)\n rightTarget = "" # Not needed but just for clarity\n break\n\n # Otherwise, try maximum reduction by the right first and then by the left\n for subStampSize in range(min(stampSize - 1, rightTargetSize), 0, -1):\n # Try reduction by the right first\n stampEndIdx = subStampSize\n if rightTarget.endswith(stamp[:stampEndIdx]):\n res.append(rightTargetOffset + rightTargetSize - stampEndIdx)\n rightTarget = rightTarget[:-stampEndIdx]\n break\n # And then by the left\n stampStartIdx = stampSize - subStampSize\n if rightTarget.startswith(stamp[stampStartIdx:]):\n res.append(rightTargetOffset - stampStartIdx)\n subStampSize = stampSize - stampStartIdx\n rightTargetOffset += subStampSize\n rightTarget = rightTarget[subStampSize:]\n break\n else:\n # No reduction possible at all, so the problem is impossible\n return []\n\n # Handle the left-most part that doesn\'t contain the full stamp; for it, the stamp can only spread further to the right\n while leftTarget:\n # Try reduction by the right\n leftTargetSize = len(leftTarget)\n for stampEndIdx in range(min(stampSize - 1, leftTargetSize), 0, -1):\n if leftTarget.endswith(stamp[:stampEndIdx]):\n res.append(leftTargetSize - stampEndIdx)\n leftTarget = leftTarget[:-stampEndIdx]\n break\n else:\n # No reduction possible, so the problem is impossible\n return []\n\n res.reverse()\n return res\n``` | 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 "`, then `s` is `"????? "` initially. In one turn you can:
* place `stamp` at index `0` of `s` to obtain `"abc?? "`,
* place `stamp` at index `1` of `s` to obtain `"?abc? "`, or
* place `stamp` at index `2` of `s` to obtain `"??abc "`.
Note that `stamp` must be fully contained in the boundaries of `s` in order to stamp (i.e., you cannot place `stamp` at index `3` of `s`).
We want to convert `s` to `target` using **at most** `10 * target.length` turns.
Return _an array of the index of the left-most letter being stamped at each turn_. If we cannot obtain `target` from `s` within `10 * target.length` turns, return an empty array.
**Example 1:**
**Input:** stamp = "abc ", target = "ababc "
**Output:** \[0,2\]
**Explanation:** Initially s = "????? ".
- Place stamp at index 0 to get "abc?? ".
- Place stamp at index 2 to get "ababc ".
\[1,0,2\] would also be accepted as an answer, as well as some other answers.
**Example 2:**
**Input:** stamp = "abca ", target = "aabcaca "
**Output:** \[3,0,1\]
**Explanation:** Initially s = "??????? ".
- Place stamp at index 3 to get "???abca ".
- Place stamp at index 0 to get "abcabca ".
- Place stamp at index 1 to get "aabcaca ".
**Constraints:**
* `1 <= stamp.length <= target.length <= 1000`
* `stamp` and `target` consist of lowercase English letters. | 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 solution with the smallest number of turns and where the indexes are as much as possible in increasing order.\n\n- The comment in the problem description about "*at most 10 * `target.length` turns*" makes absolutely no sense, as if solutions exist then there is at least one with at most `target.length-stamp.length+1` turns...\n\n- The code I present here is not the most concise but:\n - I wanted an iterative solution and to avoid auxiliary function calls.\n - I haven\'t had the time to try and make it nicer.\n\n# Approach\n- We move backward in time, identifying turns from the last one to the first one.\n\n- If we split the target by all the occurrences of the full stamp, then:\n - For the left-most part, the stamp can only spread further to the right.\n - For the right-most part, the stamp can only spread further to the left.\n - For all the middle parts, the stamp can spread further on both sides.\n\n- Based on the objective mentioned in the second note above, our backward analysis:\n - Starts with the right-most occurrence of the full stamp.\n - Then processes its right part, which is the right-most part with no occurrences of the full stamp.\n We reduce it from its end by repeatedly trying to find the largest trailing part of the stamp that matches it.\n - Then iteratively, until there are no more occurrences of the full stamp:\n - Finds the next right-most occurrence of the full stamp.\n - And processes the part between it and the occurrence of the full stamp previously processed:\n - In the case it is shorter than the stamp, we use the right-most occurrence of it in the stamp if any.\n - Otherwise, we repeatedly try to reduce it as much as possible from its end first (as described above) and then from its start (as described below).\n - Finally processes the left part of the last found occurrence, which is the left-most part with no occurrences of the full stamp.\n We reduce it from its start by repeatedly trying to find the largest leading part of the stamp that matches it.\n- At the end, we reverse the list of indexes built along the way.\n\n# Complexity\n\n- Time: `O(T*S)`, assuming string slicing to be `O(1)`\n where `S` and `T` are the numbers of characters in `stamp` and `target` respectively\n- Space: `O(T)`\n\n# Code\n\nThe code below gave me: `Runtime: 36 ms, faster than 100.00% of Python3 online submissions`\n\n```\nfrom typing import List\n\n\nclass Solution:\n def movesToStamp(self, stamp: str, target: str) -> List[int]:\n # The stamp and target must start with the same letter and end with the same letter\n if stamp[0] != target[0] or stamp[-1] != target[-1]:\n return []\n\n # The target must contain at least one occurrence of the full stamp\n idx = target.rfind(stamp)\n if idx == -1:\n return []\n\n res = [idx]\n stampSize = len(stamp)\n rightTargetOffset = idx + stampSize\n leftTarget, rightTarget = target[:idx], target[rightTargetOffset:]\n\n # Handle the right-most part that doesn\'t contain the full stamp; for it, the stamp can only spread further to the left\n while rightTarget:\n # Try reduction by the left\n rightTargetSize = len(rightTarget)\n for stampStartIdx in range(max(1, stampSize - rightTargetSize), stampSize):\n if rightTarget.startswith(stamp[stampStartIdx:]):\n res.append(rightTargetOffset - stampStartIdx)\n subStampSize = stampSize - stampStartIdx\n rightTargetOffset += subStampSize\n rightTarget = rightTarget[subStampSize:]\n break\n else:\n # No reduction possible, so the problem is impossible\n return []\n\n while True:\n # Find the next right-most occurrence of the full stamp, if any\n idx = leftTarget.rfind(stamp)\n if idx == -1:\n break\n\n res.append(idx)\n rightTargetOffset = idx + stampSize\n leftTarget, rightTarget = leftTarget[:idx], leftTarget[rightTargetOffset:]\n\n # Handle a middle part that doesn\'t contain the full stamp; for it, the stamp can spread further both to the left and to the right\n while rightTarget:\n rightTargetSize = len(rightTarget)\n\n # If the part is shorter than the stamp, then we can check whether the stamp contains it\n if rightTargetSize < stampSize:\n idx = stamp.rfind(rightTarget)\n if idx != -1:\n res.append(rightTargetOffset - idx)\n rightTarget = "" # Not needed but just for clarity\n break\n\n # Otherwise, try maximum reduction by the right first and then by the left\n for subStampSize in range(min(stampSize - 1, rightTargetSize), 0, -1):\n # Try reduction by the right first\n stampEndIdx = subStampSize\n if rightTarget.endswith(stamp[:stampEndIdx]):\n res.append(rightTargetOffset + rightTargetSize - stampEndIdx)\n rightTarget = rightTarget[:-stampEndIdx]\n break\n # And then by the left\n stampStartIdx = stampSize - subStampSize\n if rightTarget.startswith(stamp[stampStartIdx:]):\n res.append(rightTargetOffset - stampStartIdx)\n subStampSize = stampSize - stampStartIdx\n rightTargetOffset += subStampSize\n rightTarget = rightTarget[subStampSize:]\n break\n else:\n # No reduction possible at all, so the problem is impossible\n return []\n\n # Handle the left-most part that doesn\'t contain the full stamp; for it, the stamp can only spread further to the right\n while leftTarget:\n # Try reduction by the right\n leftTargetSize = len(leftTarget)\n for stampEndIdx in range(min(stampSize - 1, leftTargetSize), 0, -1):\n if leftTarget.endswith(stamp[:stampEndIdx]):\n res.append(leftTargetSize - stampEndIdx)\n leftTarget = leftTarget[:-stampEndIdx]\n break\n else:\n # No reduction possible, so the problem is impossible\n return []\n\n res.reverse()\n return res\n``` | 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 **any order**. The answer is **guaranteed** to be **unique** (except for the order that it is in).
**Example 1:**
**Input:** points = \[\[1,3\],\[-2,2\]\], k = 1
**Output:** \[\[-2,2\]\]
**Explanation:**
The distance between (1, 3) and the origin is sqrt(10).
The distance between (-2, 2) and the origin is sqrt(8).
Since sqrt(8) < sqrt(10), (-2, 2) is closer to the origin.
We only want the closest k = 1 points from the origin, so the answer is just \[\[-2,2\]\].
**Example 2:**
**Input:** points = \[\[3,3\],\[5,-1\],\[-2,4\]\], k = 2
**Output:** \[\[3,3\],\[-2,4\]\]
**Explanation:** The answer \[\[-2,4\],\[3,3\]\] would also be accepted.
**Constraints:**
* `1 <= k <= points.length <= 104`
* `-104 < xi, yi < 104` | 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)\n```\n```python3 []\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n def customSort(s):\n idx, log = s.split(\' \', 1)\n if log[0].isalpha(): return (0, log, idx)\n return (1,)\n\n return sorted(logs, key=customSort)\n```\n\n | 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.
Reorder these logs so that:
1. The **letter-logs** come before all **digit-logs**.
2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
3. The **digit-logs** maintain their relative ordering.
Return _the final order of the logs_.
**Example 1:**
**Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\]
**Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\]
**Explanation:**
The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ".
The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ".
**Example 2:**
**Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\]
**Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\]
**Constraints:**
* `1 <= logs.length <= 100`
* `3 <= logs[i].length <= 100`
* All the tokens of `logs[i]` are separated by a **single** space.
* `logs[i]` is guaranteed to have an identifier and at least one word after the identifier. | 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)\n```\n```python3 []\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n def customSort(s):\n idx, log = s.split(\' \', 1)\n if log[0].isalpha(): return (0, log, idx)\n return (1,)\n\n return sorted(logs, key=customSort)\n```\n\n | 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 by k = 5:
\[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\]
**Example 2:**
**Input:** nums = \[5\], k = 9
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `2 <= k <= 104` | 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 trailing comma so they are not confused with a simple one (1) or 1 by python.\n\t\t\t\treturn (1,)\n\t\t\t\n\t\t\t# Is an alphabetical log, use 0 so they are always to the left of the numerical logs, \n\t\t\t# then use the more complex sorting rules for just the alphabetical logs.\n left_side, right_side = log.split(" ", 1)\n return (0, right_side, left_side)\n\n\t\t# Sort the logs according to the function we defined.\n return sorted(logs, key=sorting_algorithm)\n```\nO(nlogn * m) time complexity where n is the number of strings and m is the max length of the strings. The .split() function operates with O(m) time within each string. The sorting function operates with O(nlogn) time for the strings.\n\nO(mlogn) space complexity where n is the number of strings and m is the max length of the strings. The built in python sorting algorithm uses log(n) space, holding onto the split logs uses up O(m) space for each sorting step.\n\n\nSame idea as above, this approach is explained with a long description below:\n```\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n def sorting_algorithm(log):\n left_side, right_side = log.split(" ", 1)\n\n if right_side[0].isalpha():\n return (0, right_side, left_side)\n else:\n return (1,)\n\n return sorted(logs, key=sorting_algorithm)\n```\n\nWe split each log into a list with two entries so the following log:\n`"dig1 8 1 5 1"`\nTurns into the following:\n`["dig1", "8 1 5 1"]`\n\nThe log.split(" ", 1) means to only at most one time, from left to right, upon encountering a white-space character, split the string into two strings and store the two strings in a list.\n\nThen we look at the second string, or the right_side in this case of "8 1 5 1", we can see that the first character of 8, which is from right_side[0] is not an alpha character, with .isalpha() only returning true when a character is any lowercase or uppercase character from "a-z".\n\nFor a log like "let1 art can", right_side[0].isalpha() would be applied to the letter \'a\' in this case, and would return true. \n\nWhat we are returning from this function informs the sorted() function how sorted() ought to behave. The return of (0, right_side, left_side) tells sorted() to sort this entire log with a priority of 0, which is lower in value than 1, so any log with a right_side that begins with a letter will come before any log with a right_side that begins with a number.\n\nAfter ensuring that the logs with letters in the right_side come first, the letter logs are further sorted alpha-numerically by the contents of their entire right side, then if the right_sides still match, they are sorted even further based on the contents of their left_sides, alpha-numerically with the sorted() function.\n\nThe second return statement is missing instructions on how to be sorted with only (1,) passed into it, missing the second argument. The logs with digits in their right_side only know that they must come after the letter logs, and they do not sort because they have no rule to sort by in the second argument. \n\nWe have to write it as (1, ) because this is a tuple, I think of it as just (1), but we cannot write (1) because Python would think of it as just 1, rather than as a tuple with one element. We are specifying the sorting rules for the sort algorithm by returning tuples.\n\nThe logs are then sorted() with the sorting logic provided by sorting_algorithm. The key in sorted() is an optional argument that allows us to attach our own custom function to override the default sorting behaviour. \n\nThe built in sorting algorithm is used, which is TimSort in Python, most relevant sorting algorithms including this one provide a worst case run time of O(nlog(n)) and a space of O(n).\n\n\n | 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.
Reorder these logs so that:
1. The **letter-logs** come before all **digit-logs**.
2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
3. The **digit-logs** maintain their relative ordering.
Return _the final order of the logs_.
**Example 1:**
**Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\]
**Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\]
**Explanation:**
The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ".
The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ".
**Example 2:**
**Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\]
**Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\]
**Constraints:**
* `1 <= logs.length <= 100`
* `3 <= logs[i].length <= 100`
* All the tokens of `logs[i]` are separated by a **single** space.
* `logs[i]` is guaranteed to have an identifier and at least one word after the identifier. | 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 trailing comma so they are not confused with a simple one (1) or 1 by python.\n\t\t\t\treturn (1,)\n\t\t\t\n\t\t\t# Is an alphabetical log, use 0 so they are always to the left of the numerical logs, \n\t\t\t# then use the more complex sorting rules for just the alphabetical logs.\n left_side, right_side = log.split(" ", 1)\n return (0, right_side, left_side)\n\n\t\t# Sort the logs according to the function we defined.\n return sorted(logs, key=sorting_algorithm)\n```\nO(nlogn * m) time complexity where n is the number of strings and m is the max length of the strings. The .split() function operates with O(m) time within each string. The sorting function operates with O(nlogn) time for the strings.\n\nO(mlogn) space complexity where n is the number of strings and m is the max length of the strings. The built in python sorting algorithm uses log(n) space, holding onto the split logs uses up O(m) space for each sorting step.\n\n\nSame idea as above, this approach is explained with a long description below:\n```\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n def sorting_algorithm(log):\n left_side, right_side = log.split(" ", 1)\n\n if right_side[0].isalpha():\n return (0, right_side, left_side)\n else:\n return (1,)\n\n return sorted(logs, key=sorting_algorithm)\n```\n\nWe split each log into a list with two entries so the following log:\n`"dig1 8 1 5 1"`\nTurns into the following:\n`["dig1", "8 1 5 1"]`\n\nThe log.split(" ", 1) means to only at most one time, from left to right, upon encountering a white-space character, split the string into two strings and store the two strings in a list.\n\nThen we look at the second string, or the right_side in this case of "8 1 5 1", we can see that the first character of 8, which is from right_side[0] is not an alpha character, with .isalpha() only returning true when a character is any lowercase or uppercase character from "a-z".\n\nFor a log like "let1 art can", right_side[0].isalpha() would be applied to the letter \'a\' in this case, and would return true. \n\nWhat we are returning from this function informs the sorted() function how sorted() ought to behave. The return of (0, right_side, left_side) tells sorted() to sort this entire log with a priority of 0, which is lower in value than 1, so any log with a right_side that begins with a letter will come before any log with a right_side that begins with a number.\n\nAfter ensuring that the logs with letters in the right_side come first, the letter logs are further sorted alpha-numerically by the contents of their entire right side, then if the right_sides still match, they are sorted even further based on the contents of their left_sides, alpha-numerically with the sorted() function.\n\nThe second return statement is missing instructions on how to be sorted with only (1,) passed into it, missing the second argument. The logs with digits in their right_side only know that they must come after the letter logs, and they do not sort because they have no rule to sort by in the second argument. \n\nWe have to write it as (1, ) because this is a tuple, I think of it as just (1), but we cannot write (1) because Python would think of it as just 1, rather than as a tuple with one element. We are specifying the sorting rules for the sort algorithm by returning tuples.\n\nThe logs are then sorted() with the sorting logic provided by sorting_algorithm. The key in sorted() is an optional argument that allows us to attach our own custom function to override the default sorting behaviour. \n\nThe built in sorting algorithm is used, which is TimSort in Python, most relevant sorting algorithms including this one provide a worst case run time of O(nlog(n)) and a space of O(n).\n\n\n | 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 by k = 5:
\[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\]
**Example 2:**
**Input:** nums = \[5\], k = 9
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `2 <= k <= 104` | 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)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python\nclass Log:\n def __init__(self, log):\n self.log = log\n\n def __eq__(self, other):\n return self.log == other.log\n\n def __lt__(self, other):\n id1, *rest1 = self.log.split(" ")\n id2, *rest2 = other.log.split(" ")\n if rest1 == rest2:\n return id1 < id2\n else:\n return " ".join(rest1) < " ".join(rest2)\n\n def __gt__(self, other):\n id1, *rest1 = self.log.split(" ")\n id2, *rest2 = other.log.split(" ")\n if rest1 == rest2:\n return id1 > id2\n else:\n return " ".join(rest1) > " ".join(rest2)\n\n def __repr__(self):\n return self.log\n\n\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n\n digit_logs, letter_logs = [], []\n for log in logs:\n identifier, first, *rest = log.split(" ")\n if first.isdigit():\n digit_logs.append(log)\n else:\n log = Log(log)\n bisect.insort(letter_logs, log)\n \n return [l.log for l in letter_logs] + digit_logs\n \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.
Reorder these logs so that:
1. The **letter-logs** come before all **digit-logs**.
2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
3. The **digit-logs** maintain their relative ordering.
Return _the final order of the logs_.
**Example 1:**
**Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\]
**Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\]
**Explanation:**
The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ".
The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ".
**Example 2:**
**Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\]
**Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\]
**Constraints:**
* `1 <= logs.length <= 100`
* `3 <= logs[i].length <= 100`
* All the tokens of `logs[i]` are separated by a **single** space.
* `logs[i]` is guaranteed to have an identifier and at least one word after the identifier. | 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)`\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```python\nclass Log:\n def __init__(self, log):\n self.log = log\n\n def __eq__(self, other):\n return self.log == other.log\n\n def __lt__(self, other):\n id1, *rest1 = self.log.split(" ")\n id2, *rest2 = other.log.split(" ")\n if rest1 == rest2:\n return id1 < id2\n else:\n return " ".join(rest1) < " ".join(rest2)\n\n def __gt__(self, other):\n id1, *rest1 = self.log.split(" ")\n id2, *rest2 = other.log.split(" ")\n if rest1 == rest2:\n return id1 > id2\n else:\n return " ".join(rest1) > " ".join(rest2)\n\n def __repr__(self):\n return self.log\n\n\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n\n digit_logs, letter_logs = [], []\n for log in logs:\n identifier, first, *rest = log.split(" ")\n if first.isdigit():\n digit_logs.append(log)\n else:\n log = Log(log)\n bisect.insort(letter_logs, log)\n \n return [l.log for l in letter_logs] + digit_logs\n \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 by k = 5:
\[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\]
**Example 2:**
**Input:** nums = \[5\], k = 9
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `2 <= k <= 104` | 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, maxsplit)\nword = \'I, like, algorithm, and, datastructure\'\n \n# maxsplit: 0 \nprint(word.split(\', \', 0)) \n >>[\'I, like, algorithm, and, datastructure\'] \n\n# maxsplit: 4 \nprint(word.split(\', \', 4)) \n>>[\'I\', \'like\', \'algorithm\', \'and\', \'datastructure\']\n\n\n# maxsplit: 1 \nprint(word.split(\', \', 1)) \n>>[\'I\', \'like, algorithm, and, datastructure\']\n\n```\n```\nInput: logs = [\n\t\t\t\t"dig1 8 1 5 1",\n\t\t\t\t"let1 art can",\n\t\t\t\t"dig2 3 6",\n\t\t\t\t"let2 own kit dig",\n\t\t\t\t"let3 art zero"]\n\t\t\t\t\n# a, b = log.split(" ", 1)\n\na: a1 b: 9 2 3 1\na: g1 b: act car\na: zo4 b: 4 7\na: ab1 b: off key dog\na: a8 b: act zoo\n\nOutput = [\n\t\t\t"let1 art can",\n\t\t\t"let3 art zero",\n\t\t\t"let2 own kit dig",\n\t\t\t"dig1 8 1 5 1",\n\t\t\t"dig2 3 6"]\n```\nBy default, sort(key) means to sort the list by key in increasing order.\nif b[0] is letter: key = (0,b,a)\nIf b[0] is not letter: key = (1,None,None)\n **effect of use (None,None) is when you sort letter-logs, the digit-logs remain in the same order.**\n(1,) is short for (1,None,None). \nstep 1: 0 < 1: so letter-logs come before any digit-log.\nwe get:\n["let1 art can","let2 own kit dig","let3 art zero","dig1 8 1 5 1","dig2 3 6"]\nstep 2: b and None The letter-logs are sorted lexicographically by contend(b), the digit-logs remain in the same order\nWe get:\n["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]\nstep3: a and None, The letter-logs are sorted lexicographically by identifier(a), the digit-logs remain in the same order.\nWe get:\n["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]\n\n```\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n return sorted(logs,key = self.sort)\n def sort(self,logs):\n a,b = logs.split(\' \', 1)\n if b[0].isalpha():\n return (0,b,a)\n else:\n return (1,None,None)\n``` | 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.
Reorder these logs so that:
1. The **letter-logs** come before all **digit-logs**.
2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
3. The **digit-logs** maintain their relative ordering.
Return _the final order of the logs_.
**Example 1:**
**Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\]
**Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\]
**Explanation:**
The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ".
The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ".
**Example 2:**
**Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\]
**Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\]
**Constraints:**
* `1 <= logs.length <= 100`
* `3 <= logs[i].length <= 100`
* All the tokens of `logs[i]` are separated by a **single** space.
* `logs[i]` is guaranteed to have an identifier and at least one word after the identifier. | 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, maxsplit)\nword = \'I, like, algorithm, and, datastructure\'\n \n# maxsplit: 0 \nprint(word.split(\', \', 0)) \n >>[\'I, like, algorithm, and, datastructure\'] \n\n# maxsplit: 4 \nprint(word.split(\', \', 4)) \n>>[\'I\', \'like\', \'algorithm\', \'and\', \'datastructure\']\n\n\n# maxsplit: 1 \nprint(word.split(\', \', 1)) \n>>[\'I\', \'like, algorithm, and, datastructure\']\n\n```\n```\nInput: logs = [\n\t\t\t\t"dig1 8 1 5 1",\n\t\t\t\t"let1 art can",\n\t\t\t\t"dig2 3 6",\n\t\t\t\t"let2 own kit dig",\n\t\t\t\t"let3 art zero"]\n\t\t\t\t\n# a, b = log.split(" ", 1)\n\na: a1 b: 9 2 3 1\na: g1 b: act car\na: zo4 b: 4 7\na: ab1 b: off key dog\na: a8 b: act zoo\n\nOutput = [\n\t\t\t"let1 art can",\n\t\t\t"let3 art zero",\n\t\t\t"let2 own kit dig",\n\t\t\t"dig1 8 1 5 1",\n\t\t\t"dig2 3 6"]\n```\nBy default, sort(key) means to sort the list by key in increasing order.\nif b[0] is letter: key = (0,b,a)\nIf b[0] is not letter: key = (1,None,None)\n **effect of use (None,None) is when you sort letter-logs, the digit-logs remain in the same order.**\n(1,) is short for (1,None,None). \nstep 1: 0 < 1: so letter-logs come before any digit-log.\nwe get:\n["let1 art can","let2 own kit dig","let3 art zero","dig1 8 1 5 1","dig2 3 6"]\nstep 2: b and None The letter-logs are sorted lexicographically by contend(b), the digit-logs remain in the same order\nWe get:\n["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]\nstep3: a and None, The letter-logs are sorted lexicographically by identifier(a), the digit-logs remain in the same order.\nWe get:\n["let1 art can","let3 art zero","let2 own kit dig","dig1 8 1 5 1","dig2 3 6"]\n\n```\nclass Solution:\n def reorderLogFiles(self, logs: List[str]) -> List[str]:\n return sorted(logs,key = self.sort)\n def sort(self,logs):\n a,b = logs.split(\' \', 1)\n if b[0].isalpha():\n return (0,b,a)\n else:\n return (1,None,None)\n``` | 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 by k = 5:
\[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\]
**Example 2:**
**Input:** nums = \[5\], k = 9
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `2 <= k <= 104` | 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 = [x.split(" ", maxsplit=1) for x in letter]\n \n letter = sorted(letter, key = lambda x: (x[1], x[0]))\n \n letter = [\' \'.join(map(str, x)) for x in letter]\n \n return letter + digit \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.
Reorder these logs so that:
1. The **letter-logs** come before all **digit-logs**.
2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
3. The **digit-logs** maintain their relative ordering.
Return _the final order of the logs_.
**Example 1:**
**Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\]
**Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\]
**Explanation:**
The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ".
The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ".
**Example 2:**
**Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\]
**Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\]
**Constraints:**
* `1 <= logs.length <= 100`
* `3 <= logs[i].length <= 100`
* All the tokens of `logs[i]` are separated by a **single** space.
* `logs[i]` is guaranteed to have an identifier and at least one word after the identifier. | 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 = [x.split(" ", maxsplit=1) for x in letter]\n \n letter = sorted(letter, key = lambda x: (x[1], x[0]))\n \n letter = [\' \'.join(map(str, x)) for x in letter]\n \n return letter + digit \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 by k = 5:
\[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\]
**Example 2:**
**Input:** nums = \[5\], k = 9
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `2 <= k <= 104` | 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(key = lambda x : x.split()[1:])\n return l + d\n```\n**If you like this solution, please upvote for this** | 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.
Reorder these logs so that:
1. The **letter-logs** come before all **digit-logs**.
2. The **letter-logs** are sorted lexicographically by their contents. If their contents are the same, then sort them lexicographically by their identifiers.
3. The **digit-logs** maintain their relative ordering.
Return _the final order of the logs_.
**Example 1:**
**Input:** logs = \[ "dig1 8 1 5 1 ", "let1 art can ", "dig2 3 6 ", "let2 own kit dig ", "let3 art zero "\]
**Output:** \[ "let1 art can ", "let3 art zero ", "let2 own kit dig ", "dig1 8 1 5 1 ", "dig2 3 6 "\]
**Explanation:**
The letter-log contents are all different, so their ordering is "art can ", "art zero ", "own kit dig ".
The digit-logs have a relative order of "dig1 8 1 5 1 ", "dig2 3 6 ".
**Example 2:**
**Input:** logs = \[ "a1 9 2 3 1 ", "g1 act car ", "zo4 4 7 ", "ab1 off key dog ", "a8 act zoo "\]
**Output:** \[ "g1 act car ", "a8 act zoo ", "ab1 off key dog ", "a1 9 2 3 1 ", "zo4 4 7 "\]
**Constraints:**
* `1 <= logs.length <= 100`
* `3 <= logs[i].length <= 100`
* All the tokens of `logs[i]` are separated by a **single** space.
* `logs[i]` is guaranteed to have an identifier and at least one word after the identifier. | 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(key = lambda x : x.split()[1:])\n return l + d\n```\n**If you like this solution, please upvote for this** | 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 by k = 5:
\[4, 5, 0, -2, -3, 1\], \[5\], \[5, 0\], \[5, 0, -2, -3\], \[0\], \[0, -2, -3\], \[-2, -3\]
**Example 2:**
**Input:** nums = \[5\], k = 9
**Output:** 0
**Constraints:**
* `1 <= nums.length <= 3 * 104`
* `-104 <= nums[i] <= 104`
* `2 <= k <= 104` | 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)$$ -->\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# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n l=[]\n def traversal(root):\n if root is None:\n return\n l.append(root.val)\n traversal(root.left)\n traversal(root.right)\n traversal(root)\n sum_=0\n for i in l:\n if i>=low and i<=high:\n sum_+=i\n return sum_\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 range \[7, 15\]. 7 + 10 + 15 = 32.
**Example 2:**
**Input:** root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10
**Output:** 23
**Explanation:** Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10 = 23.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 2 * 104]`.
* `1 <= Node.val <= 105`
* `1 <= low <= high <= 105`
* All `Node.val` are **unique**. | 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)$$ -->\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# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:\n l=[]\n def traversal(root):\n if root is None:\n return\n l.append(root.val)\n traversal(root.left)\n traversal(root.right)\n traversal(root)\n sum_=0\n for i in l:\n if i>=low and i<=high:\n sum_+=i\n return sum_\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 may jump forward from index `i` to index `j` (with `i < j`) in the following way:
* During **odd-numbered jumps** (i.e., jumps 1, 3, 5, ...), you jump to the index `j` such that `arr[i] <= arr[j]` and `arr[j]` is the smallest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`.
* During **even-numbered jumps** (i.e., jumps 2, 4, 6, ...), you jump to the index `j` such that `arr[i] >= arr[j]` and `arr[j]` is the largest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`.
* It may be the case that for some index `i`, there are no legal jumps.
A starting index is **good** if, starting from that index, you can reach the end of the array (index `arr.length - 1`) by jumping some number of times (possibly 0 or more than once).
Return _the number of **good** starting indices_.
**Example 1:**
**Input:** arr = \[10,13,12,14,15\]
**Output:** 2
**Explanation:**
From starting index i = 0, we can make our 1st jump to i = 2 (since arr\[2\] is the smallest among arr\[1\], arr\[2\], arr\[3\], arr\[4\] that is greater or equal to arr\[0\]), then we cannot jump any more.
From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.
From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.
From starting index i = 4, we have reached the end already.
In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of
jumps.
**Example 2:**
**Input:** arr = \[2,3,1,1,4\]
**Output:** 3
**Explanation:**
From starting index i = 0, we make jumps to i = 1, i = 2, i = 3:
During our 1st jump (odd-numbered), we first jump to i = 1 because arr\[1\] is the smallest value in \[arr\[1\], arr\[2\], arr\[3\], arr\[4\]\] that is greater than or equal to arr\[0\].
During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr\[2\] is the largest value in \[arr\[2\], arr\[3\], arr\[4\]\] that is less than or equal to arr\[1\]. arr\[3\] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3
During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr\[3\] is the smallest value in \[arr\[3\], arr\[4\]\] that is greater than or equal to arr\[2\].
We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.
In a similar manner, we can deduce that:
From starting index i = 1, we jump to i = 4, so we reach the end.
From starting index i = 2, we jump to i = 3, and then we can't jump anymore.
From starting index i = 3, we jump to i = 4, so we reach the end.
From starting index i = 4, we are already at the end.
In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some
number of jumps.
**Example 3:**
**Input:** arr = \[5,1,3,4,2\]
**Output:** 3
**Explanation:** We can reach the end from starting indices 1, 2, and 4.
**Constraints:**
* `1 <= arr.length <= 2 * 104`
* `0 <= arr[i] < 105` | 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) return rangeSumBST(root.left, L, R); // right branch excluded.\n return root.val + rangeSumBST(root.right, L, R) + rangeSumBST(root.left, L, R); // count in both children.\n }\n```\n```\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n if not root:\n return 0\n elif root.val < L:\n return self.rangeSumBST(root.right, L, R)\n elif root.val > R:\n return self.rangeSumBST(root.left, L, R)\n return root.val + self.rangeSumBST(root.left, L, R) + self.rangeSumBST(root.right, L, R)\n```\nThe following are two more similar recursive codes.\n\n**Method 2:**\n```\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (root == null) return 0; // base case.\n return (L <= root.val && root.val <= R ? root.val : 0) + rangeSumBST(root.right, L, R) + rangeSumBST(root.left, L, R);\n }\n```\n```\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n if not root:\n return 0\n return self.rangeSumBST(root.left, L, R) + \\\n self.rangeSumBST(root.right, L, R) + \\\n (root.val if L <= root.val <= R else 0)\n```\n**Method 3:**\n```\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (root == null) { return 0; }\n int sum = 0;\n if (root.val > L) { sum += rangeSumBST(root.left, L, R); } // left child is a possible candidate.\n if (root.val < R) { sum += rangeSumBST(root.right, L, R); } // right child is a possible candidate.\n if (root.val >= L && root.val <= R) { sum += root.val; } // count root in.\n return sum;\n }\n```\n```\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n if not root:\n return 0\n sum = 0\n if root.val > L:\n sum += self.rangeSumBST(root.left, L, R)\n if root.val < R:\n sum += self.rangeSumBST(root.right, L, R)\n if L <= root.val <= R:\n sum += root.val \n return sum\n```\n\n**Method 4: Iterative version**\n```\n public int rangeSumBST(TreeNode root, int L, int R) {\n Stack<TreeNode> stk = new Stack<>();\n stk.push(root);\n int sum = 0;\n while (!stk.isEmpty()) {\n TreeNode n = stk.pop();\n if (n == null) { continue; }\n if (n.val > L) { stk.push(n.left); } // left child is a possible candidate.\n if (n.val < R) { stk.push(n.right); } // right child is a possible candidate.\n if (L <= n.val && n.val <= R) { sum += n.val; }\n }\n return sum;\n }\n```\n```\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n stk, sum = [root], 0\n while stk:\n node = stk.pop()\n if node:\n if node.val > L:\n stk.append(node.left) \n if node.val < R:\n stk.append(node.right)\n if L <= node.val <= R:\n sum += node.val \n return sum\n```\n**Analysis:**\n\nAll 4 methods will DFS traverse all nodes in worst case, and if we count in the recursion trace space cost, the complexities are as follows:\n\n**Time: O(n), space: O(h)**, where `n` is the number of total nodes, `h` is the height of the tree.. | 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 range \[7, 15\]. 7 + 10 + 15 = 32.
**Example 2:**
**Input:** root = \[10,5,15,3,7,13,18,1,null,6\], low = 6, high = 10
**Output:** 23
**Explanation:** Nodes 6, 7, and 10 are in the range \[6, 10\]. 6 + 7 + 10 = 23.
**Constraints:**
* The number of nodes in the tree is in the range `[1, 2 * 104]`.
* `1 <= Node.val <= 105`
* `1 <= low <= high <= 105`
* All `Node.val` are **unique**. | 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) return rangeSumBST(root.left, L, R); // right branch excluded.\n return root.val + rangeSumBST(root.right, L, R) + rangeSumBST(root.left, L, R); // count in both children.\n }\n```\n```\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n if not root:\n return 0\n elif root.val < L:\n return self.rangeSumBST(root.right, L, R)\n elif root.val > R:\n return self.rangeSumBST(root.left, L, R)\n return root.val + self.rangeSumBST(root.left, L, R) + self.rangeSumBST(root.right, L, R)\n```\nThe following are two more similar recursive codes.\n\n**Method 2:**\n```\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (root == null) return 0; // base case.\n return (L <= root.val && root.val <= R ? root.val : 0) + rangeSumBST(root.right, L, R) + rangeSumBST(root.left, L, R);\n }\n```\n```\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n if not root:\n return 0\n return self.rangeSumBST(root.left, L, R) + \\\n self.rangeSumBST(root.right, L, R) + \\\n (root.val if L <= root.val <= R else 0)\n```\n**Method 3:**\n```\n public int rangeSumBST(TreeNode root, int L, int R) {\n if (root == null) { return 0; }\n int sum = 0;\n if (root.val > L) { sum += rangeSumBST(root.left, L, R); } // left child is a possible candidate.\n if (root.val < R) { sum += rangeSumBST(root.right, L, R); } // right child is a possible candidate.\n if (root.val >= L && root.val <= R) { sum += root.val; } // count root in.\n return sum;\n }\n```\n```\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n if not root:\n return 0\n sum = 0\n if root.val > L:\n sum += self.rangeSumBST(root.left, L, R)\n if root.val < R:\n sum += self.rangeSumBST(root.right, L, R)\n if L <= root.val <= R:\n sum += root.val \n return sum\n```\n\n**Method 4: Iterative version**\n```\n public int rangeSumBST(TreeNode root, int L, int R) {\n Stack<TreeNode> stk = new Stack<>();\n stk.push(root);\n int sum = 0;\n while (!stk.isEmpty()) {\n TreeNode n = stk.pop();\n if (n == null) { continue; }\n if (n.val > L) { stk.push(n.left); } // left child is a possible candidate.\n if (n.val < R) { stk.push(n.right); } // right child is a possible candidate.\n if (L <= n.val && n.val <= R) { sum += n.val; }\n }\n return sum;\n }\n```\n```\n def rangeSumBST(self, root: TreeNode, L: int, R: int) -> int:\n stk, sum = [root], 0\n while stk:\n node = stk.pop()\n if node:\n if node.val > L:\n stk.append(node.left) \n if node.val < R:\n stk.append(node.right)\n if L <= node.val <= R:\n sum += node.val \n return sum\n```\n**Analysis:**\n\nAll 4 methods will DFS traverse all nodes in worst case, and if we count in the recursion trace space cost, the complexities are as follows:\n\n**Time: O(n), space: O(h)**, where `n` is the number of total nodes, `h` is the height of the tree.. | 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 may jump forward from index `i` to index `j` (with `i < j`) in the following way:
* During **odd-numbered jumps** (i.e., jumps 1, 3, 5, ...), you jump to the index `j` such that `arr[i] <= arr[j]` and `arr[j]` is the smallest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`.
* During **even-numbered jumps** (i.e., jumps 2, 4, 6, ...), you jump to the index `j` such that `arr[i] >= arr[j]` and `arr[j]` is the largest possible value. If there are multiple such indices `j`, you can only jump to the **smallest** such index `j`.
* It may be the case that for some index `i`, there are no legal jumps.
A starting index is **good** if, starting from that index, you can reach the end of the array (index `arr.length - 1`) by jumping some number of times (possibly 0 or more than once).
Return _the number of **good** starting indices_.
**Example 1:**
**Input:** arr = \[10,13,12,14,15\]
**Output:** 2
**Explanation:**
From starting index i = 0, we can make our 1st jump to i = 2 (since arr\[2\] is the smallest among arr\[1\], arr\[2\], arr\[3\], arr\[4\] that is greater or equal to arr\[0\]), then we cannot jump any more.
From starting index i = 1 and i = 2, we can make our 1st jump to i = 3, then we cannot jump any more.
From starting index i = 3, we can make our 1st jump to i = 4, so we have reached the end.
From starting index i = 4, we have reached the end already.
In total, there are 2 different starting indices i = 3 and i = 4, where we can reach the end with some number of
jumps.
**Example 2:**
**Input:** arr = \[2,3,1,1,4\]
**Output:** 3
**Explanation:**
From starting index i = 0, we make jumps to i = 1, i = 2, i = 3:
During our 1st jump (odd-numbered), we first jump to i = 1 because arr\[1\] is the smallest value in \[arr\[1\], arr\[2\], arr\[3\], arr\[4\]\] that is greater than or equal to arr\[0\].
During our 2nd jump (even-numbered), we jump from i = 1 to i = 2 because arr\[2\] is the largest value in \[arr\[2\], arr\[3\], arr\[4\]\] that is less than or equal to arr\[1\]. arr\[3\] is also the largest value, but 2 is a smaller index, so we can only jump to i = 2 and not i = 3
During our 3rd jump (odd-numbered), we jump from i = 2 to i = 3 because arr\[3\] is the smallest value in \[arr\[3\], arr\[4\]\] that is greater than or equal to arr\[2\].
We can't jump from i = 3 to i = 4, so the starting index i = 0 is not good.
In a similar manner, we can deduce that:
From starting index i = 1, we jump to i = 4, so we reach the end.
From starting index i = 2, we jump to i = 3, and then we can't jump anymore.
From starting index i = 3, we jump to i = 4, so we reach the end.
From starting index i = 4, we are already at the end.
In total, there are 3 different starting indices i = 1, i = 3, and i = 4, where we can reach the end with some
number of jumps.
**Example 3:**
**Input:** arr = \[5,1,3,4,2\]
**Output:** 3
**Explanation:** We can reach the end from starting indices 1, 2, and 4.
**Constraints:**
* `1 <= arr.length <= 2 * 104`
* `0 <= arr[i] < 105` | 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 (auto l1 = u.begin(); l1 != u.end(); ++l1) {\n auto &[y1,line1] = *l1;\n for (auto l2 = l1; ++l2 != u.end(); ) {\n auto &[y2,line2] = *l2;\n auto h = abs(y1 - y2);\n auto i = line1.begin();\n auto iend = line1.end();\n auto j = line2.begin();\n auto jend = line2.end();\n auto prev = INT_MIN;\n auto minw = INT_MAX;\n while(i != iend && j != jend) {\n if (*i < *j) {\n ++i;\n continue;\n }\n if (*i > *j) {\n ++j;\n continue;\n }\n if (prev != INT_MIN)\n minw = min(minw, *i - prev);\n prev = *i;\n ++i;\n ++j;\n }\n if (minw != INT_MAX)\n ret = min(ret, h*minw);\n }\n }\n return ret == INT_MAX ? 0 : ret;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def minAreaRect(self, points: List[List[int]]) -> int:\n x_vals = {}\n y_vals = {}\n for p in points:\n x_vals.setdefault(p[0], set())\n x_vals[p[0]].add(p[1])\n y_vals.setdefault(p[1], set())\n y_vals[p[1]].add(p[0])\n changed = True\n while changed:\n changed = False\n for x in list(x_vals.keys()):\n y_set = x_vals[x]\n if len(y_set) != 1: continue\n changed = True\n for y in y_set: break\n x_vals.pop(x)\n y_vals[y].remove(x)\n if len(y_vals[y]) == 0: y_vals.pop(y)\n for y in list(y_vals.keys()):\n x_set = y_vals[y]\n if len(x_set) != 1: continue\n changed = True\n for x in x_set: break\n y_vals.pop(y)\n x_vals[x].remove(y)\n if len(x_vals[x]) == 0: x_vals.pop(x)\n if len(x_vals) < 2 or len(y_vals) < 2: return 0\n p_dict = x_vals if len(x_vals) <= len(y_vals) else y_vals\n keys = sorted(p_dict.keys())\n res = float("inf")\n for i1, k1 in enumerate(keys):\n for i2 in range(i1 + 1, len(keys)):\n k2 = keys[i2]\n h = k2 - k1\n if h >= res: continue\n intersect = sorted(p_dict[k1].intersection(p_dict[k2]))\n best = float("inf")\n for j in range(len(intersect) - 1):\n best = min(best, intersect[j + 1] - intersect[j])\n res = min(res, h * best)\n if not isinstance(res, int): return 0\n return res\n```\n\n```Java []\nclass Solution {\n public int minAreaRect(int[][] points) {\n HashMap<Integer, HashSet<Integer>> map = new HashMap<>();\n for(int i = 0; i<points.length; i++){\n if(!map.containsKey(points[i][0])){\n map.put(points[i][0], new HashSet<Integer>());\n }\n map.get(points[i][0]).add(points[i][1]);\n }\n int min = Integer.MAX_VALUE;\n Arrays.sort(points, (x,y)->x[0]-y[0]);\n for(int i = 0; i<points.length; i++){\n for(int j = i+1; j<points.length; j++){\n if(points[i][0]==points[j][0]||points[i][1]==points[j][1]){\n continue;\n }\n int area = Math.abs(points[i][0]-points[j][0])*Math.abs(points[i][1]-points[j][1]);\n if(area<min&&map.get(points[i][0]).contains(points[j][1])&&map.get(points[j][0]).contains(points[i][1])){\n min = area;\n }\n }\n }\n if(min==Integer.MAX_VALUE){\n return 0;\n }else{\n return min;\n }\n }\n}\n```\n | 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\],\[2,2\]\]
**Output:** 4
**Example 2:**
**Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\]
**Output:** 2
**Constraints:**
* `1 <= points.length <= 500`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**. | 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 (auto l1 = u.begin(); l1 != u.end(); ++l1) {\n auto &[y1,line1] = *l1;\n for (auto l2 = l1; ++l2 != u.end(); ) {\n auto &[y2,line2] = *l2;\n auto h = abs(y1 - y2);\n auto i = line1.begin();\n auto iend = line1.end();\n auto j = line2.begin();\n auto jend = line2.end();\n auto prev = INT_MIN;\n auto minw = INT_MAX;\n while(i != iend && j != jend) {\n if (*i < *j) {\n ++i;\n continue;\n }\n if (*i > *j) {\n ++j;\n continue;\n }\n if (prev != INT_MIN)\n minw = min(minw, *i - prev);\n prev = *i;\n ++i;\n ++j;\n }\n if (minw != INT_MAX)\n ret = min(ret, h*minw);\n }\n }\n return ret == INT_MAX ? 0 : ret;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def minAreaRect(self, points: List[List[int]]) -> int:\n x_vals = {}\n y_vals = {}\n for p in points:\n x_vals.setdefault(p[0], set())\n x_vals[p[0]].add(p[1])\n y_vals.setdefault(p[1], set())\n y_vals[p[1]].add(p[0])\n changed = True\n while changed:\n changed = False\n for x in list(x_vals.keys()):\n y_set = x_vals[x]\n if len(y_set) != 1: continue\n changed = True\n for y in y_set: break\n x_vals.pop(x)\n y_vals[y].remove(x)\n if len(y_vals[y]) == 0: y_vals.pop(y)\n for y in list(y_vals.keys()):\n x_set = y_vals[y]\n if len(x_set) != 1: continue\n changed = True\n for x in x_set: break\n y_vals.pop(y)\n x_vals[x].remove(y)\n if len(x_vals[x]) == 0: x_vals.pop(x)\n if len(x_vals) < 2 or len(y_vals) < 2: return 0\n p_dict = x_vals if len(x_vals) <= len(y_vals) else y_vals\n keys = sorted(p_dict.keys())\n res = float("inf")\n for i1, k1 in enumerate(keys):\n for i2 in range(i1 + 1, len(keys)):\n k2 = keys[i2]\n h = k2 - k1\n if h >= res: continue\n intersect = sorted(p_dict[k1].intersection(p_dict[k2]))\n best = float("inf")\n for j in range(len(intersect) - 1):\n best = min(best, intersect[j + 1] - intersect[j])\n res = min(res, h * best)\n if not isinstance(res, int): return 0\n return res\n```\n\n```Java []\nclass Solution {\n public int minAreaRect(int[][] points) {\n HashMap<Integer, HashSet<Integer>> map = new HashMap<>();\n for(int i = 0; i<points.length; i++){\n if(!map.containsKey(points[i][0])){\n map.put(points[i][0], new HashSet<Integer>());\n }\n map.get(points[i][0]).add(points[i][1]);\n }\n int min = Integer.MAX_VALUE;\n Arrays.sort(points, (x,y)->x[0]-y[0]);\n for(int i = 0; i<points.length; i++){\n for(int j = i+1; j<points.length; j++){\n if(points[i][0]==points[j][0]||points[i][1]==points[j][1]){\n continue;\n }\n int area = Math.abs(points[i][0]-points[j][0])*Math.abs(points[i][1]-points[j][1]);\n if(area<min&&map.get(points[i][0]).contains(points[j][1])&&map.get(points[j][0]).contains(points[i][1])){\n min = area;\n }\n }\n }\n if(min==Integer.MAX_VALUE){\n return 0;\n }else{\n return min;\n }\n }\n}\n```\n | 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 side lengths: 1, 2, and 2.
**Example 2:**
**Input:** nums = \[1,2,1,10\]
**Output:** 0
**Explanation:**
You cannot use the side lengths 1, 1, and 2 to form a triangle.
You cannot use the side lengths 1, 1, and 10 to form a triangle.
You cannot use the side lengths 1, 2, and 10 to form a triangle.
As we cannot use any three side lengths to form a triangle of non-zero area, we return 0.
**Constraints:**
* `3 <= nums.length <= 104`
* `1 <= nums[i] <= 106` | 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 points.sort()\n points_set = set([tuple(point) for point in points])\n smallest = float(\'inf\')\n for i, (x1, y1) in enumerate(points):\n for j, (x2, y2) in enumerate(points[i:], i):\n if x1 < x2 and y1 < y2 and (x1, y2) in points_set and (x2, y1) in points_set:\n area = (x2 - x1) * (y2 - y1)\n smallest = min(smallest, area)\n return smallest if smallest != float(\'inf\') else 0\n```\n\n**Solution 2**\nSimilar idea as above, but here we take `(x1, y1)` as lower left and try to find the upper right `(x2, y2)` using `(x1, y2)` and `(x2, y1)`. We can sort of treat all x-coordinates at the same y-coordinate as a \'row\' and all y-coordinates at the same x-coordinate as a \'column\'. Use `x1` to see what `y2`s are in this column, and `y1` to see what `x2`s are in this row. The trick is that once we find a valid `(x2, y2)` combo, it *must* be the smallest rectangle for that `(x1, y1), (x2, y2)`. Break from iterating through `y2`s and move on to the next `x2`. This has a huge time savings for these test cases despite a (roughly?) equivalent time complexity. I\'m actually not 100% sure how to evaluate time complexity here (we pick up `O(NlogN)` from sorting and `N` binary searches), but I\'m assuming it is still quadratic in the worst case.\n`O(N^2)` @ 370ms, beat 94%.\n```\ndef minAreaRect(self, points: List[List[int]]) -> int:\n # Collect all y coordinates per x coordinate into a list (and vice versa).\n x_to_y = collections.defaultdict(list)\n y_to_x = collections.defaultdict(list)\n for x, y in points:\n x_to_y[x].append(y)\n y_to_x[y].append(x)\n\n # Sort all lists.\n for x, y_list in x_to_y.items():\n y_list.sort()\n\n for y, x_list in y_to_x.items():\n x_list.sort()\n\n # For each x1, y1 in points, \n points = set([tuple(point) for point in points])\n smallest = float(\'inf\')\n for x1, y1 in points:\n # Get all y2 coordinates for this x1 (and vice versa).\n y_list = x_to_y[x1]\n x_list = y_to_x[y1]\n\n # But only consider the y2 coordinates that are greater than y1.\n # Meaning, lets only consider rectangles from lower left to upper right.\n y_idx = bisect.bisect_right(y_list, y1)\n x_idx = bisect.bisect_right(x_list, x1)\n ys_above = y_list[y_idx:]\n xs_right = x_list[x_idx:]\n for x2 in xs_right:\n for y2 in ys_above:\n # Here, we know (x1, y2) and (y1, x2) are points because they were \n # in x_to_y and y_to_x. If (x2, y2) is a point, we have a rectangle.\n if (x2, y2) in points:\n smallest = min(smallest, (x2 - x1) * (y2 - y1))\n # Key to efficiency: Because the lists were sorted, we have found\n # the smallest rectangle for this (x2, y2). Move to next x2.\n break\n if smallest <= (x2 - x1) * (y2 - y1):\n break\n return smallest if smallest != float(\'inf\') else 0\n\n\n\n\n``` | 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\],\[2,2\]\]
**Output:** 4
**Example 2:**
**Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\]
**Output:** 2
**Constraints:**
* `1 <= points.length <= 500`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**. | 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 points.sort()\n points_set = set([tuple(point) for point in points])\n smallest = float(\'inf\')\n for i, (x1, y1) in enumerate(points):\n for j, (x2, y2) in enumerate(points[i:], i):\n if x1 < x2 and y1 < y2 and (x1, y2) in points_set and (x2, y1) in points_set:\n area = (x2 - x1) * (y2 - y1)\n smallest = min(smallest, area)\n return smallest if smallest != float(\'inf\') else 0\n```\n\n**Solution 2**\nSimilar idea as above, but here we take `(x1, y1)` as lower left and try to find the upper right `(x2, y2)` using `(x1, y2)` and `(x2, y1)`. We can sort of treat all x-coordinates at the same y-coordinate as a \'row\' and all y-coordinates at the same x-coordinate as a \'column\'. Use `x1` to see what `y2`s are in this column, and `y1` to see what `x2`s are in this row. The trick is that once we find a valid `(x2, y2)` combo, it *must* be the smallest rectangle for that `(x1, y1), (x2, y2)`. Break from iterating through `y2`s and move on to the next `x2`. This has a huge time savings for these test cases despite a (roughly?) equivalent time complexity. I\'m actually not 100% sure how to evaluate time complexity here (we pick up `O(NlogN)` from sorting and `N` binary searches), but I\'m assuming it is still quadratic in the worst case.\n`O(N^2)` @ 370ms, beat 94%.\n```\ndef minAreaRect(self, points: List[List[int]]) -> int:\n # Collect all y coordinates per x coordinate into a list (and vice versa).\n x_to_y = collections.defaultdict(list)\n y_to_x = collections.defaultdict(list)\n for x, y in points:\n x_to_y[x].append(y)\n y_to_x[y].append(x)\n\n # Sort all lists.\n for x, y_list in x_to_y.items():\n y_list.sort()\n\n for y, x_list in y_to_x.items():\n x_list.sort()\n\n # For each x1, y1 in points, \n points = set([tuple(point) for point in points])\n smallest = float(\'inf\')\n for x1, y1 in points:\n # Get all y2 coordinates for this x1 (and vice versa).\n y_list = x_to_y[x1]\n x_list = y_to_x[y1]\n\n # But only consider the y2 coordinates that are greater than y1.\n # Meaning, lets only consider rectangles from lower left to upper right.\n y_idx = bisect.bisect_right(y_list, y1)\n x_idx = bisect.bisect_right(x_list, x1)\n ys_above = y_list[y_idx:]\n xs_right = x_list[x_idx:]\n for x2 in xs_right:\n for y2 in ys_above:\n # Here, we know (x1, y2) and (y1, x2) are points because they were \n # in x_to_y and y_to_x. If (x2, y2) is a point, we have a rectangle.\n if (x2, y2) in points:\n smallest = min(smallest, (x2 - x1) * (y2 - y1))\n # Key to efficiency: Because the lists were sorted, we have found\n # the smallest rectangle for this (x2, y2). Move to next x2.\n break\n if smallest <= (x2 - x1) * (y2 - y1):\n break\n return smallest if smallest != float(\'inf\') else 0\n\n\n\n\n``` | 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 side lengths: 1, 2, and 2.
**Example 2:**
**Input:** nums = \[1,2,1,10\]
**Output:** 0
**Explanation:**
You cannot use the side lengths 1, 1, and 2 to form a triangle.
You cannot use the side lengths 1, 1, and 10 to form a triangle.
You cannot use the side lengths 1, 2, and 10 to form a triangle.
As we cannot use any three side lengths to form a triangle of non-zero area, we return 0.
**Constraints:**
* `3 <= nums.length <= 104`
* `1 <= nums[i] <= 106` | 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 ---> x2 will be in the from of (x2,y2)\n At last check if (x2,y1) is present in points or not :\n <<<If present we get our 4 points now find the area >>>>\n\t\t\t\t\t\t\t \nUse dictionary to store data\n\n```\n\n# CODE\n```\nclass Solution:\n def minAreaRect(self, points: List[List[int]]) -> int:\n x_axis = defaultdict(dict)\n y_axis = defaultdict(dict)\n d = {}\n points.sort()\n \n ans = float(\'inf\')\n \n for point in points:\n x_axis[point[0]][point[1]] = True\n y_axis[point[1]][point[0]] = True\n d[(point[0],point[1])] = True\n\n for point in points:\n x1 = point[0]\n y1 = point[1]\n for y2 in x_axis[x1]:\n if y2 == y1:continue\n for x2 in y_axis[y2]:\n if x2 == x1:continue\n if (x2,y1) in d:\n tmp = abs(x2-x1) * abs(y2-y1)\n if tmp < ans : ans = tmp\n return ans if ans!=float(\'inf\') else 0\n``` | 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\],\[2,2\]\]
**Output:** 4
**Example 2:**
**Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\]
**Output:** 2
**Constraints:**
* `1 <= points.length <= 500`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**. | 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 ---> x2 will be in the from of (x2,y2)\n At last check if (x2,y1) is present in points or not :\n <<<If present we get our 4 points now find the area >>>>\n\t\t\t\t\t\t\t \nUse dictionary to store data\n\n```\n\n# CODE\n```\nclass Solution:\n def minAreaRect(self, points: List[List[int]]) -> int:\n x_axis = defaultdict(dict)\n y_axis = defaultdict(dict)\n d = {}\n points.sort()\n \n ans = float(\'inf\')\n \n for point in points:\n x_axis[point[0]][point[1]] = True\n y_axis[point[1]][point[0]] = True\n d[(point[0],point[1])] = True\n\n for point in points:\n x1 = point[0]\n y1 = point[1]\n for y2 in x_axis[x1]:\n if y2 == y1:continue\n for x2 in y_axis[y2]:\n if x2 == x1:continue\n if (x2,y1) in d:\n tmp = abs(x2-x1) * abs(y2-y1)\n if tmp < ans : ans = tmp\n return ans if ans!=float(\'inf\') else 0\n``` | 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 side lengths: 1, 2, and 2.
**Example 2:**
**Input:** nums = \[1,2,1,10\]
**Output:** 0
**Explanation:**
You cannot use the side lengths 1, 1, and 2 to form a triangle.
You cannot use the side lengths 1, 1, and 10 to form a triangle.
You cannot use the side lengths 1, 2, and 10 to form a triangle.
As we cannot use any three side lengths to form a triangle of non-zero area, we return 0.
**Constraints:**
* `3 <= nums.length <= 104`
* `1 <= nums[i] <= 106` | 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 useful then plese up-vote. Thank you!\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n\n- Space complexity: $$O(n)$$ for the `seen` set\n\n# Code\n```\nclass Solution:\n def minAreaRect(self, points: List[List[int]]) -> int:\n seen = set()\n ans = sys.maxsize\n for x1, y1 in points:\n for x2, y2 in points:\n if (x1,y2) in seen and (x2,y1) in seen:\n ans = min(ans, abs((x2-x1)*(y2-y1)))\n seen.add((x1,y1))\n return ans if ans != sys.maxsize else 0\n\n``` | 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\],\[2,2\]\]
**Output:** 4
**Example 2:**
**Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\]
**Output:** 2
**Constraints:**
* `1 <= points.length <= 500`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**. | 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 useful then plese up-vote. Thank you!\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n\n- Space complexity: $$O(n)$$ for the `seen` set\n\n# Code\n```\nclass Solution:\n def minAreaRect(self, points: List[List[int]]) -> int:\n seen = set()\n ans = sys.maxsize\n for x1, y1 in points:\n for x2, y2 in points:\n if (x1,y2) in seen and (x2,y1) in seen:\n ans = min(ans, abs((x2-x1)*(y2-y1)))\n seen.add((x1,y1))\n return ans if ans != sys.maxsize else 0\n\n``` | 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 side lengths: 1, 2, and 2.
**Example 2:**
**Input:** nums = \[1,2,1,10\]
**Output:** 0
**Explanation:**
You cannot use the side lengths 1, 1, and 2 to form a triangle.
You cannot use the side lengths 1, 1, and 10 to form a triangle.
You cannot use the side lengths 1, 2, and 10 to form a triangle.
As we cannot use any three side lengths to form a triangle of non-zero area, we return 0.
**Constraints:**
* `3 <= nums.length <= 104`
* `1 <= nums[i] <= 106` | 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() if len(set_y) > 1}\n for x1, x2 in combinations(dict_x.keys(), 2):\n for y1, y2 in combinations(dict_x[x1] & dict_x[x2], 2):\n min_area = min(min_area, abs(x1 - x2) * abs(y1 - y2))\n return min_area if min_area < inf else 0\n``` | 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\],\[2,2\]\]
**Output:** 4
**Example 2:**
**Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\]
**Output:** 2
**Constraints:**
* `1 <= points.length <= 500`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**. | 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() if len(set_y) > 1}\n for x1, x2 in combinations(dict_x.keys(), 2):\n for y1, y2 in combinations(dict_x[x1] & dict_x[x2], 2):\n min_area = min(min_area, abs(x1 - x2) * abs(y1 - y2))\n return min_area if min_area < inf else 0\n``` | 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 side lengths: 1, 2, and 2.
**Example 2:**
**Input:** nums = \[1,2,1,10\]
**Output:** 0
**Explanation:**
You cannot use the side lengths 1, 1, and 2 to form a triangle.
You cannot use the side lengths 1, 1, and 10 to form a triangle.
You cannot use the side lengths 1, 2, and 10 to form a triangle.
As we cannot use any three side lengths to form a triangle of non-zero area, we return 0.
**Constraints:**
* `3 <= nums.length <= 104`
* `1 <= nums[i] <= 106` | 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 far.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n 1. Initialize a variable `res` to store the minimum area found, and set it to positive infinity.\n 2. Create a set `vis` to keep track of visited points.\n 3. Iterate through each point in the input `points`.\n a. For each point, iterate through the visited points in `vis`.\n b. Check if the current point, along with any two points from the visited set, forms a rectangle.\n c. If a rectangle is found, calculate its area and update the minimum area (`res`) accordingly.\n d. Add the current point to the visited set.\n 4. Return the minimum area found, or 0 if no rectangle is found.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2) where n is the number of points\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n) where n is the number of points\n# Code\n```\nclass Solution:\n def minAreaRect(self, points: List[List[int]]) -> int:\n res = float(\'inf\')\n\n vis = set()\n\n for x,y in points:\n for xv, yv in vis:\n # check diagonal points\n if (xv, y) in vis and (x, yv) in vis:\n area = abs(xv-x) * abs(yv-y)\n res = min(res, area)\n vis.add((x,y))\n \n return res if res != float(\'inf\') else 0\n```\n# ThinkBIG\n\uD83D\uDE80 Elevating Your LeetCode Game with this Algorithm? \uD83E\uDDE0\uD83D\uDCBB If you\'ve found this solution to be insightful and well-crafted, consider boosting its visibility with an upvote. \uD83D\uDD1D Together, we can assist fellow programmers in ascending to greater coding pinnacles! \uD83D\uDE4C | 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\],\[2,2\]\]
**Output:** 4
**Example 2:**
**Input:** points = \[\[1,1\],\[1,3\],\[3,1\],\[3,3\],\[4,1\],\[4,3\]\]
**Output:** 2
**Constraints:**
* `1 <= points.length <= 500`
* `points[i].length == 2`
* `0 <= xi, yi <= 4 * 104`
* All the given points are **unique**. | 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 far.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n 1. Initialize a variable `res` to store the minimum area found, and set it to positive infinity.\n 2. Create a set `vis` to keep track of visited points.\n 3. Iterate through each point in the input `points`.\n a. For each point, iterate through the visited points in `vis`.\n b. Check if the current point, along with any two points from the visited set, forms a rectangle.\n c. If a rectangle is found, calculate its area and update the minimum area (`res`) accordingly.\n d. Add the current point to the visited set.\n 4. Return the minimum area found, or 0 if no rectangle is found.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2) where n is the number of points\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n) where n is the number of points\n# Code\n```\nclass Solution:\n def minAreaRect(self, points: List[List[int]]) -> int:\n res = float(\'inf\')\n\n vis = set()\n\n for x,y in points:\n for xv, yv in vis:\n # check diagonal points\n if (xv, y) in vis and (x, yv) in vis:\n area = abs(xv-x) * abs(yv-y)\n res = min(res, area)\n vis.add((x,y))\n \n return res if res != float(\'inf\') else 0\n```\n# ThinkBIG\n\uD83D\uDE80 Elevating Your LeetCode Game with this Algorithm? \uD83E\uDDE0\uD83D\uDCBB If you\'ve found this solution to be insightful and well-crafted, consider boosting its visibility with an upvote. \uD83D\uDD1D Together, we can assist fellow programmers in ascending to greater coding pinnacles! \uD83D\uDE4C | 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 side lengths: 1, 2, and 2.
**Example 2:**
**Input:** nums = \[1,2,1,10\]
**Output:** 0
**Explanation:**
You cannot use the side lengths 1, 1, and 2 to form a triangle.
You cannot use the side lengths 1, 1, and 10 to form a triangle.
You cannot use the side lengths 1, 2, and 10 to form a triangle.
As we cannot use any three side lengths to form a triangle of non-zero area, we return 0.
**Constraints:**
* `3 <= nums.length <= 104`
* `1 <= nums[i] <= 106` | 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 if(last[s[i-1] - \'a\'] != -1)\n dp[i] = 2 * dp[i-1] - dp[last[s[i-1] - \'a\']];\n \n dp[i] %= MOD;\n last[s[i-1] - \'a\'] = i - 1;\n }\n if(dp[s.size()] <= 0)\n dp[s.size()] += MOD;\n return dp[s.size()] - 1;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def distinctSubseqII(self, s: str) -> int:\n dp=defaultdict(int)\n a=0\n b=10**9 + 7\n for c in s:\n tmp=a-dp[c]\n dp[c]=(a + 1) % b\n a=(tmp + dp[c])%b\n return a\n```\n\n```Java []\nclass Solution {\n public int distinctSubseqII(String s) {\n int mod = (int) 1e9 + 7;\n int n = s.length();\n int[] record4DeDup = new int[26];\n int curRes = 1;//empty\n char[] chs = s.toCharArray();\n for (int i = 0; i < n; i++) {\n int addCount = curRes;\n curRes = ((curRes + addCount) % mod - record4DeDup[chs[i] - \'a\'] % mod + mod) % mod;\n record4DeDup[chs[i] - \'a\'] = addCount;\n }\n return (curRes - 1 + mod) % mod;\n }\n}\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 positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not.
**Example 1:**
**Input:** s = "abc "
**Output:** 7
**Explanation:** The 7 distinct subsequences are "a ", "b ", "c ", "ab ", "ac ", "bc ", and "abc ".
**Example 2:**
**Input:** s = "aba "
**Output:** 6
**Explanation:** The 6 distinct subsequences are "a ", "b ", "ab ", "aa ", "ba ", and "aba ".
**Example 3:**
**Input:** s = "aaa "
**Output:** 3
**Explanation:** The 3 distinct subsequences are "a ", "aa " and "aaa ".
**Constraints:**
* `1 <= s.length <= 2000`
* `s` consists of lowercase English letters. | 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 if(last[s[i-1] - \'a\'] != -1)\n dp[i] = 2 * dp[i-1] - dp[last[s[i-1] - \'a\']];\n \n dp[i] %= MOD;\n last[s[i-1] - \'a\'] = i - 1;\n }\n if(dp[s.size()] <= 0)\n dp[s.size()] += MOD;\n return dp[s.size()] - 1;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def distinctSubseqII(self, s: str) -> int:\n dp=defaultdict(int)\n a=0\n b=10**9 + 7\n for c in s:\n tmp=a-dp[c]\n dp[c]=(a + 1) % b\n a=(tmp + dp[c])%b\n return a\n```\n\n```Java []\nclass Solution {\n public int distinctSubseqII(String s) {\n int mod = (int) 1e9 + 7;\n int n = s.length();\n int[] record4DeDup = new int[26];\n int curRes = 1;//empty\n char[] chs = s.toCharArray();\n for (int i = 0; i < n; i++) {\n int addCount = curRes;\n curRes = ((curRes + addCount) % mod - record4DeDup[chs[i] - \'a\'] % mod + mod) % mod;\n record4DeDup[chs[i] - \'a\'] = addCount;\n }\n return (curRes - 1 + mod) % mod;\n }\n}\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 becomes \[0,1,9,16,100\].
**Example 2:**
**Input:** nums = \[-7,-3,2,3,11\]
**Output:** \[4,9,9,49,121\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` is sorted in **non-decreasing** order.
**Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach? | 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\n for i in range(index + 1, N):\n if s[i] == s[index]:\n best -= calc(i + 1, True) \n break\n\n return best % MOD\n \n\n return calc(0, False) % MOD\n \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 positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not.
**Example 1:**
**Input:** s = "abc "
**Output:** 7
**Explanation:** The 7 distinct subsequences are "a ", "b ", "c ", "ab ", "ac ", "bc ", and "abc ".
**Example 2:**
**Input:** s = "aba "
**Output:** 6
**Explanation:** The 6 distinct subsequences are "a ", "b ", "ab ", "aa ", "ba ", and "aba ".
**Example 3:**
**Input:** s = "aaa "
**Output:** 3
**Explanation:** The 3 distinct subsequences are "a ", "aa " and "aaa ".
**Constraints:**
* `1 <= s.length <= 2000`
* `s` consists of lowercase English letters. | 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\n for i in range(index + 1, N):\n if s[i] == s[index]:\n best -= calc(i + 1, True) \n break\n\n return best % MOD\n \n\n return calc(0, False) % MOD\n \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 becomes \[0,1,9,16,100\].
**Example 2:**
**Input:** nums = \[-7,-3,2,3,11\]
**Output:** \[4,9,9,49,121\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` is sorted in **non-decreasing** order.
**Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach? | 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 subsequences given the current character and its previous occurrences.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe given Python code offers an optimized solution to this problem. The differentSubsequences function takes a string s as input and returns the number of distinct subsequences modulo 10^9 + 7. Let\'s break down the code to understand its inner workings:\n\n \n\n1. Initialization: The code starts by initializing the length of the input string (n), an array to store the number of distinct subsequences (distinct_subsequences_count), and a modulus value (mod) to prevent integer overflow.\n\n2. Dynamic programming loop: The code loops through the characters of the input string. For each character, it calculates the number of distinct subsequences based on previous occurrences.\n\n3. Result: A finite number of distinct subsequences modulo 10^9 + 7 is returned.\n\n**Please Upvote \uD83D\uDE0A\uD83D\uDE0A**\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. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def distinctSubseqII(self, s: str) -> int:\n # Length of the input string\n n = len(s)\n \n # Initialize an array to store the number of distinct subsequences\n distinct_subsequences_count = [0 if i > 0 else 1 for i in range(n + 1)]\n \n # Modulus value to prevent integer overflow\n mod = (10**9) + 7\n \n # Dictionary to store the last occurrence index of each character\n last_occurrence = {}\n \n # Loop through the characters of the input string\n for i in range(1, n + 1):\n char = s[i - 1]\n \n # Calculate the number of distinct subsequences for the current character\n distinct_subsequences_count[i] = distinct_subsequences_count[i - 1] * 2 % mod\n \n # Check if the current character has occurred before\n if char in last_occurrence:\n idx = last_occurrence[char]\n # Subtract the count of subsequences ending with the previous occurrence\n distinct_subsequences_count[i] -= distinct_subsequences_count[idx - 1] % mod\n \n # Update the last occurrence index of the current character\n last_occurrence[char] = i\n \n # Return the final count of distinct subsequences modulo the specified value\n return distinct_subsequences_count[n] % mod\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 positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not.
**Example 1:**
**Input:** s = "abc "
**Output:** 7
**Explanation:** The 7 distinct subsequences are "a ", "b ", "c ", "ab ", "ac ", "bc ", and "abc ".
**Example 2:**
**Input:** s = "aba "
**Output:** 6
**Explanation:** The 6 distinct subsequences are "a ", "b ", "ab ", "aa ", "ba ", and "aba ".
**Example 3:**
**Input:** s = "aaa "
**Output:** 3
**Explanation:** The 3 distinct subsequences are "a ", "aa " and "aaa ".
**Constraints:**
* `1 <= s.length <= 2000`
* `s` consists of lowercase English letters. | 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 subsequences given the current character and its previous occurrences.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe given Python code offers an optimized solution to this problem. The differentSubsequences function takes a string s as input and returns the number of distinct subsequences modulo 10^9 + 7. Let\'s break down the code to understand its inner workings:\n\n \n\n1. Initialization: The code starts by initializing the length of the input string (n), an array to store the number of distinct subsequences (distinct_subsequences_count), and a modulus value (mod) to prevent integer overflow.\n\n2. Dynamic programming loop: The code loops through the characters of the input string. For each character, it calculates the number of distinct subsequences based on previous occurrences.\n\n3. Result: A finite number of distinct subsequences modulo 10^9 + 7 is returned.\n\n**Please Upvote \uD83D\uDE0A\uD83D\uDE0A**\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. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def distinctSubseqII(self, s: str) -> int:\n # Length of the input string\n n = len(s)\n \n # Initialize an array to store the number of distinct subsequences\n distinct_subsequences_count = [0 if i > 0 else 1 for i in range(n + 1)]\n \n # Modulus value to prevent integer overflow\n mod = (10**9) + 7\n \n # Dictionary to store the last occurrence index of each character\n last_occurrence = {}\n \n # Loop through the characters of the input string\n for i in range(1, n + 1):\n char = s[i - 1]\n \n # Calculate the number of distinct subsequences for the current character\n distinct_subsequences_count[i] = distinct_subsequences_count[i - 1] * 2 % mod\n \n # Check if the current character has occurred before\n if char in last_occurrence:\n idx = last_occurrence[char]\n # Subtract the count of subsequences ending with the previous occurrence\n distinct_subsequences_count[i] -= distinct_subsequences_count[idx - 1] % mod\n \n # Update the last occurrence index of the current character\n last_occurrence[char] = i\n \n # Return the final count of distinct subsequences modulo the specified value\n return distinct_subsequences_count[n] % mod\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 becomes \[0,1,9,16,100\].
**Example 2:**
**Input:** nums = \[-7,-3,2,3,11\]
**Output:** \[4,9,9,49,121\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` is sorted in **non-decreasing** order.
**Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach? | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def distinctSubseqII(self, s: str) -> int:\n n = len(s)\n M = 10**9+7\n map = defaultdict(list)\n for idx, ch in enumerate(s):\n map[ch].append(idx)\n \n @cache\n def dp(idx):\n if idx == n: return 0\n tmp = 0\n for k, v in map.items():\n v_idx = bisect.bisect(v, idx)\n if v_idx == len(v): continue\n else:\n tmp = (tmp + dp(v[v_idx])) % M\n return (tmp+1) % M\n\n res = 0\n for k, v in map.items():\n res = (res + dp(v[0])) % M\n return res \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 positions of the remaining characters. (i.e., `"ace "` is a subsequence of `"abcde "` while `"aec "` is not.
**Example 1:**
**Input:** s = "abc "
**Output:** 7
**Explanation:** The 7 distinct subsequences are "a ", "b ", "c ", "ab ", "ac ", "bc ", and "abc ".
**Example 2:**
**Input:** s = "aba "
**Output:** 6
**Explanation:** The 6 distinct subsequences are "a ", "b ", "ab ", "aa ", "ba ", and "aba ".
**Example 3:**
**Input:** s = "aaa "
**Output:** 3
**Explanation:** The 3 distinct subsequences are "a ", "aa " and "aaa ".
**Constraints:**
* `1 <= s.length <= 2000`
* `s` consists of lowercase English letters. | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def distinctSubseqII(self, s: str) -> int:\n n = len(s)\n M = 10**9+7\n map = defaultdict(list)\n for idx, ch in enumerate(s):\n map[ch].append(idx)\n \n @cache\n def dp(idx):\n if idx == n: return 0\n tmp = 0\n for k, v in map.items():\n v_idx = bisect.bisect(v, idx)\n if v_idx == len(v): continue\n else:\n tmp = (tmp + dp(v[v_idx])) % M\n return (tmp+1) % M\n\n res = 0\n for k, v in map.items():\n res = (res + dp(v[0])) % M\n return res \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 becomes \[0,1,9,16,100\].
**Example 2:**
**Input:** nums = \[-7,-3,2,3,11\]
**Output:** \[4,9,9,49,121\]
**Constraints:**
* `1 <= nums.length <= 104`
* `-104 <= nums[i] <= 104`
* `nums` is sorted in **non-decreasing** order.
**Follow up:** Squaring each element and sorting the new array is very trivial, could you find an `O(n)` solution using a different approach? | 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 return 0;\n }\n for(int i=0;i<index;i++)\n {\n if(arr[i]>=arr[i+1])\n {\n return 0;\n }\n }\n for(int i=n-1;i>index;i--)\n {\n if(arr[i]>=arr[i-1])\n {\n return 0;\n }\n }\n return 1;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def validMountainArray(self, arr: List[int]) -> bool:\n if len(arr) == 1:\n return False\n increasing, previous = None, arr[0]\n\n for e in arr[1:]:\n if previous == e:\n return False\n if increasing is None:\n if e <= previous:\n return False\n increasing = True\n elif increasing and previous > e:\n increasing = False\n elif not increasing and previous < e:\n return False\n previous = e\n\n return not increasing\n```\n\n```Java []\nclass Solution {\n public boolean validMountainArray(int[] a) {\n int max = Integer.MIN_VALUE;\n int index_Max = 0, x = 0;\n boolean b = true;\n for (int i : a) max = Math.max(max, i);\n while (max != a[x++]) index_Max++;\n if(a.length < 3 || index_Max == a.length - 1 || index_Max == 0) return false;\n for (int i = 0; i < index_Max; i++) {\n if (!(a[i] < a[i + 1])) return false;\n }\n for (int i = index_Max; i < a.length - 1; i++) {\n if (a[i] <= a[i + 1]) return false;\n }\n return b;\n }\n}\n```\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] > ... > arr[arr.length - 1]`
**Example 1:**
**Input:** arr = \[2,1\]
**Output:** false
**Example 2:**
**Input:** arr = \[3,5,5\]
**Output:** false
**Example 3:**
**Input:** arr = \[0,3,2,1\]
**Output:** true
**Constraints:**
* `1 <= arr.length <= 104`
* `0 <= arr[i] <= 104` | 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 return 0;\n }\n for(int i=0;i<index;i++)\n {\n if(arr[i]>=arr[i+1])\n {\n return 0;\n }\n }\n for(int i=n-1;i>index;i--)\n {\n if(arr[i]>=arr[i-1])\n {\n return 0;\n }\n }\n return 1;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def validMountainArray(self, arr: List[int]) -> bool:\n if len(arr) == 1:\n return False\n increasing, previous = None, arr[0]\n\n for e in arr[1:]:\n if previous == e:\n return False\n if increasing is None:\n if e <= previous:\n return False\n increasing = True\n elif increasing and previous > e:\n increasing = False\n elif not increasing and previous < e:\n return False\n previous = e\n\n return not increasing\n```\n\n```Java []\nclass Solution {\n public boolean validMountainArray(int[] a) {\n int max = Integer.MIN_VALUE;\n int index_Max = 0, x = 0;\n boolean b = true;\n for (int i : a) max = Math.max(max, i);\n while (max != a[x++]) index_Max++;\n if(a.length < 3 || index_Max == a.length - 1 || index_Max == 0) return false;\n for (int i = 0; i < index_Max; i++) {\n if (!(a[i] < a[i + 1])) return false;\n }\n for (int i = index_Max; i < a.length - 1; i++) {\n if (a[i] <= a[i + 1]) return false;\n }\n return b;\n }\n}\n```\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 if:
* For `i <= k < j`:
* `arr[k] > arr[k + 1]` when `k` is odd, and
* `arr[k] < arr[k + 1]` when `k` is even.
* Or, for `i <= k < j`:
* `arr[k] > arr[k + 1]` when `k` is even, and
* `arr[k] < arr[k + 1]` when `k` is odd.
**Example 1:**
**Input:** arr = \[9,4,2,10,7,8,8,1,9\]
**Output:** 5
**Explanation:** arr\[1\] > arr\[2\] < arr\[3\] > arr\[4\] < arr\[5\]
**Example 2:**
**Input:** arr = \[4,8,12,16\]
**Output:** 2
**Example 3:**
**Input:** arr = \[100\]
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 4 * 104`
* `0 <= arr[i] <= 109` | 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 you will be able to come up with a straightforward solution. |
✔️ [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, we compare two indices from scans checking whether they met at the peak of the mountain.\n\nTime: **O(n)** - scan\nSpace: **O(1)** - nothing stored\n\nRuntime: 196 ms, faster than **89.44%** of Python3 online submissions for Valid Mountain Array.\nMemory Usage: 15.3 MB, less than **99.55%** of Python3 online submissions for Valid Mountain Array.\n\n```\ndef validMountainArray(self, a: List[int]) -> bool:\n\tstart, end, L = 0, -1, len(a)\n\n\twhile start < L-1 and a[start] < a[start+1]: \n\t\tstart += 1\n\twhile end > -L and a[end] < a[end-1]: \n\t\tend -= 1\n\n\treturn start == end + L and 0 < start and end < -1\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.** | 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] > ... > arr[arr.length - 1]`
**Example 1:**
**Input:** arr = \[2,1\]
**Output:** false
**Example 2:**
**Input:** arr = \[3,5,5\]
**Output:** false
**Example 3:**
**Input:** arr = \[0,3,2,1\]
**Output:** true
**Constraints:**
* `1 <= arr.length <= 104`
* `0 <= arr[i] <= 104` | 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, we compare two indices from scans checking whether they met at the peak of the mountain.\n\nTime: **O(n)** - scan\nSpace: **O(1)** - nothing stored\n\nRuntime: 196 ms, faster than **89.44%** of Python3 online submissions for Valid Mountain Array.\nMemory Usage: 15.3 MB, less than **99.55%** of Python3 online submissions for Valid Mountain Array.\n\n```\ndef validMountainArray(self, a: List[int]) -> bool:\n\tstart, end, L = 0, -1, len(a)\n\n\twhile start < L-1 and a[start] < a[start+1]: \n\t\tstart += 1\n\twhile end > -L and a[end] < a[end-1]: \n\t\tend -= 1\n\n\treturn start == end + L and 0 < start and end < -1\n```\n\n**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.** | 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 if:
* For `i <= k < j`:
* `arr[k] > arr[k + 1]` when `k` is odd, and
* `arr[k] < arr[k + 1]` when `k` is even.
* Or, for `i <= k < j`:
* `arr[k] > arr[k + 1]` when `k` is even, and
* `arr[k] < arr[k + 1]` when `k` is odd.
**Example 1:**
**Input:** arr = \[9,4,2,10,7,8,8,1,9\]
**Output:** 5
**Explanation:** arr\[1\] > arr\[2\] < arr\[3\] > arr\[4\] < arr\[5\]
**Example 2:**
**Input:** arr = \[4,8,12,16\]
**Output:** 2
**Example 3:**
**Input:** arr = \[100\]
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 4 * 104`
* `0 <= arr[i] <= 109` | 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 you will be able to come up with a straightforward solution. |
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 return False\n peak = 0\n while peak + 1 < n and arr[peak] < arr[peak + 1]:\n peak += 1\n\n if peak == 0 or peak == n - 1:\n return False\n\n while peak + 1 < n and arr[peak] > arr[peak + 1]:\n peak += 1\n \n return peak == 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] > ... > arr[arr.length - 1]`
**Example 1:**
**Input:** arr = \[2,1\]
**Output:** false
**Example 2:**
**Input:** arr = \[3,5,5\]
**Output:** false
**Example 3:**
**Input:** arr = \[0,3,2,1\]
**Output:** true
**Constraints:**
* `1 <= arr.length <= 104`
* `0 <= arr[i] <= 104` | 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 return False\n peak = 0\n while peak + 1 < n and arr[peak] < arr[peak + 1]:\n peak += 1\n\n if peak == 0 or peak == n - 1:\n return False\n\n while peak + 1 < n and arr[peak] > arr[peak + 1]:\n peak += 1\n \n return peak == 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 if:
* For `i <= k < j`:
* `arr[k] > arr[k + 1]` when `k` is odd, and
* `arr[k] < arr[k + 1]` when `k` is even.
* Or, for `i <= k < j`:
* `arr[k] > arr[k + 1]` when `k` is even, and
* `arr[k] < arr[k + 1]` when `k` is odd.
**Example 1:**
**Input:** arr = \[9,4,2,10,7,8,8,1,9\]
**Output:** 5
**Explanation:** arr\[1\] > arr\[2\] < arr\[3\] > arr\[4\] < arr\[5\]
**Example 2:**
**Input:** arr = \[4,8,12,16\]
**Output:** 2
**Example 3:**
**Input:** arr = \[100\]
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 4 * 104`
* `0 <= arr[i] <= 109` | 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 you will be able to come up with a straightforward solution. |
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 solving the problem. -->\nThe code uses a for loop to iterate over the elements of the array, starting from the second element. It then checks if the current element is greater than the previous element. If it is, it sets the variable strictly_increasing to True. If the current element is less than the previous element, it checks if strictly_increasing is True. If it is, it sets the variable strictly_decreasing to True. If the current element is equal to the previous element, the code returns False.\n\nIf the loop completes without returning False, the code returns True if both strictly_increasing and strictly_decreasing are True, else it returns False.\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution:\n def validMountainArray(self, arr: List[int]) -> bool:\n strictly_increasing = strictly_decreasing = False\n\n for i in range(1, len(arr)):\n if arr[i] > arr[i - 1]:\n if strictly_decreasing:\n return False\n strictly_increasing = True\n elif arr[i] < arr[i - 1]:\n if not strictly_increasing:\n return False\n strictly_decreasing = True\n else:\n return False\n\n return True if strictly_increasing and strictly_decreasing else False\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] > ... > arr[arr.length - 1]`
**Example 1:**
**Input:** arr = \[2,1\]
**Output:** false
**Example 2:**
**Input:** arr = \[3,5,5\]
**Output:** false
**Example 3:**
**Input:** arr = \[0,3,2,1\]
**Output:** true
**Constraints:**
* `1 <= arr.length <= 104`
* `0 <= arr[i] <= 104` | 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 solving the problem. -->\nThe code uses a for loop to iterate over the elements of the array, starting from the second element. It then checks if the current element is greater than the previous element. If it is, it sets the variable strictly_increasing to True. If the current element is less than the previous element, it checks if strictly_increasing is True. If it is, it sets the variable strictly_decreasing to True. If the current element is equal to the previous element, the code returns False.\n\nIf the loop completes without returning False, the code returns True if both strictly_increasing and strictly_decreasing are True, else it returns False.\n\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution:\n def validMountainArray(self, arr: List[int]) -> bool:\n strictly_increasing = strictly_decreasing = False\n\n for i in range(1, len(arr)):\n if arr[i] > arr[i - 1]:\n if strictly_decreasing:\n return False\n strictly_increasing = True\n elif arr[i] < arr[i - 1]:\n if not strictly_increasing:\n return False\n strictly_decreasing = True\n else:\n return False\n\n return True if strictly_increasing and strictly_decreasing else False\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 if:
* For `i <= k < j`:
* `arr[k] > arr[k + 1]` when `k` is odd, and
* `arr[k] < arr[k + 1]` when `k` is even.
* Or, for `i <= k < j`:
* `arr[k] > arr[k + 1]` when `k` is even, and
* `arr[k] < arr[k + 1]` when `k` is odd.
**Example 1:**
**Input:** arr = \[9,4,2,10,7,8,8,1,9\]
**Output:** 5
**Explanation:** arr\[1\] > arr\[2\] < arr\[3\] > arr\[4\] < arr\[5\]
**Example 2:**
**Input:** arr = \[4,8,12,16\]
**Output:** 2
**Example 3:**
**Input:** arr = \[100\]
**Output:** 1
**Constraints:**
* `1 <= arr.length <= 4 * 104`
* `0 <= arr[i] <= 109` | 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 you will be able to come up with a straightforward solution. |
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)$$ -->\n\n\n# Code\n```\nclass Solution:\n def diStringMatch(self, s: str) -> List[int]:\n per=[]\n lower=0\n upper=len(s)\n for i in s:\n if i==\'I\':\n per.append(lower)\n lower+=1\n else:\n per.append(upper)\n upper-=1\n if s[len(s)-1]==\'I\':\n per.append(upper)\n else:\n per.append(lower)\n return per\n\n \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 multiple valid permutations perm, return **any of them**.
**Example 1:**
**Input:** s = "IDID"
**Output:** \[0,4,1,3,2\]
**Example 2:**
**Input:** s = "III"
**Output:** \[0,1,2,3\]
**Example 3:**
**Input:** s = "DDI"
**Output:** \[3,2,0,1\]
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'I'` or `'D'`. | 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)$$ -->\n\n\n# Code\n```\nclass Solution:\n def diStringMatch(self, s: str) -> List[int]:\n per=[]\n lower=0\n upper=len(s)\n for i in s:\n if i==\'I\':\n per.append(lower)\n lower+=1\n else:\n per.append(upper)\n upper-=1\n if s[len(s)-1]==\'I\':\n per.append(upper)\n else:\n per.append(lower)\n return per\n\n \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.
Return _the **minimum** number of moves required to make every node have **exactly** one coin_.
**Example 1:**
**Input:** root = \[3,0,0\]
**Output:** 2
**Explanation:** From the root of the tree, we move one coin to its left child, and one coin to its right child.
**Example 2:**
**Input:** root = \[0,3,0\]
**Output:** 3
**Explanation:** From the left child of the root, we move two coins to the root \[taking two moves\]. Then, we move one coin from the root of the tree to the right child.
**Constraints:**
* The number of nodes in the tree is `n`.
* `1 <= n <= 100`
* `0 <= Node.val <= n`
* The sum of all `Node.val` is `n`. | 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 else:L.append(dc)\n return L\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 multiple valid permutations perm, return **any of them**.
**Example 1:**
**Input:** s = "IDID"
**Output:** \[0,4,1,3,2\]
**Example 2:**
**Input:** s = "III"
**Output:** \[0,1,2,3\]
**Example 3:**
**Input:** s = "DDI"
**Output:** \[3,2,0,1\]
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'I'` or `'D'`. | 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 else:L.append(dc)\n return L\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.
Return _the **minimum** number of moves required to make every node have **exactly** one coin_.
**Example 1:**
**Input:** root = \[3,0,0\]
**Output:** 2
**Explanation:** From the root of the tree, we move one coin to its left child, and one coin to its right child.
**Example 2:**
**Input:** root = \[0,3,0\]
**Output:** 3
**Explanation:** From the left child of the root, we move two coins to the root \[taking two moves\]. Then, we move one coin from the root of the tree to the right child.
**Constraints:**
* The number of nodes in the tree is `n`.
* `1 <= n <= 100`
* `0 <= Node.val <= n`
* The sum of all `Node.val` is `n`. | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def diStringMatch(self, s: str) -> List[int]:\n ans=[0]*(len(s)+1)\n count=0\n high=len(s)\n for i in range(len(s)):\n if s[i]=="I":\n ans[i]=count\n count+=1\n else:\n ans[i]=high\n high-=1\n ans[-1]=count\n return ans\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 multiple valid permutations perm, return **any of them**.
**Example 1:**
**Input:** s = "IDID"
**Output:** \[0,4,1,3,2\]
**Example 2:**
**Input:** s = "III"
**Output:** \[0,1,2,3\]
**Example 3:**
**Input:** s = "DDI"
**Output:** \[3,2,0,1\]
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'I'` or `'D'`. | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def diStringMatch(self, s: str) -> List[int]:\n ans=[0]*(len(s)+1)\n count=0\n high=len(s)\n for i in range(len(s)):\n if s[i]=="I":\n ans[i]=count\n count+=1\n else:\n ans[i]=high\n high-=1\n ans[-1]=count\n return ans\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.
Return _the **minimum** number of moves required to make every node have **exactly** one coin_.
**Example 1:**
**Input:** root = \[3,0,0\]
**Output:** 2
**Explanation:** From the root of the tree, we move one coin to its left child, and one coin to its right child.
**Example 2:**
**Input:** root = \[0,3,0\]
**Output:** 3
**Explanation:** From the left child of the root, we move two coins to the root \[taking two moves\]. Then, we move one coin from the root of the tree to the right child.
**Constraints:**
* The number of nodes in the tree is `n`.
* `1 <= n <= 100`
* `0 <= Node.val <= n`
* The sum of all `Node.val` is `n`. | 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 possible integer and the last element is the largest possible integer, such that each integer in the list is unique.\n\nThe function first initializes variables lenn to the length of the input string arr, i to 0, and j to lenn. It also initializes an empty list final to store the final output.\n\nNext, the function iterates over the characters in the input string arr. If the current character is "D", the function appends j to the final list and decrements j by 1. Otherwise, the function appends i to the final list and increments i by 1. This ensures that the integers in the output list are increasing or decreasing in accordance with the input string.\n\nFinally, the function checks the last character in the input string arr. If it is "I", the function appends the final value of i to the final list. Otherwise, it appends the final value of j.\n\nThe function returns the final list, which contains the unique integers that correspond to the input string arr.\n\nThe time complexity of the diStringMatch function is O(n), where n is the length of the input string arr, because the function performs a constant number of operations (appending to a list, decrementing or incrementing variables) for each character in the string.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\nclass Solution:\n def diStringMatch(self, arr: str) -> List[int]:\n lenn = len(arr)\n i = 0\n j = lenn\n final = []\n\n for k in range(lenn):\n if arr[k] == "D":\n final.append(j)\n j -= 1\n else:\n final.append(i)\n i += 1\n if arr[lenn-1] == "I":\n final.append(i)\n else:\n final.append(j)\n\n return final\n```\nUpvote will be Appreciated. | 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 multiple valid permutations perm, return **any of them**.
**Example 1:**
**Input:** s = "IDID"
**Output:** \[0,4,1,3,2\]
**Example 2:**
**Input:** s = "III"
**Output:** \[0,1,2,3\]
**Example 3:**
**Input:** s = "DDI"
**Output:** \[3,2,0,1\]
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'I'` or `'D'`. | 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 possible integer and the last element is the largest possible integer, such that each integer in the list is unique.\n\nThe function first initializes variables lenn to the length of the input string arr, i to 0, and j to lenn. It also initializes an empty list final to store the final output.\n\nNext, the function iterates over the characters in the input string arr. If the current character is "D", the function appends j to the final list and decrements j by 1. Otherwise, the function appends i to the final list and increments i by 1. This ensures that the integers in the output list are increasing or decreasing in accordance with the input string.\n\nFinally, the function checks the last character in the input string arr. If it is "I", the function appends the final value of i to the final list. Otherwise, it appends the final value of j.\n\nThe function returns the final list, which contains the unique integers that correspond to the input string arr.\n\nThe time complexity of the diStringMatch function is O(n), where n is the length of the input string arr, because the function performs a constant number of operations (appending to a list, decrementing or incrementing variables) for each character in the string.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N)\n\n# Code\n```\nclass Solution:\n def diStringMatch(self, arr: str) -> List[int]:\n lenn = len(arr)\n i = 0\n j = lenn\n final = []\n\n for k in range(lenn):\n if arr[k] == "D":\n final.append(j)\n j -= 1\n else:\n final.append(i)\n i += 1\n if arr[lenn-1] == "I":\n final.append(i)\n else:\n final.append(j)\n\n return final\n```\nUpvote will be Appreciated. | 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.
Return _the **minimum** number of moves required to make every node have **exactly** one coin_.
**Example 1:**
**Input:** root = \[3,0,0\]
**Output:** 2
**Explanation:** From the root of the tree, we move one coin to its left child, and one coin to its right child.
**Example 2:**
**Input:** root = \[0,3,0\]
**Output:** 3
**Explanation:** From the left child of the root, we move two coins to the root \[taking two moves\]. Then, we move one coin from the root of the tree to the right child.
**Constraints:**
* The number of nodes in the tree is `n`.
* `1 <= n <= 100`
* `0 <= Node.val <= n`
* The sum of all `Node.val` is `n`. | 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)$$ -->\n\n# Code\n```\nclass Solution:\n def diStringMatch(self, s: str) -> List[int]:\n res = [0]*(len(s)+1)\n i,j = 0,len(s)\n for k in range(len(s)):\n if s[k] == "I":\n res[k] = i\n i+=1\n else:\n res[k] = j\n j-=1\n if s[-1] == "I":\n res[-1] = i\n else:\n res[-1] = j\n return res \n\n\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 multiple valid permutations perm, return **any of them**.
**Example 1:**
**Input:** s = "IDID"
**Output:** \[0,4,1,3,2\]
**Example 2:**
**Input:** s = "III"
**Output:** \[0,1,2,3\]
**Example 3:**
**Input:** s = "DDI"
**Output:** \[3,2,0,1\]
**Constraints:**
* `1 <= s.length <= 105`
* `s[i]` is either `'I'` or `'D'`. | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.