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 3 (20ms) | Faster than 95% | Generating All Sequential Digits within Range | sequential-digits | 0 | 1 | ***Generating All Sequential Digits with help of of Array "a" and thus appending the required ones in Array "ans" which are within the range low and high :-***\n\n```\nclass Solution:\n def sequentialDigits(self, low: int, high: int) -> List[int]:\n l=len(str(low))\n h=len(str(high))\n ans=[]\n ... | 3 | An integer has _sequential digits_ if and only if each digit in the number is one more than the previous digit.
Return a **sorted** list of all the integers in the range `[low, high]` inclusive that have sequential digits.
**Example 1:**
**Input:** low = 100, high = 300
**Output:** \[123,234\]
**Example 2:**
**Inp... | null |
[Python3] prefix sum & binary search | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | 0 | 1 | Algorithm: \nBuild a `(m+1)x(n+1)` matrix of prefix sums of given matrix where `prefix[i][j] = sum(mat[:i][:j])`. And search for maximum `k` such that `sum(mat[i:i+k][j:j+k])` not exceeding threshold. Notice:\n1) `prefix[i+1][j+1] = prefix[i][j+1] + prefix[i+1][j] - prefix[i][j] + mat[i][j]`. \n2) `sum(mat[i:i+k][j:j+k... | 18 | Given a `m x n` matrix `mat` and an integer `threshold`, return _the maximum side-length of a square with a sum less than or equal to_ `threshold` _or return_ `0` _if there is no such square_.
**Example 1:**
**Input:** mat = \[\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\]\], threshold = 4
**Output:** 2
**Expl... | null |
[Python3] prefix sum & binary search | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | 0 | 1 | Algorithm: \nBuild a `(m+1)x(n+1)` matrix of prefix sums of given matrix where `prefix[i][j] = sum(mat[:i][:j])`. And search for maximum `k` such that `sum(mat[i:i+k][j:j+k])` not exceeding threshold. Notice:\n1) `prefix[i+1][j+1] = prefix[i][j+1] + prefix[i+1][j] - prefix[i][j] + mat[i][j]`. \n2) `sum(mat[i:i+k][j:j+k... | 18 | Given an array of integers `nums`, you start with an initial **positive** value _startValue__._
In each iteration, you calculate the step by step sum of _startValue_ plus elements in `nums` (from left to right).
Return the minimum **positive** value of _startValue_ such that the step by step sum is never less than 1.... | Store prefix sum of all grids in another 2D array. Try all possible solutions and if you cannot find one return -1. If x is a valid answer then any y < x is also valid answer. Use binary search to find answer. |
[ O(MN) ] Prefix Sum + Sliding Window. Beats 99% | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | 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(MN)\n\n- Space complexity: O(MN)\n\n# Code\n```\nclass Solution:\n def maxSideLength(self, mat: List[List[int]], threshold: int... | 0 | Given a `m x n` matrix `mat` and an integer `threshold`, return _the maximum side-length of a square with a sum less than or equal to_ `threshold` _or return_ `0` _if there is no such square_.
**Example 1:**
**Input:** mat = \[\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\]\], threshold = 4
**Output:** 2
**Expl... | null |
[ O(MN) ] Prefix Sum + Sliding Window. Beats 99% | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | 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(MN)\n\n- Space complexity: O(MN)\n\n# Code\n```\nclass Solution:\n def maxSideLength(self, mat: List[List[int]], threshold: int... | 0 | Given an array of integers `nums`, you start with an initial **positive** value _startValue__._
In each iteration, you calculate the step by step sum of _startValue_ plus elements in `nums` (from left to right).
Return the minimum **positive** value of _startValue_ such that the step by step sum is never less than 1.... | Store prefix sum of all grids in another 2D array. Try all possible solutions and if you cannot find one return -1. If x is a valid answer then any y < x is also valid answer. Use binary search to find answer. |
Prefix Sum & Binary Search | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n1.Add dummy row and column with value 0 for convenience.\n2.Compute prefix sum of mat.\n3.For a given side_length, square sum where the bottom right cell locates at (r, c) = mat[r][c] - mat[r-k][c] - mat[r][c-k] + mat[r-k][c-k].\n The test function r... | 0 | Given a `m x n` matrix `mat` and an integer `threshold`, return _the maximum side-length of a square with a sum less than or equal to_ `threshold` _or return_ `0` _if there is no such square_.
**Example 1:**
**Input:** mat = \[\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\]\], threshold = 4
**Output:** 2
**Expl... | null |
Prefix Sum & Binary Search | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n1.Add dummy row and column with value 0 for convenience.\n2.Compute prefix sum of mat.\n3.For a given side_length, square sum where the bottom right cell locates at (r, c) = mat[r][c] - mat[r-k][c] - mat[r][c-k] + mat[r-k][c-k].\n The test function r... | 0 | Given an array of integers `nums`, you start with an initial **positive** value _startValue__._
In each iteration, you calculate the step by step sum of _startValue_ plus elements in `nums` (from left to right).
Return the minimum **positive** value of _startValue_ such that the step by step sum is never less than 1.... | Store prefix sum of all grids in another 2D array. Try all possible solutions and if you cannot find one return -1. If x is a valid answer then any y < x is also valid answer. Use binary search to find answer. |
Solution | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int maxSideLength(vector<vector<int>>& mat, int threshold) {\n int row = mat.size(), col = mat.front().size();\n \n vector<vector<int>> psum(row, vector<int>(col, 0));\n psum[0][0] = mat[0][0];\n for (int i = 1; i < row; i++)\n psum... | 0 | Given a `m x n` matrix `mat` and an integer `threshold`, return _the maximum side-length of a square with a sum less than or equal to_ `threshold` _or return_ `0` _if there is no such square_.
**Example 1:**
**Input:** mat = \[\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\]\], threshold = 4
**Output:** 2
**Expl... | null |
Solution | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int maxSideLength(vector<vector<int>>& mat, int threshold) {\n int row = mat.size(), col = mat.front().size();\n \n vector<vector<int>> psum(row, vector<int>(col, 0));\n psum[0][0] = mat[0][0];\n for (int i = 1; i < row; i++)\n psum... | 0 | Given an array of integers `nums`, you start with an initial **positive** value _startValue__._
In each iteration, you calculate the step by step sum of _startValue_ plus elements in `nums` (from left to right).
Return the minimum **positive** value of _startValue_ such that the step by step sum is never less than 1.... | Store prefix sum of all grids in another 2D array. Try all possible solutions and if you cannot find one return -1. If x is a valid answer then any y < x is also valid answer. Use binary search to find answer. |
Easy Presum with For Loop | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | 0 | 1 | # Approach\nPresum[:i][:j] store the sum of all elements in mat[:i][:j]\n\nSo the sum for the rectangle of `[i+length][j+length]` is\n```\nprefix[i+length][j+length] - prefix[i][j+length] - prefix[i+length][j]\n+ prefix[i][j]\n```\nThen iterate all possible squares with starting points of [i,j], if there is a square th... | 0 | Given a `m x n` matrix `mat` and an integer `threshold`, return _the maximum side-length of a square with a sum less than or equal to_ `threshold` _or return_ `0` _if there is no such square_.
**Example 1:**
**Input:** mat = \[\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\],\[1,1,3,2,4,3,2\]\], threshold = 4
**Output:** 2
**Expl... | null |
Easy Presum with For Loop | maximum-side-length-of-a-square-with-sum-less-than-or-equal-to-threshold | 0 | 1 | # Approach\nPresum[:i][:j] store the sum of all elements in mat[:i][:j]\n\nSo the sum for the rectangle of `[i+length][j+length]` is\n```\nprefix[i+length][j+length] - prefix[i][j+length] - prefix[i+length][j]\n+ prefix[i][j]\n```\nThen iterate all possible squares with starting points of [i,j], if there is a square th... | 0 | Given an array of integers `nums`, you start with an initial **positive** value _startValue__._
In each iteration, you calculate the step by step sum of _startValue_ plus elements in `nums` (from left to right).
Return the minimum **positive** value of _startValue_ such that the step by step sum is never less than 1.... | Store prefix sum of all grids in another 2D array. Try all possible solutions and if you cannot find one return -1. If x is a valid answer then any y < x is also valid answer. Use binary search to find answer. |
Dijkstra, Python 3 | shortest-path-in-a-grid-with-obstacles-elimination | 0 | 1 | ```\nimport heapq\nclass Solution:\n def shortestPath(self, grid: List[List[int]], k: int) -> int:\n ROW, COL = len(grid), len(grid[0])\n # Dijkstra\n steps = []\n heapq.heappush(steps, (0, 0, ROW-1, COL-1))\n found = set([(ROW-1, COL-1)])\n while steps:\n s, remo... | 1 | You are given an `m x n` integer matrix `grid` where each cell is either `0` (empty) or `1` (obstacle). You can move up, down, left, or right from and to an empty cell in **one step**.
Return _the minimum number of **steps** to walk from the upper left corner_ `(0, 0)` _to the lower right corner_ `(m - 1, n - 1)` _giv... | Check every three consecutive numbers in the array for parity. |
Dijkstra, Python 3 | shortest-path-in-a-grid-with-obstacles-elimination | 0 | 1 | ```\nimport heapq\nclass Solution:\n def shortestPath(self, grid: List[List[int]], k: int) -> int:\n ROW, COL = len(grid), len(grid[0])\n # Dijkstra\n steps = []\n heapq.heappush(steps, (0, 0, ROW-1, COL-1))\n found = set([(ROW-1, COL-1)])\n while steps:\n s, remo... | 1 | Given an integer `k`, _return the minimum number of Fibonacci numbers whose sum is equal to_ `k`. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
* `F1 = 1`
* `F2 = 1`
* `Fn = Fn-1 + Fn-2` for `n > 2.`
It is guaranteed that for the given constraints we can always fin... | Use BFS. BFS on (x,y,r) x,y is coordinate, r is remain number of obstacles you can remove. |
Simple solution using BFS traversal (58% Faster, 99.44% memory efficient) | shortest-path-in-a-grid-with-obstacles-elimination | 0 | 1 | ```\nimport heapq\nclass Solution:\n def shortestPath(self, grid: List[List[int]], k: int) -> int:\n m=len(grid)\n n=len(grid[0])\n visited=[[-1]*n for _ in range(m)]\n lst=[(0,-1*k,0,0)]\n visited[0][0]=1\n row=[-1,1,0,0]\n col=[0,0,-1,1]\n heapq.heapify(lst)\... | 1 | You are given an `m x n` integer matrix `grid` where each cell is either `0` (empty) or `1` (obstacle). You can move up, down, left, or right from and to an empty cell in **one step**.
Return _the minimum number of **steps** to walk from the upper left corner_ `(0, 0)` _to the lower right corner_ `(m - 1, n - 1)` _giv... | Check every three consecutive numbers in the array for parity. |
Simple solution using BFS traversal (58% Faster, 99.44% memory efficient) | shortest-path-in-a-grid-with-obstacles-elimination | 0 | 1 | ```\nimport heapq\nclass Solution:\n def shortestPath(self, grid: List[List[int]], k: int) -> int:\n m=len(grid)\n n=len(grid[0])\n visited=[[-1]*n for _ in range(m)]\n lst=[(0,-1*k,0,0)]\n visited[0][0]=1\n row=[-1,1,0,0]\n col=[0,0,-1,1]\n heapq.heapify(lst)\... | 1 | Given an integer `k`, _return the minimum number of Fibonacci numbers whose sum is equal to_ `k`. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
* `F1 = 1`
* `F2 = 1`
* `Fn = Fn-1 + Fn-2` for `n > 2.`
It is guaranteed that for the given constraints we can always fin... | Use BFS. BFS on (x,y,r) x,y is coordinate, r is remain number of obstacles you can remove. |
Dual BFS!!! | Beats 99.43%!!! | First Dual BFS Solution Posted in LeetCode!!! | shortest-path-in-a-grid-with-obstacles-elimination | 0 | 1 | [TOC]\n\n# Approach\nStart search from both sides.\n\nTo use dual BFS, we need to record the number of eliminated obstacles from both side, say `used`, seperately, because one coordinate can be reached from both sides, and for each side, there might be different path with different number of eliminated obstacles.\n\nSi... | 1 | You are given an `m x n` integer matrix `grid` where each cell is either `0` (empty) or `1` (obstacle). You can move up, down, left, or right from and to an empty cell in **one step**.
Return _the minimum number of **steps** to walk from the upper left corner_ `(0, 0)` _to the lower right corner_ `(m - 1, n - 1)` _giv... | Check every three consecutive numbers in the array for parity. |
Dual BFS!!! | Beats 99.43%!!! | First Dual BFS Solution Posted in LeetCode!!! | shortest-path-in-a-grid-with-obstacles-elimination | 0 | 1 | [TOC]\n\n# Approach\nStart search from both sides.\n\nTo use dual BFS, we need to record the number of eliminated obstacles from both side, say `used`, seperately, because one coordinate can be reached from both sides, and for each side, there might be different path with different number of eliminated obstacles.\n\nSi... | 1 | Given an integer `k`, _return the minimum number of Fibonacci numbers whose sum is equal to_ `k`. The same Fibonacci number can be used multiple times.
The Fibonacci numbers are defined as:
* `F1 = 1`
* `F2 = 1`
* `Fn = Fn-1 + Fn-2` for `n > 2.`
It is guaranteed that for the given constraints we can always fin... | Use BFS. BFS on (x,y,r) x,y is coordinate, r is remain number of obstacles you can remove. |
Simplest Python one-liner | find-numbers-with-even-number-of-digits | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def findNumbers(self, nums: List[int]) -> int:\n return len([x for x in nums if len(str(x)) % 2 == 0])\n``` | 2 | Given an array `nums` of integers, return how many of them contain an **even number** of digits.
**Example 1:**
**Input:** nums = \[12,345,2,6,7896\]
**Output:** 2
**Explanation:**
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).... | Find a formula for the number of apples inside a square with a side length L. Iterate over the possible lengths of the square until enough apples are collected. |
Python Simple Solution-O(n),O(n) | find-numbers-with-even-number-of-digits | 0 | 1 | # Intuition\n1)Task is to find out how many given numbers has even number of digits.\n2)Check the length of the integers after converting them into string format\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nBrute Force Approach : Convert the integers into string format and then ch... | 1 | Given an array `nums` of integers, return how many of them contain an **even number** of digits.
**Example 1:**
**Input:** nums = \[12,345,2,6,7896\]
**Output:** 2
**Explanation:**
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).... | Find a formula for the number of apples inside a square with a side length L. Iterate over the possible lengths of the square until enough apples are collected. |
Python 3 lightning fast one line solution | find-numbers-with-even-number-of-digits | 0 | 1 | ```\nclass Solution:\n def findNumbers(self, nums: List[int]) -> int:\n return len([x for x in nums if len(str(x)) % 2 == 0])\n``` | 32 | Given an array `nums` of integers, return how many of them contain an **even number** of digits.
**Example 1:**
**Input:** nums = \[12,345,2,6,7896\]
**Output:** 2
**Explanation:**
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).... | Find a formula for the number of apples inside a square with a side length L. Iterate over the possible lengths of the square until enough apples are collected. |
1 Liner using map | find-numbers-with-even-number-of-digits | 0 | 1 | # Code\n```\nclass Solution:\n def findNumbers(self, nums: List[int]) -> int:\n return sum(not n&1 for n in map(len, map(str, nums)))\n``` | 3 | Given an array `nums` of integers, return how many of them contain an **even number** of digits.
**Example 1:**
**Input:** nums = \[12,345,2,6,7896\]
**Output:** 2
**Explanation:**
12 contains 2 digits (even number of digits).
345 contains 3 digits (odd number of digits).
2 contains 1 digit (odd number of digits).... | Find a formula for the number of apples inside a square with a side length L. Iterate over the possible lengths of the square until enough apples are collected. |
Easy to understand Python Solution | divide-array-in-sets-of-k-consecutive-numbers | 0 | 1 | # Code\n```\nclass Solution:\n def isPossibleDivide(self, nums: List[int], k: int) -> bool:\n nums.sort()\n count = Counter(nums)\n\n if len(nums)%k!=0:\n return False\n\n for num in nums:\n if count[num]:\n for n in range(num,num+k):\n ... | 0 | Given an array of integers `nums` and a positive integer `k`, check whether it is possible to divide this array into sets of `k` consecutive numbers.
Return `true` _if it is possible_. Otherwise, return `false`.
**Example 1:**
**Input:** nums = \[1,2,3,3,4,4,5,6\], k = 4
**Output:** true
**Explanation:** Array can b... | The queries must be answered efficiently to avoid time limit exceeded verdict. Use sparse table (dynamic programming application) to travel the tree upwards in a fast way. |
Easy to understand Python Solution | divide-array-in-sets-of-k-consecutive-numbers | 0 | 1 | # Code\n```\nclass Solution:\n def isPossibleDivide(self, nums: List[int], k: int) -> bool:\n nums.sort()\n count = Counter(nums)\n\n if len(nums)%k!=0:\n return False\n\n for num in nums:\n if count[num]:\n for n in range(num,num+k):\n ... | 0 | Given a string `s` of zeros and ones, _return the maximum score after splitting the string into two **non-empty** substrings_ (i.e. **left** substring and **right** substring).
The score after splitting a string is the number of **zeros** in the **left** substring plus the number of **ones** in the **right** substring... | If the smallest number in the possible-to-split array is V, then numbers V+1, V+2, ... V+k-1 must contain there as well. You can iteratively find k sets and remove them from array until it becomes empty. Failure to do so would mean that array is unsplittable. |
Intuitive Python solution - using template | maximum-number-of-occurrences-of-a-substring | 0 | 1 | # Approach\n\nIn short, we record each VALID substrings and their occurrence and return their max occ. \n\nUsing sliding window template to solve this problem. Having left and right index. We update the occurrence of specific substring when it meets the conditions, and we need to shrink the window when its length is in... | 1 | Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must be between `minSize` and `maxSize` inclusive.
**Example 1:**
**Input:** s = "aababc... | Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon". |
Intuitive Python solution - using template | maximum-number-of-occurrences-of-a-substring | 0 | 1 | # Approach\n\nIn short, we record each VALID substrings and their occurrence and return their max occ. \n\nUsing sliding window template to solve this problem. Having left and right index. We update the occurrence of specific substring when it meets the conditions, and we need to shrink the window when its length is in... | 1 | There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards.
Your score is the sum of the points of the card... | Check out the constraints, (maxSize <=26). This means you can explore all substrings in O(n * 26). Find the Maximum Number of Occurrences of a Substring with bruteforce. |
Use hashmap, only store subs which satisfy the maxLetters | maximum-number-of-occurrences-of-a-substring | 0 | 1 | # Intuition\nFirstly, you can ignore the maxSize. Why ?\nA window with repeated maxSize will always satisfy its prefix and minSize of that repeated maxSize substring would be a prefix. If we can already satisfy the prefix so why even bother moving any further. Also, with minSize, our substring size will be small and ha... | 1 | Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must be between `minSize` and `maxSize` inclusive.
**Example 1:**
**Input:** s = "aababc... | Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon". |
Use hashmap, only store subs which satisfy the maxLetters | maximum-number-of-occurrences-of-a-substring | 0 | 1 | # Intuition\nFirstly, you can ignore the maxSize. Why ?\nA window with repeated maxSize will always satisfy its prefix and minSize of that repeated maxSize substring would be a prefix. If we can already satisfy the prefix so why even bother moving any further. Also, with minSize, our substring size will be small and ha... | 1 | There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards.
Your score is the sum of the points of the card... | Check out the constraints, (maxSize <=26). This means you can explore all substrings in O(n * 26). Find the Maximum Number of Occurrences of a Substring with bruteforce. |
Python 3 || 2 lines, Counter || T/M: 100% / 29% | maximum-number-of-occurrences-of-a-substring | 0 | 1 | Another`Counter`version for consideration. Two observations:\n- The`maxSize`parameter is a "red herring." I suspect it was added to make this problem a *Medium* rather than an *Easy*. For example, if the string`"abcdef"`has five occurrences, then so does`"abc"` Thus, if `minSize = 3`, then we only need check strings of... | 4 | Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must be between `minSize` and `maxSize` inclusive.
**Example 1:**
**Input:** s = "aababc... | Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon". |
Python 3 || 2 lines, Counter || T/M: 100% / 29% | maximum-number-of-occurrences-of-a-substring | 0 | 1 | Another`Counter`version for consideration. Two observations:\n- The`maxSize`parameter is a "red herring." I suspect it was added to make this problem a *Medium* rather than an *Easy*. For example, if the string`"abcdef"`has five occurrences, then so does`"abc"` Thus, if `minSize = 3`, then we only need check strings of... | 4 | There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards.
Your score is the sum of the points of the card... | Check out the constraints, (maxSize <=26). This means you can explore all substrings in O(n * 26). Find the Maximum Number of Occurrences of a Substring with bruteforce. |
✅ Python Hashmap Easy Approach ✅ | maximum-number-of-occurrences-of-a-substring | 0 | 1 | # Code\n```\nclass Solution:\n def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:\n d = defaultdict(int)\n\n for i in range(0, len(s)-minSize+1):\n if len(set((t:=s[i:minSize+i]))) <= maxLetters: d[t] += 1\n\n return max(d.values()) if d else 0\n \n`... | 1 | Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must be between `minSize` and `maxSize` inclusive.
**Example 1:**
**Input:** s = "aababc... | Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon". |
✅ Python Hashmap Easy Approach ✅ | maximum-number-of-occurrences-of-a-substring | 0 | 1 | # Code\n```\nclass Solution:\n def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:\n d = defaultdict(int)\n\n for i in range(0, len(s)-minSize+1):\n if len(set((t:=s[i:minSize+i]))) <= maxLetters: d[t] += 1\n\n return max(d.values()) if d else 0\n \n`... | 1 | There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards.
Your score is the sum of the points of the card... | Check out the constraints, (maxSize <=26). This means you can explore all substrings in O(n * 26). Find the Maximum Number of Occurrences of a Substring with bruteforce. |
python easy approach | maximum-number-of-occurrences-of-a-substring | 0 | 1 | ```\nclass Solution:\n def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:\n s1 = []\n count ={}\n while minSize <= maxSize:\n for i in range(0,len(s)):\n if (i+ minSize) <=len(s) and len(set(s[i: i+ minSize])) <= maxLetters:\n ... | 4 | Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must be between `minSize` and `maxSize` inclusive.
**Example 1:**
**Input:** s = "aababc... | Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon". |
python easy approach | maximum-number-of-occurrences-of-a-substring | 0 | 1 | ```\nclass Solution:\n def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:\n s1 = []\n count ={}\n while minSize <= maxSize:\n for i in range(0,len(s)):\n if (i+ minSize) <=len(s) and len(set(s[i: i+ minSize])) <= maxLetters:\n ... | 4 | There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards.
Your score is the sum of the points of the card... | Check out the constraints, (maxSize <=26). This means you can explore all substrings in O(n * 26). Find the Maximum Number of Occurrences of a Substring with bruteforce. |
[Python] O(n) simple solution using counter. | maximum-number-of-occurrences-of-a-substring | 0 | 1 | ```python\n def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:\n # count frequency of characters\n count = collections.Counter()\n \n # Check only for minSize\n for i in range(len(s) - minSize + 1):\n t = s[i : i+minSize]\n if len(set(... | 9 | Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must be between `minSize` and `maxSize` inclusive.
**Example 1:**
**Input:** s = "aababc... | Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon". |
[Python] O(n) simple solution using counter. | maximum-number-of-occurrences-of-a-substring | 0 | 1 | ```python\n def maxFreq(self, s: str, maxLetters: int, minSize: int, maxSize: int) -> int:\n # count frequency of characters\n count = collections.Counter()\n \n # Check only for minSize\n for i in range(len(s) - minSize + 1):\n t = s[i : i+minSize]\n if len(set(... | 9 | There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards.
Your score is the sum of the points of the card... | Check out the constraints, (maxSize <=26). This means you can explore all substrings in O(n * 26). Find the Maximum Number of Occurrences of a Substring with bruteforce. |
You just have to focus on minSize | maximum-number-of-occurrences-of-a-substring | 0 | 1 | # Intuition\nUnderstand there is no need to check for maxSize.\n\n# Approach\nCheck for the occurance on minSize and add them to dictionary. Finally return the max value.\n\n# Complexity\n- Time complexity:\n The time complexity of this solution be O(N * K / M) where N = input size ; M = minSize and K = size of the di... | 0 | Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must be between `minSize` and `maxSize` inclusive.
**Example 1:**
**Input:** s = "aababc... | Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon". |
You just have to focus on minSize | maximum-number-of-occurrences-of-a-substring | 0 | 1 | # Intuition\nUnderstand there is no need to check for maxSize.\n\n# Approach\nCheck for the occurance on minSize and add them to dictionary. Finally return the max value.\n\n# Complexity\n- Time complexity:\n The time complexity of this solution be O(N * K / M) where N = input size ; M = minSize and K = size of the di... | 0 | There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards.
Your score is the sum of the points of the card... | Check out the constraints, (maxSize <=26). This means you can explore all substrings in O(n * 26). Find the Maximum Number of Occurrences of a Substring with bruteforce. |
Python Easy to Understand and Efficient Sliding Window | maximum-number-of-occurrences-of-a-substring | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a string `s`, return the maximum number of ocurrences of **any** substring under the following rules:
* The number of unique characters in the substring must be less than or equal to `maxLetters`.
* The substring size must be between `minSize` and `maxSize` inclusive.
**Example 1:**
**Input:** s = "aababc... | Count the frequency of letters in the given string. Find the letter than can make the minimum number of instances of the word "balloon". |
Python Easy to Understand and Efficient Sliding Window | maximum-number-of-occurrences-of-a-substring | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | There are several cards **arranged in a row**, and each card has an associated number of points. The points are given in the integer array `cardPoints`.
In one step, you can take one card from the beginning or from the end of the row. You have to take exactly `k` cards.
Your score is the sum of the points of the card... | Check out the constraints, (maxSize <=26). This means you can explore all substrings in O(n * 26). Find the Maximum Number of Occurrences of a Substring with bruteforce. |
Python, C++ Solution || modified BFS Solution easy to understand | maximum-candies-you-can-get-from-boxes | 0 | 1 | # Intuition\nWe check boxes in queue once every iteration, if no box get opened, then we finished the BFS.\n\nIn BFS, if a box is open, we do 4 things.\n1. opened += 1 to track if there has boxes opened or not in a iteration.\n2. add candy to ans.\n3. change the status of box to open if there\'s the key.\n4. append the... | 0 | You have `n` boxes labeled from `0` to `n - 1`. You are given four arrays: `status`, `candies`, `keys`, and `containedBoxes` where:
* `status[i]` is `1` if the `ith` box is open and `0` if the `ith` box is closed,
* `candies[i]` is the number of candies in the `ith` box,
* `keys[i]` is a list of the labels of th... | Find all brackets in the string. Does the order of the reverse matter ? The order does not matter. |
Python, C++ Solution || modified BFS Solution easy to understand | maximum-candies-you-can-get-from-boxes | 0 | 1 | # Intuition\nWe check boxes in queue once every iteration, if no box get opened, then we finished the BFS.\n\nIn BFS, if a box is open, we do 4 things.\n1. opened += 1 to track if there has boxes opened or not in a iteration.\n2. add candy to ans.\n3. change the status of box to open if there\'s the key.\n4. append the... | 0 | Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_.
**Example 1:**
**Input:** nums = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,4,2,7,5,3,8,6,9\]
**Example 2:**
**Input:** nums = \[\[1,2,3,4,5\],\[6,7\],\[8\],\[9,10,11\],\[12,13,14,15,16\]\]
**Ou... | Use Breadth First Search (BFS) to traverse all possible boxes you can open. Only push to the queue the boxes the you have with their keys. |
Python 3: Simple BFS | maximum-candies-you-can-get-from-boxes | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | You have `n` boxes labeled from `0` to `n - 1`. You are given four arrays: `status`, `candies`, `keys`, and `containedBoxes` where:
* `status[i]` is `1` if the `ith` box is open and `0` if the `ith` box is closed,
* `candies[i]` is the number of candies in the `ith` box,
* `keys[i]` is a list of the labels of th... | Find all brackets in the string. Does the order of the reverse matter ? The order does not matter. |
Python 3: Simple BFS | maximum-candies-you-can-get-from-boxes | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_.
**Example 1:**
**Input:** nums = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,4,2,7,5,3,8,6,9\]
**Example 2:**
**Input:** nums = \[\[1,2,3,4,5\],\[6,7\],\[8\],\[9,10,11\],\[12,13,14,15,16\]\]
**Ou... | Use Breadth First Search (BFS) to traverse all possible boxes you can open. Only push to the queue the boxes the you have with their keys. |
Shortest BFS Code With Explanation | maximum-candies-you-can-get-from-boxes | 0 | 1 | \n\n```\nBox 1 initially was closed(0), but later when we found a key to open box 1 we opened it.\n\nThat means if we find hundred boxes which is closed but later w... | 0 | You have `n` boxes labeled from `0` to `n - 1`. You are given four arrays: `status`, `candies`, `keys`, and `containedBoxes` where:
* `status[i]` is `1` if the `ith` box is open and `0` if the `ith` box is closed,
* `candies[i]` is the number of candies in the `ith` box,
* `keys[i]` is a list of the labels of th... | Find all brackets in the string. Does the order of the reverse matter ? The order does not matter. |
Shortest BFS Code With Explanation | maximum-candies-you-can-get-from-boxes | 0 | 1 | \n\n```\nBox 1 initially was closed(0), but later when we found a key to open box 1 we opened it.\n\nThat means if we find hundred boxes which is closed but later w... | 0 | Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_.
**Example 1:**
**Input:** nums = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,4,2,7,5,3,8,6,9\]
**Example 2:**
**Input:** nums = \[\[1,2,3,4,5\],\[6,7\],\[8\],\[9,10,11\],\[12,13,14,15,16\]\]
**Ou... | Use Breadth First Search (BFS) to traverse all possible boxes you can open. Only push to the queue the boxes the you have with their keys. |
Simple Python3 BFS | maximum-candies-you-can-get-from-boxes | 0 | 1 | ```\nclass Solution:\n def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:\n queue = [i for i in initialBoxes if status[i] == 1]\n visited = set(queue)\n res = 0\n #haskeys = set([])\n ... | 0 | You have `n` boxes labeled from `0` to `n - 1`. You are given four arrays: `status`, `candies`, `keys`, and `containedBoxes` where:
* `status[i]` is `1` if the `ith` box is open and `0` if the `ith` box is closed,
* `candies[i]` is the number of candies in the `ith` box,
* `keys[i]` is a list of the labels of th... | Find all brackets in the string. Does the order of the reverse matter ? The order does not matter. |
Simple Python3 BFS | maximum-candies-you-can-get-from-boxes | 0 | 1 | ```\nclass Solution:\n def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:\n queue = [i for i in initialBoxes if status[i] == 1]\n visited = set(queue)\n res = 0\n #haskeys = set([])\n ... | 0 | Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_.
**Example 1:**
**Input:** nums = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,4,2,7,5,3,8,6,9\]
**Example 2:**
**Input:** nums = \[\[1,2,3,4,5\],\[6,7\],\[8\],\[9,10,11\],\[12,13,14,15,16\]\]
**Ou... | Use Breadth First Search (BFS) to traverse all possible boxes you can open. Only push to the queue the boxes the you have with their keys. |
Solution | maximum-candies-you-can-get-from-boxes | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int maxCandies(vector<int>& status, vector<int>& candies, vector<vector<int>>& keys, vector<vector<int>>& containedBoxes, vector<int>& initialBoxes) {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n \n int n = candies.size(), ans... | 0 | You have `n` boxes labeled from `0` to `n - 1`. You are given four arrays: `status`, `candies`, `keys`, and `containedBoxes` where:
* `status[i]` is `1` if the `ith` box is open and `0` if the `ith` box is closed,
* `candies[i]` is the number of candies in the `ith` box,
* `keys[i]` is a list of the labels of th... | Find all brackets in the string. Does the order of the reverse matter ? The order does not matter. |
Solution | maximum-candies-you-can-get-from-boxes | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int maxCandies(vector<int>& status, vector<int>& candies, vector<vector<int>>& keys, vector<vector<int>>& containedBoxes, vector<int>& initialBoxes) {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n \n int n = candies.size(), ans... | 0 | Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_.
**Example 1:**
**Input:** nums = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,4,2,7,5,3,8,6,9\]
**Example 2:**
**Input:** nums = \[\[1,2,3,4,5\],\[6,7\],\[8\],\[9,10,11\],\[12,13,14,15,16\]\]
**Ou... | Use Breadth First Search (BFS) to traverse all possible boxes you can open. Only push to the queue the boxes the you have with their keys. |
Deque | Fast | Python Solution | maximum-candies-you-can-get-from-boxes | 0 | 1 | \n# Code\n```\nfrom collections import deque\nclass Solution:\n def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:\n \n q = deque(initialBoxes)\n visited = set()\n res = 0\n while q:\n... | 0 | You have `n` boxes labeled from `0` to `n - 1`. You are given four arrays: `status`, `candies`, `keys`, and `containedBoxes` where:
* `status[i]` is `1` if the `ith` box is open and `0` if the `ith` box is closed,
* `candies[i]` is the number of candies in the `ith` box,
* `keys[i]` is a list of the labels of th... | Find all brackets in the string. Does the order of the reverse matter ? The order does not matter. |
Deque | Fast | Python Solution | maximum-candies-you-can-get-from-boxes | 0 | 1 | \n# Code\n```\nfrom collections import deque\nclass Solution:\n def maxCandies(self, status: List[int], candies: List[int], keys: List[List[int]], containedBoxes: List[List[int]], initialBoxes: List[int]) -> int:\n \n q = deque(initialBoxes)\n visited = set()\n res = 0\n while q:\n... | 0 | Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_.
**Example 1:**
**Input:** nums = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,4,2,7,5,3,8,6,9\]
**Example 2:**
**Input:** nums = \[\[1,2,3,4,5\],\[6,7\],\[8\],\[9,10,11\],\[12,13,14,15,16\]\]
**Ou... | Use Breadth First Search (BFS) to traverse all possible boxes you can open. Only push to the queue the boxes the you have with their keys. |
Plain BFS Solution. 80.90% | maximum-candies-you-can-get-from-boxes | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n Problem is SIMPLE BFS with just one addition of keys and that works based on few conditions.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n 1) If we get any box with locked status we can store that bo... | 0 | You have `n` boxes labeled from `0` to `n - 1`. You are given four arrays: `status`, `candies`, `keys`, and `containedBoxes` where:
* `status[i]` is `1` if the `ith` box is open and `0` if the `ith` box is closed,
* `candies[i]` is the number of candies in the `ith` box,
* `keys[i]` is a list of the labels of th... | Find all brackets in the string. Does the order of the reverse matter ? The order does not matter. |
Plain BFS Solution. 80.90% | maximum-candies-you-can-get-from-boxes | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n Problem is SIMPLE BFS with just one addition of keys and that works based on few conditions.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n 1) If we get any box with locked status we can store that bo... | 0 | Given a 2D integer array `nums`, return _all elements of_ `nums` _in diagonal order as shown in the below images_.
**Example 1:**
**Input:** nums = \[\[1,2,3\],\[4,5,6\],\[7,8,9\]\]
**Output:** \[1,4,2,7,5,3,8,6,9\]
**Example 2:**
**Input:** nums = \[\[1,2,3,4,5\],\[6,7\],\[8\],\[9,10,11\],\[12,13,14,15,16\]\]
**Ou... | Use Breadth First Search (BFS) to traverse all possible boxes you can open. Only push to the queue the boxes the you have with their keys. |
real in place solution on python | replace-elements-with-greatest-element-on-right-side | 0 | 1 | # Approach\n1. for comfortable we need to start for the last elem, but we musn\'t use reversed or [::-1] becouse its create a new list. its not in place. We should not create any structure.\n2. We need to start loop for the last element.\n3. After that we comparable number with temporary max\n4. if number bigger than m... | 2 | Given an array `arr`, replace every element in that array with the greatest element among the elements to its right, and replace the last element with `-1`.
After doing so, return the array.
**Example 1:**
**Input:** arr = \[17,18,5,4,6,1\]
**Output:** \[18,6,6,6,1,-1\]
**Explanation:**
- index 0 --> the greatest e... | How to solve the problem for k=1 ? Use Kadane's algorithm for k=1. What are the possible cases for the answer ? The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1. |
Easy to Understand | Simple | Python Solution | replace-elements-with-greatest-element-on-right-side | 0 | 1 | ```\ndef replaceElements(self, arr: List[int]) -> List[int]:\n m = -1\n i = len(arr) -1 \n while i >= 0:\n temp = arr[i]\n arr[i] = m\n if temp > m:\n m = temp\n i-= 1\n return arr\n```\n\n**I hope that you\'ve found the solution use... | 47 | Given an array `arr`, replace every element in that array with the greatest element among the elements to its right, and replace the last element with `-1`.
After doing so, return the array.
**Example 1:**
**Input:** arr = \[17,18,5,4,6,1\]
**Output:** \[18,6,6,6,1,-1\]
**Explanation:**
- index 0 --> the greatest e... | How to solve the problem for k=1 ? Use Kadane's algorithm for k=1. What are the possible cases for the answer ? The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1. |
Python 3, simple For loop for suffix max approach, time complexity: O(n), Space complexity: O(1) | replace-elements-with-greatest-element-on-right-side | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt can be solved by suffix sum approach\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHere we are storing previous maxvalue and replacing array element with the same if it is not last element. I am using 2 variab... | 2 | Given an array `arr`, replace every element in that array with the greatest element among the elements to its right, and replace the last element with `-1`.
After doing so, return the array.
**Example 1:**
**Input:** arr = \[17,18,5,4,6,1\]
**Output:** \[18,6,6,6,1,-1\]
**Explanation:**
- index 0 --> the greatest e... | How to solve the problem for k=1 ? Use Kadane's algorithm for k=1. What are the possible cases for the answer ? The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1. |
Easy Python Solution | replace-elements-with-greatest-element-on-right-side | 0 | 1 | ```\nclass Solution:\n def replaceElements(self, arr: List[int]) -> List[int]:\n maxi=-1\n n=len(arr)\n for i in range(n-1, -1, -1):\n temp=arr[i]\n arr[i]=maxi\n maxi=max(maxi, temp)\n return arr\n``` | 1 | Given an array `arr`, replace every element in that array with the greatest element among the elements to its right, and replace the last element with `-1`.
After doing so, return the array.
**Example 1:**
**Input:** arr = \[17,18,5,4,6,1\]
**Output:** \[18,6,6,6,1,-1\]
**Explanation:**
- index 0 --> the greatest e... | How to solve the problem for k=1 ? Use Kadane's algorithm for k=1. What are the possible cases for the answer ? The answer is the maximum between, the answer for k=1, the sum of the whole array multiplied by k, or the maximum suffix sum plus the maximum prefix sum plus (k-2) multiplied by the whole array sum for k > 1. |
Simple Binary Search approach without Sorting. | sum-of-mutated-array-closest-to-target | 0 | 1 | # Intuition\nI thought of completing this problem without any extra space. So, the arrsum function I thought would take O(n) time to find arrsum. If I iterate through every possiblilty it will lead to O(N*N) .So, I used Binary Search therefore, O(N*logN).\n\n# Approach\nUse two Binary searches in the possible range (ta... | 0 | Given an integer array `arr` and a target value `target`, return the integer `value` such that when we change all the integers larger than `value` in the given array to be equal to `value`, the sum of the array gets as close as possible (in absolute difference) to `target`.
In case of a tie, return the minimum such in... | Use Tarjan's algorithm. |
Simple Binary Search approach without Sorting. | sum-of-mutated-array-closest-to-target | 0 | 1 | # Intuition\nI thought of completing this problem without any extra space. So, the arrsum function I thought would take O(n) time to find arrsum. If I iterate through every possiblilty it will lead to O(N*N) .So, I used Binary Search therefore, O(N*logN).\n\n# Approach\nUse two Binary searches in the possible range (ta... | 0 | You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane.
**Example 1:**
**Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\]
**Output:** true
**Example 2:**
**Input:** coo... | If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value. |
[Python3] Sort & scan | sum-of-mutated-array-closest-to-target | 0 | 1 | Algorithm:\nSort the array in ascending order. \nAt each index `i`, compute the value to set `arr[i:]` to so that `sum(arr)` would be closest to `target`. If this value is smaller than `arr[i]`, return it; otherwise, return `arr[-1]`. \n\nImplementation (24ms, 100%):\n```\nclass Solution:\n def findBestValue(self, a... | 22 | Given an integer array `arr` and a target value `target`, return the integer `value` such that when we change all the integers larger than `value` in the given array to be equal to `value`, the sum of the array gets as close as possible (in absolute difference) to `target`.
In case of a tie, return the minimum such in... | Use Tarjan's algorithm. |
[Python3] Sort & scan | sum-of-mutated-array-closest-to-target | 0 | 1 | Algorithm:\nSort the array in ascending order. \nAt each index `i`, compute the value to set `arr[i:]` to so that `sum(arr)` would be closest to `target`. If this value is smaller than `arr[i]`, return it; otherwise, return `arr[-1]`. \n\nImplementation (24ms, 100%):\n```\nclass Solution:\n def findBestValue(self, a... | 22 | You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane.
**Example 1:**
**Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\]
**Output:** true
**Example 2:**
**Input:** coo... | If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value. |
Python solution with video explanation | sum-of-mutated-array-closest-to-target | 0 | 1 | [https://www.youtube.com/watch?v=j0KejYpI_Mc&feature=youtu.be]\n```\nclass Solution:\n def findBestValue(self, arr: List[int], target: int) -> int:\n arr.sort()\n length = len(arr)\n \n for x in range(length):\n sol = round(target / length)\n if arr[x] >= sol:\n ... | 5 | Given an integer array `arr` and a target value `target`, return the integer `value` such that when we change all the integers larger than `value` in the given array to be equal to `value`, the sum of the array gets as close as possible (in absolute difference) to `target`.
In case of a tie, return the minimum such in... | Use Tarjan's algorithm. |
Python solution with video explanation | sum-of-mutated-array-closest-to-target | 0 | 1 | [https://www.youtube.com/watch?v=j0KejYpI_Mc&feature=youtu.be]\n```\nclass Solution:\n def findBestValue(self, arr: List[int], target: int) -> int:\n arr.sort()\n length = len(arr)\n \n for x in range(length):\n sol = round(target / length)\n if arr[x] >= sol:\n ... | 5 | You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane.
**Example 1:**
**Input:** coordinates = \[\[1,2\],\[2,3\],\[3,4\],\[4,5\],\[5,6\],\[6,7\]\]
**Output:** true
**Example 2:**
**Input:** coo... | If you draw a graph with the value on one axis and the absolute difference between the target and the array sum, what will you get? That graph is uni-modal. Use ternary search on that graph to find the best value. |
Python (Simple DP) | number-of-paths-with-max-score | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given a square `board` of characters. You can move on the board starting at the bottom right square marked with the character `'S'`.
You need to reach the top left square marked with the character `'E'`. The rest of the squares are labeled either with a numeric character `1, 2, ..., 9` or with an obstacle `'X'... | null |
Python (Simple DP) | number-of-paths-with-max-score | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** othe... | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
Python | DP | number-of-paths-with-max-score | 0 | 1 | # Complexity\n- Time complexity: O(n^2)\n- Space complexity: O(n^2)\n\n# Code\n```\nclass Solution:\n def pathsWithMaxScore(self, board: List[str]) -> List[int]:\n n, m = len(board), len(board[0])\n\n dp = [[(float(\'-inf\'), 0)] * m for _ in range(n)]\n dp[0][0] = (0, 1)\n\n for i in ran... | 0 | You are given a square `board` of characters. You can move on the board starting at the bottom right square marked with the character `'S'`.
You need to reach the top left square marked with the character `'E'`. The rest of the squares are labeled either with a numeric character `1, 2, ..., 9` or with an obstacle `'X'... | null |
Python | DP | number-of-paths-with-max-score | 0 | 1 | # Complexity\n- Time complexity: O(n^2)\n- Space complexity: O(n^2)\n\n# Code\n```\nclass Solution:\n def pathsWithMaxScore(self, board: List[str]) -> List[int]:\n n, m = len(board), len(board[0])\n\n dp = [[(float(\'-inf\'), 0)] * m for _ in range(n)]\n dp[0][0] = (0, 1)\n\n for i in ran... | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** othe... | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
python, DP, intuitive | number-of-paths-with-max-score | 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:\nstill studying, should be O(n^2)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nfrom functools import cache\nmod = 1000000007\nclass ... | 0 | You are given a square `board` of characters. You can move on the board starting at the bottom right square marked with the character `'S'`.
You need to reach the top left square marked with the character `'E'`. The rest of the squares are labeled either with a numeric character `1, 2, ..., 9` or with an obstacle `'X'... | null |
python, DP, intuitive | number-of-paths-with-max-score | 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:\nstill studying, should be O(n^2)\n\n- Space complexity:\nO(1)\n\n# Code\n```\nfrom functools import cache\nmod = 1000000007\nclass ... | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** othe... | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
DP | 10 liner | Simple | Fast | Python Solution | number-of-paths-with-max-score | 0 | 1 | # Code\n```\nclass Solution:\n def pathsWithMaxScore(self, A):\n n, mod = len(A), 10**9 + 7\n dp = [[[-10**5, 0] for j in range(n + 1)] for i in range(n + 1)]\n dp[n - 1][n - 1] = [0, 1]\n for x in range(n)[::-1]:\n for y in range(n)[::-1]:\n if A[x][y] in \'XS\'... | 0 | You are given a square `board` of characters. You can move on the board starting at the bottom right square marked with the character `'S'`.
You need to reach the top left square marked with the character `'E'`. The rest of the squares are labeled either with a numeric character `1, 2, ..., 9` or with an obstacle `'X'... | null |
DP | 10 liner | Simple | Fast | Python Solution | number-of-paths-with-max-score | 0 | 1 | # Code\n```\nclass Solution:\n def pathsWithMaxScore(self, A):\n n, mod = len(A), 10**9 + 7\n dp = [[[-10**5, 0] for j in range(n + 1)] for i in range(n + 1)]\n dp[n - 1][n - 1] = [0, 1]\n for x in range(n)[::-1]:\n for y in range(n)[::-1]:\n if A[x][y] in \'XS\'... | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** othe... | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
Solution | number-of-paths-with-max-score | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n typedef pair<int, int> pr;\n \n vector<int> pathsWithMaxScore(vector<string>& board) {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n \n char n = board.size();\n \n board[0][0] = \'0\';\n \n pr ... | 0 | You are given a square `board` of characters. You can move on the board starting at the bottom right square marked with the character `'S'`.
You need to reach the top left square marked with the character `'E'`. The rest of the squares are labeled either with a numeric character `1, 2, ..., 9` or with an obstacle `'X'... | null |
Solution | number-of-paths-with-max-score | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n typedef pair<int, int> pr;\n \n vector<int> pathsWithMaxScore(vector<string>& board) {\n ios::sync_with_stdio(false);\n cin.tie(0);\n cout.tie(0);\n \n char n = board.size();\n \n board[0][0] = \'0\';\n \n pr ... | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** othe... | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
Python Bottom-up DP: 87% time, 51% space | number-of-paths-with-max-score | 0 | 1 | ```python []\nclass Solution:\n def pathsWithMaxScore(self, board: List[str]) -> List[int]:\n MOD = 10 ** 9 + 7\n m = len(board)\n n = len(board[0])\n\n dp = [[[0, 0]] * (n + 1) for _ in range(m + 1)]\n dp[1][1] = [0, 1]\n for i in range(m + 1): dp[i][0] = [-math.inf, 0]\n\n... | 0 | You are given a square `board` of characters. You can move on the board starting at the bottom right square marked with the character `'S'`.
You need to reach the top left square marked with the character `'E'`. The rest of the squares are labeled either with a numeric character `1, 2, ..., 9` or with an obstacle `'X'... | null |
Python Bottom-up DP: 87% time, 51% space | number-of-paths-with-max-score | 0 | 1 | ```python []\nclass Solution:\n def pathsWithMaxScore(self, board: List[str]) -> List[int]:\n MOD = 10 ** 9 + 7\n m = len(board)\n n = len(board[0])\n\n dp = [[[0, 0]] * (n + 1) for _ in range(m + 1)]\n dp[1][1] = [0, 1]\n for i in range(m + 1): dp[i][0] = [-math.inf, 0]\n\n... | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** othe... | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
Easy Recursion + Memoization Python Solution | Faster than 97% | number-of-paths-with-max-score | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nMaintain 2 separate states in the DP: Max Score and number of paths with max score\n\n# Complexity\n- Time complexity: $$O(n * m)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n * m)$$\n<!-- Add your space complex... | 0 | You are given a square `board` of characters. You can move on the board starting at the bottom right square marked with the character `'S'`.
You need to reach the top left square marked with the character `'E'`. The rest of the squares are labeled either with a numeric character `1, 2, ..., 9` or with an obstacle `'X'... | null |
Easy Recursion + Memoization Python Solution | Faster than 97% | number-of-paths-with-max-score | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nMaintain 2 separate states in the DP: Max Score and number of paths with max score\n\n# Complexity\n- Time complexity: $$O(n * m)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n * m)$$\n<!-- Add your space complex... | 0 | You are given a string s of length `n` containing only four kinds of characters: `'Q'`, `'W'`, `'E'`, and `'R'`.
A string is said to be **balanced** if each of its characters appears `n / 4` times where `n` is the length of the string.
Return _the minimum length of the substring that can be replaced with **any** othe... | Use dynamic programming to find the path with the max score. Use another dynamic programming array to count the number of paths with max score. |
Easy Python soln | deepest-leaves-sum | 0 | 1 | # Easy python soln\n\n# Code\n```\nclass Solution(object):\n def deepestLeavesSum(self, root):\n if not root: return 0\n h=[0]\n def dfs(root,depth):\n h[0]=max(h[0],depth)\n if root.left: dfs(root.left,depth+1)\n if root.right: dfs(root.right,depth+1)\n d... | 1 | Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes i... | What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest. |
Easy Python soln | deepest-leaves-sum | 0 | 1 | # Easy python soln\n\n# Code\n```\nclass Solution(object):\n def deepestLeavesSum(self, root):\n if not root: return 0\n h=[0]\n def dfs(root,depth):\n h[0]=max(h[0],depth)\n if root.left: dfs(root.left,depth+1)\n if root.right: dfs(root.right,depth+1)\n d... | 1 | Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.`
Return the number of _closed islands_.
**Example 1:**
**Input:** grid = \[\[1,1,1,1,1,1,1,0\],... | Traverse the tree to find the max depth. Traverse the tree again to compute the sum required. |
Deepest leaves sum | deepest-leaves-sum | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | Given the `root` of a binary tree, return _the sum of values of its deepest leaves_.
**Example 1:**
**Input:** root = \[1,2,3,4,5,null,6,7,null,null,null,null,8\]
**Output:** 15
**Example 2:**
**Input:** root = \[6,7,8,2,7,1,3,9,null,1,4,null,null,null,5\]
**Output:** 19
**Constraints:**
* The number of nodes i... | What's the optimal way to delete characters if three or more consecutive characters are equal? If three or more consecutive characters are equal, keep two of them and delete the rest. |
Deepest leaves sum | deepest-leaves-sum | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | Given a 2D `grid` consists of `0s` (land) and `1s` (water). An _island_ is a maximal 4-directionally connected group of `0s` and a _closed island_ is an island **totally** (all left, top, right, bottom) surrounded by `1s.`
Return the number of _closed islands_.
**Example 1:**
**Input:** grid = \[\[1,1,1,1,1,1,1,0\],... | Traverse the tree to find the max depth. Traverse the tree again to compute the sum required. |
Simple solution in Python3 | find-n-unique-integers-sum-up-to-zero | 0 | 1 | # Intuition\nHere we have:\n- `n` as integer\n- and our goal is to create a list of integers, that sum up to `0`\n\nSince we could represent a final answer with **any valid combination** of integers, an algorithm is quite simple:\n- **define** a starting point as `mid = n // 2 or n >> 1`\n- **enumerate** `mid` count of... | 1 | Given an integer `n`, return **any** array containing `n` **unique** integers such that they add up to `0`.
**Example 1:**
**Input:** n = 5
**Output:** \[-7,-1,1,3,4\]
**Explanation:** These arrays also are accepted \[-5,-1,1,2,3\] , \[-3,-1,2,-2,4\].
**Example 2:**
**Input:** n = 3
**Output:** \[-1,0,1\]
**Exampl... | Use a greedy approach. Use the letter with the maximum current limit that can be added without breaking the condition. |
Easy Peasy Python Solution ^_^ | find-n-unique-integers-sum-up-to-zero | 0 | 1 | # Intuition\nHere we get two cases:\nCase 1: \nIf number of elements is odd.\nWe will add a zero at the beginning and rest of the elements will be negative and postive integers of ceiling(n/2).\n\nCase 2:\nIf number of elements is even.\nWe will directly add the elements that will be negative and postive integers of ce... | 5 | Given an integer `n`, return **any** array containing `n` **unique** integers such that they add up to `0`.
**Example 1:**
**Input:** n = 5
**Output:** \[-7,-1,1,3,4\]
**Explanation:** These arrays also are accepted \[-5,-1,1,2,3\] , \[-3,-1,2,-2,4\].
**Example 2:**
**Input:** n = 3
**Output:** \[-1,0,1\]
**Exampl... | Use a greedy approach. Use the letter with the maximum current limit that can be added without breaking the condition. |
Simple solution with Sorting in Python3 | all-elements-in-two-binary-search-trees | 0 | 1 | # Intuition\nThe problem description is the following:\n- there\'re two **Binary Search Trees(BST)** \n- the task is to **merge** their values in **sorted** ascending order and store them to list\n\n# Approach\n1. initialize an empty `nums` list to store the nodes\n2. create function `dfs` to iterate over trees, **the ... | 1 | Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
**Example 2:**
**Input:** root1 = \[1,null,8\], root2 = \[8,1\]
**Output:** \[1,1,8... | How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start... |
All elements in two binary search trees | all-elements-in-two-binary-search-trees | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
**Example 2:**
**Input:** root1 = \[1,null,8\], root2 = \[8,1\]
**Output:** \[1,1,8... | How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start... |
simple iterative solution with simultaneous traversal of both the BSTs | all-elements-in-two-binary-search-trees | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
**Example 2:**
**Input:** root1 = \[1,null,8\], root2 = \[8,1\]
**Output:** \[1,1,8... | How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start... |
✔️ [Python3] 6-LINES (╭ರ_ ⊙ ), Explained | all-elements-in-two-binary-search-trees | 0 | 1 | **UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nThe simplest way to solve this problem is to traverse two trees to form lists with sorted values, and then just merge them. For traversing BST we use recursive in-order DFS. We form sorted lists in descending order a... | 32 | Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
**Example 2:**
**Input:** root1 = \[1,null,8\], root2 = \[8,1\]
**Output:** \[1,1,8... | How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start... |
python3 easy solution 3lines | all-elements-in-two-binary-search-trees | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 1 | Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
**Example 2:**
**Input:** root1 = \[1,null,8\], root2 = \[8,1\]
**Output:** \[1,1,8... | How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start... |
Why is Python generator-based inorder traversal so slow? | all-elements-in-two-binary-search-trees | 0 | 1 | The Python 3 solution below gets TLE for the last test case, both of whose trees are lopsided (each node has at most one child) and consist of 5000 nodes:\n```\nimport heapq\n\nclass Solution:\n def getAllElements(self, root1: TreeNode, root2: TreeNode) -> List[int]:\n def gen(node):\n if node:\n ... | 37 | Given two binary search trees `root1` and `root2`, return _a list containing all the integers from both trees sorted in **ascending** order_.
**Example 1:**
**Input:** root1 = \[2,1,4\], root2 = \[1,0,3\]
**Output:** \[0,1,1,2,3,4\]
**Example 2:**
**Input:** root1 = \[1,null,8\], root2 = \[8,1\]
**Output:** \[1,1,8... | How to solve this problem in quadratic complexity ? For every subarray start at index i, keep finding new maximum values until a value larger than arr[i] is found. Since the limits are high, you need a linear solution. Use a stack to keep the values of the array sorted as you iterate the array from the end to the start... |
Recursion and BFS | jump-game-iii | 0 | 1 | ### BFS\n\n```CPP []\nclass Solution {\npublic:\n bool canReach(vector<int>& arr, int start) \n {\n queue<int> q(deque<int>{start});\n int i = start, n = arr.size(), left_index, right_index;\n\n while(!q.empty() && arr[i] != 0)\n {\n i = q.front(), q.pop();\n left... | 2 | Given an array of non-negative integers `arr`, you are initially positioned at `start` index of the array. When you are at index `i`, you can jump to `i + arr[i]` or `i - arr[i]`, check if you can reach to **any** index with value 0.
Notice that you can not jump outside of the array at any time.
**Example 1:**
**Inp... | Find the minimum absolute difference between two elements in the array. The minimum absolute difference must be a difference between two consecutive elements in the sorted array. |
[Python3] backtracking | verbal-arithmetic-puzzle | 0 | 1 | \n```\nclass Solution:\n def isSolvable(self, words: List[str], result: str) -> bool:\n if max(map(len, words)) > len(result): return False # edge case \n \n words.append(result)\n digits = [0]*10 \n mp = {} # mapping from letter to digit \n \n def fn(i, j, val): \n ... | 7 | Given an equation, represented by `words` on the left side and the `result` on the right side.
You need to check if the equation is solvable under the following rules:
* Each character is decoded as one digit (0 - 9).
* No two characters can map to the same digit.
* Each `words[i]` and `result` are decoded as o... | Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search. Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result. |
Python: Backtracking with Pruning | verbal-arithmetic-puzzle | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given an equation, represented by `words` on the left side and the `result` on the right side.
You need to check if the equation is solvable under the following rules:
* Each character is decoded as one digit (0 - 9).
* No two characters can map to the same digit.
* Each `words[i]` and `result` are decoded as o... | Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search. Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result. |
python solution faster than 98% | verbal-arithmetic-puzzle | 0 | 1 | \n# Approach\n<!-- Describe your approach to solving the problem. -->\nBacktracking\n\n\n# Code\n```\nclass Solution:\n def isSolvable(self, words: List[str], result: str) -> bool:\n head = set()\n num = dict()\n for word in words:\n for i in range(len(word)):\n if i ==... | 0 | Given an equation, represented by `words` on the left side and the `result` on the right side.
You need to check if the equation is solvable under the following rules:
* Each character is decoded as one digit (0 - 9).
* No two characters can map to the same digit.
* Each `words[i]` and `result` are decoded as o... | Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search. Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result. |
Solution | verbal-arithmetic-puzzle | 1 | 1 | ```C++ []\nusing PCI = pair<char, int>;\n\nclass Solution {\nprivate:\n vector<PCI> weight;\n vector<int> suffix_sum_min, suffix_sum_max;\n vector<int> lead_zero;\n bool used[10];\npublic:\n int pow10(int x) {\n int ret = 1;\n for (int i = 0; i < x; ++i) {\n ret *= 10;\n }... | 0 | Given an equation, represented by `words` on the left side and the `result` on the right side.
You need to check if the equation is solvable under the following rules:
* Each character is decoded as one digit (0 - 9).
* No two characters can map to the same digit.
* Each `words[i]` and `result` are decoded as o... | Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search. Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result. |
Fast | Python Solution | verbal-arithmetic-puzzle | 0 | 1 | # Code\n```\nclass Solution:\n def isSolvable(self, words: List[str], result: str) -> bool:\n if max(map(len, words)) > len(result): return False # edge case \n \n words.append(result)\n digits = [0]*10 \n mp = {} # mapping from letter to digit \n \n def fn(i, j, val)... | 0 | Given an equation, represented by `words` on the left side and the `result` on the right side.
You need to check if the equation is solvable under the following rules:
* Each character is decoded as one digit (0 - 9).
* No two characters can map to the same digit.
* Each `words[i]` and `result` are decoded as o... | Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search. Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result. |
Backtracking with Cuts in Python, faster than 85% | verbal-arithmetic-puzzle | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nExploring all the $$N!$$ permutations can be too slow. This solution simulates the additive arithmetic that guesses the value of each alphabet from the least significant column to the most significant column. Of course, the carry should b... | 0 | Given an equation, represented by `words` on the left side and the `result` on the right side.
You need to check if the equation is solvable under the following rules:
* Each character is decoded as one digit (0 - 9).
* No two characters can map to the same digit.
* Each `words[i]` and `result` are decoded as o... | Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search. Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result. |
Similar to Ye15 Solution with more Comments for easier understanding! | verbal-arithmetic-puzzle | 0 | 1 | # Code\n```python []\nclass Solution:\n def isSolvable(self, words: List[str], result: str) -> bool:\n if max(map(len, words)) > len(result): # If any of the words are bigger than the result, it will be impossible to solve\n return False\n # Add the result to the list, this way we will only ... | 1 | Given an equation, represented by `words` on the left side and the `result` on the right side.
You need to check if the equation is solvable under the following rules:
* Each character is decoded as one digit (0 - 9).
* No two characters can map to the same digit.
* Each `words[i]` and `result` are decoded as o... | Write a function f(k) to determine how many ugly numbers smaller than k. As f(k) is non-decreasing, try binary search. Find all ugly numbers in [1, LCM(a, b, c)] (LCM is Least Common Multiple). Use inclusion-exclusion principle to expand the result. |
Python Soln | Best for Interview | decrypt-string-from-alphabet-to-integer-mapping | 0 | 1 | 1. Starting from `i=0`, check if `s[i+2]==\'#\'`\n2. If yes, then `s[i: i+2]` is a character\n3. Else, `s[i]` is a character\n```\ndef freqAlphabets(self, s: str) -> str:\n\tres = []\n\ti = 0\n\n\twhile i < len(s):\n\t\tif i + 2 < len(s) and s[i + 2] == \'#\':\n\t\t\tval = int(s[i: i + 2])\n\t\t\tres.append(chr(val + 9... | 68 | You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows:
* Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively.
* Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively.
Return _the string formed after ... | Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items. |
Python Soln | Best for Interview | decrypt-string-from-alphabet-to-integer-mapping | 0 | 1 | 1. Starting from `i=0`, check if `s[i+2]==\'#\'`\n2. If yes, then `s[i: i+2]` is a character\n3. Else, `s[i]` is a character\n```\ndef freqAlphabets(self, s: str) -> str:\n\tres = []\n\ti = 0\n\n\twhile i < len(s):\n\t\tif i + 2 < len(s) and s[i + 2] == \'#\':\n\t\t\tval = int(s[i: i + 2])\n\t\t\tres.append(chr(val + 9... | 68 | There are `n` people and `40` types of hats labeled from `1` to `40`.
Given a 2D integer array `hats`, where `hats[i]` is a list of all hats preferred by the `ith` person.
Return _the number of ways that the `n` people wear different hats to each other_.
Since the answer may be too large, return it modulo `109 + 7`.... | Scan from right to left, in each step of the scanning check whether there is a trailing "#" 2 indexes away. |
Python 3 (two lines) (beats 100%) (16 ms) (With Explanation) | decrypt-string-from-alphabet-to-integer-mapping | 0 | 1 | - Start from letter z (two digit numbers) and work backwords to avoid any confusion or inteference with one digit numbers. After replacing all two digit (hashtag based) numbers, we know that the remaining numbers will be simple one digit replacements.\n- Note that ord(\'a\') is 97 which means that chr(97) is \'a\'. Thi... | 138 | You are given a string `s` formed by digits and `'#'`. We want to map `s` to English lowercase characters as follows:
* Characters (`'a'` to `'i'`) are represented by (`'1'` to `'9'`) respectively.
* Characters (`'j'` to `'z'`) are represented by (`'10#'` to `'26#'`) respectively.
Return _the string formed after ... | Think of it as a graph problem. We need to find a topological order on the dependency graph. Build two graphs, one for the groups and another for the items. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.