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
Beat 94% in python
magic-squares-in-grid
0
1
# Idea\n- center has to be 5\n- check each number is there exact once\n- check row & col & diagonals\n\n# Code\n```\nclass Solution:\n def numMagicSquaresInside(self, grid: List[List[int]]) -> int:\n def checkMagic3x3(centerRow: int, centerCol: int) -> bool:\n # center one has to be 5 to make it ma...
0
A `3 x 3` magic square is a `3 x 3` grid filled with distinct numbers **from** `1` **to** `9` such that each row, column, and both diagonals all have the same sum. Given a `row x col` `grid` of integers, how many `3 x 3` "magic square " subgrids are there? (Each subgrid is contiguous). **Example 1:** **Input:** grid...
null
Beat 94% in python
magic-squares-in-grid
0
1
# Idea\n- center has to be 5\n- check each number is there exact once\n- check row & col & diagonals\n\n# Code\n```\nclass Solution:\n def numMagicSquaresInside(self, grid: List[List[int]]) -> int:\n def checkMagic3x3(centerRow: int, centerCol: int) -> bool:\n # center one has to be 5 to make it ma...
0
You are given two integer arrays `nums1` and `nums2` both of the same length. The **advantage** of `nums1` with respect to `nums2` is the number of indices `i` for which `nums1[i] > nums2[i]`. Return _any permutation of_ `nums1` _that maximizes its **advantage** with respect to_ `nums2`. **Example 1:** **Input:** nu...
null
Simple solution
magic-squares-in-grid
0
1
```\nclass Solution:\n def numMagicSquaresInside(self, grid: List[List[int]]) -> int:\n cnt = 0\n direct = [[(-1,0), (0,0), (1,0)], [(-1,-1), (0,-1), (1,-1)], [(-1,1), (0,1), (1,1)], [(0,-1), (0,0), (0,1)], [(-1,-1), (-1,0), (-1,1)], [(1,-1), (1,0), (1,1)], [(-1,-1), (0,0), (1,1)], [(1,-1), (0,0), (-1,...
0
A `3 x 3` magic square is a `3 x 3` grid filled with distinct numbers **from** `1` **to** `9` such that each row, column, and both diagonals all have the same sum. Given a `row x col` `grid` of integers, how many `3 x 3` "magic square " subgrids are there? (Each subgrid is contiguous). **Example 1:** **Input:** grid...
null
Simple solution
magic-squares-in-grid
0
1
```\nclass Solution:\n def numMagicSquaresInside(self, grid: List[List[int]]) -> int:\n cnt = 0\n direct = [[(-1,0), (0,0), (1,0)], [(-1,-1), (0,-1), (1,-1)], [(-1,1), (0,1), (1,1)], [(0,-1), (0,0), (0,1)], [(-1,-1), (-1,0), (-1,1)], [(1,-1), (1,0), (1,1)], [(-1,-1), (0,0), (1,1)], [(1,-1), (0,0), (-1,...
0
You are given two integer arrays `nums1` and `nums2` both of the same length. The **advantage** of `nums1` with respect to `nums2` is the number of indices `i` for which `nums1[i] > nums2[i]`. Return _any permutation of_ `nums1` _that maximizes its **advantage** with respect to_ `nums2`. **Example 1:** **Input:** nu...
null
Python3, intuitive but not most optimal -- beats 82.52% runtime and 85.44% memory
magic-squares-in-grid
0
1
# Intuition\nSlice down grid into 3x3 sub-grids and calculate sums for each:\n- rows\n- columns\n- diagonals\n\n# Approach\n1. Figure out row and column index range (i.e. highest value when slicing to 3x3 sub-grids)\n2. For each row index and column index in respective index_range\n2.1 calculate `expected_sum` (to be u...
0
A `3 x 3` magic square is a `3 x 3` grid filled with distinct numbers **from** `1` **to** `9` such that each row, column, and both diagonals all have the same sum. Given a `row x col` `grid` of integers, how many `3 x 3` "magic square " subgrids are there? (Each subgrid is contiguous). **Example 1:** **Input:** grid...
null
Python3, intuitive but not most optimal -- beats 82.52% runtime and 85.44% memory
magic-squares-in-grid
0
1
# Intuition\nSlice down grid into 3x3 sub-grids and calculate sums for each:\n- rows\n- columns\n- diagonals\n\n# Approach\n1. Figure out row and column index range (i.e. highest value when slicing to 3x3 sub-grids)\n2. For each row index and column index in respective index_range\n2.1 calculate `expected_sum` (to be u...
0
You are given two integer arrays `nums1` and `nums2` both of the same length. The **advantage** of `nums1` with respect to `nums2` is the number of indices `i` for which `nums1[i] > nums2[i]`. Return _any permutation of_ `nums1` _that maximizes its **advantage** with respect to_ `nums2`. **Example 1:** **Input:** nu...
null
Python Medium
magic-squares-in-grid
0
1
```\nclass Solution:\n def numMagicSquaresInside(self, grid: List[List[int]]) -> int:\n M, N = len(grid), len(grid[0])\n res = 0\n\n solution = [((2, 7, 6), (4, 3, 8), (9, 5, 1)), ((3, 5, 7), (4, 9, 2), (8, 1, 6)), ((1, 5, 9), (6, 7, 2), (8, 3, 4)), ((1, 8, 6), (5, 3, 7), (9, 4, 2)), ((2, 9, 4),...
0
A `3 x 3` magic square is a `3 x 3` grid filled with distinct numbers **from** `1` **to** `9` such that each row, column, and both diagonals all have the same sum. Given a `row x col` `grid` of integers, how many `3 x 3` "magic square " subgrids are there? (Each subgrid is contiguous). **Example 1:** **Input:** grid...
null
Python Medium
magic-squares-in-grid
0
1
```\nclass Solution:\n def numMagicSquaresInside(self, grid: List[List[int]]) -> int:\n M, N = len(grid), len(grid[0])\n res = 0\n\n solution = [((2, 7, 6), (4, 3, 8), (9, 5, 1)), ((3, 5, 7), (4, 9, 2), (8, 1, 6)), ((1, 5, 9), (6, 7, 2), (8, 3, 4)), ((1, 8, 6), (5, 3, 7), (9, 4, 2)), ((2, 9, 4),...
0
You are given two integer arrays `nums1` and `nums2` both of the same length. The **advantage** of `nums1` with respect to `nums2` is the number of indices `i` for which `nums1[i] > nums2[i]`. Return _any permutation of_ `nums1` _that maximizes its **advantage** with respect to_ `nums2`. **Example 1:** **Input:** nu...
null
Beats 92% of runtime !!! Detailed explanation 👨‍💻
magic-squares-in-grid
0
1
\n# Approach\nWe divide the requirements and implement functions for each requirement. This way, it\'s easier to debug the code and also know what\'s happening at every step. From the problem, it can be seen that a 3*3 grid is classified as a magic square if:\n - all rows are equal\n - all columns are equal \n ...
0
A `3 x 3` magic square is a `3 x 3` grid filled with distinct numbers **from** `1` **to** `9` such that each row, column, and both diagonals all have the same sum. Given a `row x col` `grid` of integers, how many `3 x 3` "magic square " subgrids are there? (Each subgrid is contiguous). **Example 1:** **Input:** grid...
null
Beats 92% of runtime !!! Detailed explanation 👨‍💻
magic-squares-in-grid
0
1
\n# Approach\nWe divide the requirements and implement functions for each requirement. This way, it\'s easier to debug the code and also know what\'s happening at every step. From the problem, it can be seen that a 3*3 grid is classified as a magic square if:\n - all rows are equal\n - all columns are equal \n ...
0
You are given two integer arrays `nums1` and `nums2` both of the same length. The **advantage** of `nums1` with respect to `nums2` is the number of indices `i` for which `nums1[i] > nums2[i]`. Return _any permutation of_ `nums1` _that maximizes its **advantage** with respect to_ `nums2`. **Example 1:** **Input:** nu...
null
Set theory and Memo's | 100% Time and Space Complexity on Average | Commented and Explained
magic-squares-in-grid
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere are only so many magic and non-magic squares we may encounter (though the latter is quite great!). Based on this, we can utilize memoization to speed up a set based approach to our problem. \n\nTo start, notice that we can use the o...
0
A `3 x 3` magic square is a `3 x 3` grid filled with distinct numbers **from** `1` **to** `9` such that each row, column, and both diagonals all have the same sum. Given a `row x col` `grid` of integers, how many `3 x 3` "magic square " subgrids are there? (Each subgrid is contiguous). **Example 1:** **Input:** grid...
null
Set theory and Memo's | 100% Time and Space Complexity on Average | Commented and Explained
magic-squares-in-grid
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThere are only so many magic and non-magic squares we may encounter (though the latter is quite great!). Based on this, we can utilize memoization to speed up a set based approach to our problem. \n\nTo start, notice that we can use the o...
0
You are given two integer arrays `nums1` and `nums2` both of the same length. The **advantage** of `nums1` with respect to `nums2` is the number of indices `i` for which `nums1[i] > nums2[i]`. Return _any permutation of_ `nums1` _that maximizes its **advantage** with respect to_ `nums2`. **Example 1:** **Input:** nu...
null
Very easy to understand | python
keys-and-rooms
0
1
```\nclass Solution:\n def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:\n n = len(rooms)\n keys = set()\n keys.add(0)\n k = 1\n while k!=0:\n k=len(keys)\n for i in range(n):\n if i in keys:\n keys.update(rooms[i])\...
1
There are `n` rooms labeled from `0` to `n - 1` and all the rooms are locked except for room `0`. Your goal is to visit all the rooms. However, you cannot enter a locked room without having its key. When you visit a room, you may find a set of **distinct keys** in it. Each key has a number on it, denoting which room i...
null
Very easy to understand | python
keys-and-rooms
0
1
```\nclass Solution:\n def canVisitAllRooms(self, rooms: List[List[int]]) -> bool:\n n = len(rooms)\n keys = set()\n keys.add(0)\n k = 1\n while k!=0:\n k=len(keys)\n for i in range(n):\n if i in keys:\n keys.update(rooms[i])\...
1
A car travels from a starting position to a destination which is `target` miles east of the starting position. There are gas stations along the way. The gas stations are represented as an array `stations` where `stations[i] = [positioni, fueli]` indicates that the `ith` gas station is `positioni` miles east of the sta...
null
Solution
split-array-into-fibonacci-sequence
1
1
```C++ []\nclass Solution {\npublic:\n bool helper(int ind,vector<int>& ds,string &numStr){\n if(ind==numStr.size() && ds.size()>2){\n return true;\n }\n for(int i=1;i<=10 && ind+i<=numStr.size() ;i++){\n string temp=numStr.substr(ind,i);\n long long num=stoll(te...
1
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Solution
split-array-into-fibonacci-sequence
1
1
```C++ []\nclass Solution {\npublic:\n bool helper(int ind,vector<int>& ds,string &numStr){\n if(ind==numStr.size() && ds.size()>2){\n return true;\n }\n for(int i=1;i<=10 && ind+i<=numStr.size() ;i++){\n string temp=numStr.substr(ind,i);\n long long num=stoll(te...
1
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._ For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`. Two binary trees are considered _leaf-similar_ if their leaf value sequence is the same. Return `true` i...
null
python3 clean easy understand code
split-array-into-fibonacci-sequence
0
1
# Intuition\n\nBacktracking\n\n# Approach\n\n\n\n# Code\n```\nclass Solution:\n def splitIntoFibonacci(self, num: str) -> List[int]:\n size = len(num)\n self.result = None\n\n def dfs(start, path):\n if len(path) > 2 and path[-3] + path[-2] != path[-1]:\n return False\n...
1
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
python3 clean easy understand code
split-array-into-fibonacci-sequence
0
1
# Intuition\n\nBacktracking\n\n# Approach\n\n\n\n# Code\n```\nclass Solution:\n def splitIntoFibonacci(self, num: str) -> List[int]:\n size = len(num)\n self.result = None\n\n def dfs(start, path):\n if len(path) > 2 and path[-3] + path[-2] != path[-1]:\n return False\n...
1
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._ For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`. Two binary trees are considered _leaf-similar_ if their leaf value sequence is the same. Return `true` i...
null
Backtracking (R-94%+, M-87%+)
split-array-into-fibonacci-sequence
0
1
# Complexity\n- Time complexity: **O(n * n)**\nn - len of input string.\n\n- Space complexity: **O(n)**\nWorst case: all string values are 0, output list will have the same size as input string.\n\n# Code\n```\nclass Solution:\n def splitIntoFibonacci(self, num: str) -> List[int]:\n # We can\'t build anything...
1
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Backtracking (R-94%+, M-87%+)
split-array-into-fibonacci-sequence
0
1
# Complexity\n- Time complexity: **O(n * n)**\nn - len of input string.\n\n- Space complexity: **O(n)**\nWorst case: all string values are 0, output list will have the same size as input string.\n\n# Code\n```\nclass Solution:\n def splitIntoFibonacci(self, num: str) -> List[int]:\n # We can\'t build anything...
1
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._ For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`. Two binary trees are considered _leaf-similar_ if their leaf value sequence is the same. Return `true` i...
null
Easiest Solution
split-array-into-fibonacci-sequence
1
1
\n\n# Code\n```java []\nclass Solution {\n public List<Integer> splitIntoFibonacci(String num) {\n List<Integer> list = new ArrayList<>();\n helper(num, list, 0);\n return list;\n }\n\n public boolean helper(String str, List<Integer>list, int idx){\n if(idx == str.length()) return l...
0
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Easiest Solution
split-array-into-fibonacci-sequence
1
1
\n\n# Code\n```java []\nclass Solution {\n public List<Integer> splitIntoFibonacci(String num) {\n List<Integer> list = new ArrayList<>();\n helper(num, list, 0);\n return list;\n }\n\n public boolean helper(String str, List<Integer>list, int idx){\n if(idx == str.length()) return l...
0
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._ For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`. Two binary trees are considered _leaf-similar_ if their leaf value sequence is the same. Return `true` i...
null
Non-Backtracking Iterative solution, O(N^3)
split-array-into-fibonacci-sequence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nIf we choose a partition for the first two numbers, we can uniquely derive what the rest of the sequence would look like.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nChoose indices $i, j$ so that the first ...
0
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Non-Backtracking Iterative solution, O(N^3)
split-array-into-fibonacci-sequence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nIf we choose a partition for the first two numbers, we can uniquely derive what the rest of the sequence would look like.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\nChoose indices $i, j$ so that the first ...
0
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._ For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`. Two binary trees are considered _leaf-similar_ if their leaf value sequence is the same. Return `true` i...
null
Backtracking - A clean and organized Python solution
split-array-into-fibonacci-sequence
0
1
# Intuition\nWe iterate over the search space using DFS. When we reach an invalid fibonacci index, we backtrack and continue searching.\n\n# Approach\nBacktracking\n\n# Complexity\n- Time complexity:\n?\n\n- Space complexity:\nO(n) - Just need to maintain the output array.\n\n# Code\n```\nclass Solution:\n \n def...
0
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Backtracking - A clean and organized Python solution
split-array-into-fibonacci-sequence
0
1
# Intuition\nWe iterate over the search space using DFS. When we reach an invalid fibonacci index, we backtrack and continue searching.\n\n# Approach\nBacktracking\n\n# Complexity\n- Time complexity:\n?\n\n- Space complexity:\nO(n) - Just need to maintain the output array.\n\n# Code\n```\nclass Solution:\n \n def...
0
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._ For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`. Two binary trees are considered _leaf-similar_ if their leaf value sequence is the same. Return `true` i...
null
Very easy to understand
split-array-into-fibonacci-sequence
0
1
\n# Approach\nBacktracking\n\n# Code\n```\nclass Solution:\n def splitIntoFibonacci(self, num: str) -> List[int]:\n \n n = len(num)\n res = []\n\n def backtrack(pos):\n\n if pos == n:\n if len(res) > 2 and res[-1] == res[-2] + res[-3]:\n return...
0
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Very easy to understand
split-array-into-fibonacci-sequence
0
1
\n# Approach\nBacktracking\n\n# Code\n```\nclass Solution:\n def splitIntoFibonacci(self, num: str) -> List[int]:\n \n n = len(num)\n res = []\n\n def backtrack(pos):\n\n if pos == n:\n if len(res) > 2 and res[-1] == res[-2] + res[-3]:\n return...
0
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._ For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`. Two binary trees are considered _leaf-similar_ if their leaf value sequence is the same. Return `true` i...
null
Python3 - Brute Force With Many Edge Cases
split-array-into-fibonacci-sequence
0
1
# Intuition\nWhat an interesting problem\n\n# Code\n```\nclass Solution:\n def splitIntoFibonacci(self, num: str) -> List[int]:\n c = Counter(num)\n mv = (2**31) - 1\n if c[\'0\'] == len(num):\n return [0] * len(num) # special case\n n = len(num)\n for i in range(1, 1 +...
0
You are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Python3 - Brute Force With Many Edge Cases
split-array-into-fibonacci-sequence
0
1
# Intuition\nWhat an interesting problem\n\n# Code\n```\nclass Solution:\n def splitIntoFibonacci(self, num: str) -> List[int]:\n c = Counter(num)\n mv = (2**31) - 1\n if c[\'0\'] == len(num):\n return [0] * len(num) # special case\n n = len(num)\n for i in range(1, 1 +...
0
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._ For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`. Two binary trees are considered _leaf-similar_ if their leaf value sequence is the same. Return `true` i...
null
Python (Simple Backtracking)
split-array-into-fibonacci-sequence
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 are given a string of digits `num`, such as `"123456579 "`. We can split it into a Fibonacci-like sequence `[123, 456, 579]`. Formally, a **Fibonacci-like** sequence is a list `f` of non-negative integers such that: * `0 <= f[i] < 231`, (that is, each integer fits in a **32-bit** signed integer type), * `f.le...
null
Python (Simple Backtracking)
split-array-into-fibonacci-sequence
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
Consider all the leaves of a binary tree, from left to right order, the values of those leaves form a **leaf value sequence**_._ For example, in the given tree above, the leaf value sequence is `(6, 7, 4, 9, 8)`. Two binary trees are considered _leaf-similar_ if their leaf value sequence is the same. Return `true` i...
null
Python - Beats 99%
guess-the-word
0
1
I think this "interactive" problem may be over my head, but I found a lot of other solutions poorly explained or too theoretical, so here\'s my take.\n\nObservations:\n1) If `master.guess(guess_word)` returns 0 matches then any other word in `wordlist`that matches even 1 character with `guess_word` can be eliminated.\n...
46
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: ...
null
Python - Beats 99%
guess-the-word
0
1
I think this "interactive" problem may be over my head, but I found a lot of other solutions poorly explained or too theoretical, so here\'s my take.\n\nObservations:\n1) If `master.guess(guess_word)` returns 0 matches then any other word in `wordlist`that matches even 1 character with `guess_word` can be eliminated.\n...
46
A sequence `x1, x2, ..., xn` is _Fibonacci-like_ if: * `n >= 3` * `xi + xi+1 == xi+2` for all `i + 2 <= n` Given a **strictly increasing** array `arr` of positive integers forming a sequence, return _the **length** of the longest Fibonacci-like subsequence of_ `arr`. If one does not exist, return `0`. A **subseq...
null
[Python] Solution with narrowed candidates and blacklist
guess-the-word
0
1
*Runtime: 48 ms, faster than 63.16% of Python3 online submissions for Guess the Word.\nMemory Usage: 14 MB, less than 62.02% of Python3 online submissions for Guess the Word.*\n\n1. Narrow the candidates as @qy9Mg did in [How to explain to interviewer - 843. Guess the Word](http://leetcode.com/problems/guess-the-word/d...
2
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: ...
null
[Python] Solution with narrowed candidates and blacklist
guess-the-word
0
1
*Runtime: 48 ms, faster than 63.16% of Python3 online submissions for Guess the Word.\nMemory Usage: 14 MB, less than 62.02% of Python3 online submissions for Guess the Word.*\n\n1. Narrow the candidates as @qy9Mg did in [How to explain to interviewer - 843. Guess the Word](http://leetcode.com/problems/guess-the-word/d...
2
A sequence `x1, x2, ..., xn` is _Fibonacci-like_ if: * `n >= 3` * `xi + xi+1 == xi+2` for all `i + 2 <= n` Given a **strictly increasing** array `arr` of positive integers forming a sequence, return _the **length** of the longest Fibonacci-like subsequence of_ `arr`. If one does not exist, return `0`. A **subseq...
null
Solution
guess-the-word
1
1
```C++ []\nclass Solution {\npublic:\n int StringConstrain(const string& a, const string& b){\n int equals = 0;\n for (int i = 0 ; 6 > i ; i++){\n if (a[i] == b[i]){\n equals++;\n }\n }\n return equals;\n }\n void After_Compute(vector<string>& wo...
2
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: ...
null
Solution
guess-the-word
1
1
```C++ []\nclass Solution {\npublic:\n int StringConstrain(const string& a, const string& b){\n int equals = 0;\n for (int i = 0 ; 6 > i ; i++){\n if (a[i] == b[i]){\n equals++;\n }\n }\n return equals;\n }\n void After_Compute(vector<string>& wo...
2
A sequence `x1, x2, ..., xn` is _Fibonacci-like_ if: * `n >= 3` * `xi + xi+1 == xi+2` for all `i + 2 <= n` Given a **strictly increasing** array `arr` of positive integers forming a sequence, return _the **length** of the longest Fibonacci-like subsequence of_ `arr`. If one does not exist, return `0`. A **subseq...
null
Reduce by Hamming distance. 28 ms, faster than 91.22% & 14.2 MB, less than 92.67%. Python 3.
guess-the-word
0
1
```\nclass Solution:\n def findSecretWord(self, wordlist: List[str], master: \'Master\') -> None:\n def hamming_distance(w1: str, w2: str) -> int:\n return sum(1 for k in range(6) if w1[k] != w2[k])\n\n current_guess = wordlist[0]\n curr_distance = 6 - Master.guess(master, current_gue...
2
You are given an array of unique strings `words` where `words[i]` is six letters long. One word of `words` was chosen as a secret word. You are also given the helper object `Master`. You may call `Master.guess(word)` where `word` is a six-letter-long string, and it must be from `words`. `Master.guess(word)` returns: ...
null
Reduce by Hamming distance. 28 ms, faster than 91.22% & 14.2 MB, less than 92.67%. Python 3.
guess-the-word
0
1
```\nclass Solution:\n def findSecretWord(self, wordlist: List[str], master: \'Master\') -> None:\n def hamming_distance(w1: str, w2: str) -> int:\n return sum(1 for k in range(6) if w1[k] != w2[k])\n\n current_guess = wordlist[0]\n curr_distance = 6 - Master.guess(master, current_gue...
2
A sequence `x1, x2, ..., xn` is _Fibonacci-like_ if: * `n >= 3` * `xi + xi+1 == xi+2` for all `i + 2 <= n` Given a **strictly increasing** array `arr` of positive integers forming a sequence, return _the **length** of the longest Fibonacci-like subsequence of_ `arr`. If one does not exist, return `0`. A **subseq...
null
✅Easy Solution using Stack Beats(90%) in O(N)✅
backspace-string-compare
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 two strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character. Note that after backspacing an empty text, the text will continue empty. **Example 1:** **Input:** s = "ab#c ", t = "ad#c " **Output:** true **Explanation:** Both s and t...
null
✅Easy Solution using Stack Beats(90%) in O(N)✅
backspace-string-compare
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`: * `-2`: Turn left `90` degrees. * `-1`: Turn right `90` degrees. * `1 <= k <= 9`: Move forward `k` units, one unit at a time. Some of the grid squares are `obstacl...
null
ONE LINER PYTHON3 TRIVIAL / GOLF ✅ ✅ ✅
backspace-string-compare
0
1
No explanation needed (trivial)\n\n# Code\n```\nclass Solution:\n def backspaceCompare(self, s: str, t: str) -> bool:\n return [(z.append(c) or z) for z in [[]] for i, c in enumerate(s) if c != \'#\' or (i != 0 and (c == \'#\' and z and not z.pop()))][0] == [(z.append(c) or z) for z in [[]] for i, c in enumer...
1
Given two strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character. Note that after backspacing an empty text, the text will continue empty. **Example 1:** **Input:** s = "ab#c ", t = "ad#c " **Output:** true **Explanation:** Both s and t...
null
ONE LINER PYTHON3 TRIVIAL / GOLF ✅ ✅ ✅
backspace-string-compare
0
1
No explanation needed (trivial)\n\n# Code\n```\nclass Solution:\n def backspaceCompare(self, s: str, t: str) -> bool:\n return [(z.append(c) or z) for z in [[]] for i, c in enumerate(s) if c != \'#\' or (i != 0 and (c == \'#\' and z and not z.pop()))][0] == [(z.append(c) or z) for z in [[]] for i, c in enumer...
1
A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`: * `-2`: Turn left `90` degrees. * `-1`: Turn right `90` degrees. * `1 <= k <= 9`: Move forward `k` units, one unit at a time. Some of the grid squares are `obstacl...
null
Video Solution | Explanation With Drawings | Java | C++ | Python 3
backspace-string-compare
1
1
# Intuition, approach, and complexity dicussed in detail in video solution\nhttps://youtu.be/UcRBFkfKK6w\n\n# Code\nC++\n```\n//TC : O(n)\n//SC : O(1)\nclass Solution {\npublic:\n bool backspaceCompare(string s, string t) {\n int szS = s.size(), szT = t.size();\n string sNew = findFinalString(s);\n ...
1
Given two strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character. Note that after backspacing an empty text, the text will continue empty. **Example 1:** **Input:** s = "ab#c ", t = "ad#c " **Output:** true **Explanation:** Both s and t...
null
Video Solution | Explanation With Drawings | Java | C++ | Python 3
backspace-string-compare
1
1
# Intuition, approach, and complexity dicussed in detail in video solution\nhttps://youtu.be/UcRBFkfKK6w\n\n# Code\nC++\n```\n//TC : O(n)\n//SC : O(1)\nclass Solution {\npublic:\n bool backspaceCompare(string s, string t) {\n int szS = s.size(), szT = t.size();\n string sNew = findFinalString(s);\n ...
1
A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`: * `-2`: Turn left `90` degrees. * `-1`: Turn right `90` degrees. * `1 <= k <= 9`: Move forward `k` units, one unit at a time. Some of the grid squares are `obstacl...
null
【Video】Give me 10 minutes - How we think about a solution - Python, JavaScript, Java, C++
backspace-string-compare
1
1
# Intuition\nUsing stack or pointers\n\n---\n\n# Solution Video\n\nhttps://youtu.be/YBt2dPL6z5o\n\n\u203B I put my son on my lap and recorded a video, so I\'m feeling a little rushed. lol Please leave a comment if you have any questions.\n\n\u25A0 Timeline of the video\n`0:04` Stack solution code\n`0:23` Explain key po...
59
Given two strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character. Note that after backspacing an empty text, the text will continue empty. **Example 1:** **Input:** s = "ab#c ", t = "ad#c " **Output:** true **Explanation:** Both s and t...
null
【Video】Give me 10 minutes - How we think about a solution - Python, JavaScript, Java, C++
backspace-string-compare
1
1
# Intuition\nUsing stack or pointers\n\n---\n\n# Solution Video\n\nhttps://youtu.be/YBt2dPL6z5o\n\n\u203B I put my son on my lap and recorded a video, so I\'m feeling a little rushed. lol Please leave a comment if you have any questions.\n\n\u25A0 Timeline of the video\n`0:04` Stack solution code\n`0:23` Explain key po...
59
A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`: * `-2`: Turn left `90` degrees. * `-1`: Turn right `90` degrees. * `1 <= k <= 9`: Move forward `k` units, one unit at a time. Some of the grid squares are `obstacl...
null
Intuitive Approach Using Counting. Linear time & Constant Space.
backspace-string-compare
0
1
# Approach\n\nFor both s & t (string1 & string2 in my code)\n- Simply maintain the skip (count of # in a string).\n- Iterate from reverse,\n - If found #, increment skip and continue\n - If char is valid alpha but skip > 0: decrease skip and continue\n - If char is valid and skip == 0: do nothing\n- Do the abo...
1
Given two strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character. Note that after backspacing an empty text, the text will continue empty. **Example 1:** **Input:** s = "ab#c ", t = "ad#c " **Output:** true **Explanation:** Both s and t...
null
Intuitive Approach Using Counting. Linear time & Constant Space.
backspace-string-compare
0
1
# Approach\n\nFor both s & t (string1 & string2 in my code)\n- Simply maintain the skip (count of # in a string).\n- Iterate from reverse,\n - If found #, increment skip and continue\n - If char is valid alpha but skip > 0: decrease skip and continue\n - If char is valid and skip == 0: do nothing\n- Do the abo...
1
A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`: * `-2`: Turn left `90` degrees. * `-1`: Turn right `90` degrees. * `1 <= k <= 9`: Move forward `k` units, one unit at a time. Some of the grid squares are `obstacl...
null
Backspace String Compare
backspace-string-compare
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 strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character. Note that after backspacing an empty text, the text will continue empty. **Example 1:** **Input:** s = "ab#c ", t = "ad#c " **Output:** true **Explanation:** Both s and t...
null
Backspace String Compare
backspace-string-compare
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`: * `-2`: Turn left `90` degrees. * `-1`: Turn right `90` degrees. * `1 <= k <= 9`: Move forward `k` units, one unit at a time. Some of the grid squares are `obstacl...
null
🔥REAL O(1) space and O(n) time 🔥 JAVA 🔥PYTHON
backspace-string-compare
1
1
# Intuition\nWe will not use any additional structures to fit in memory. Only primitives, only hardcore.\n\n# Approach\n**Step 1**\nFirst of all, we count the number of characters not deleted after formatting in the strings S and T.\n```java []\npublic static int countRealSymbol(String s){\n int counter = 0;\n ...
1
Given two strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character. Note that after backspacing an empty text, the text will continue empty. **Example 1:** **Input:** s = "ab#c ", t = "ad#c " **Output:** true **Explanation:** Both s and t...
null
🔥REAL O(1) space and O(n) time 🔥 JAVA 🔥PYTHON
backspace-string-compare
1
1
# Intuition\nWe will not use any additional structures to fit in memory. Only primitives, only hardcore.\n\n# Approach\n**Step 1**\nFirst of all, we count the number of characters not deleted after formatting in the strings S and T.\n```java []\npublic static int countRealSymbol(String s){\n int counter = 0;\n ...
1
A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`: * `-2`: Turn left `90` degrees. * `-1`: Turn right `90` degrees. * `1 <= k <= 9`: Move forward `k` units, one unit at a time. Some of the grid squares are `obstacl...
null
Shortest, Fastest Solution, using regex 🔥 99%
backspace-string-compare
0
1
\n# Approach\n- We process both **input strings** using the `solve()` function, which efficiently handles backspaces using **regular expressions**. Then, we compare the processed strings to check for equality.\n# Complexity\n- Time complexity: $$O(max(n, m))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n-...
1
Given two strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character. Note that after backspacing an empty text, the text will continue empty. **Example 1:** **Input:** s = "ab#c ", t = "ad#c " **Output:** true **Explanation:** Both s and t...
null
Shortest, Fastest Solution, using regex 🔥 99%
backspace-string-compare
0
1
\n# Approach\n- We process both **input strings** using the `solve()` function, which efficiently handles backspaces using **regular expressions**. Then, we compare the processed strings to check for equality.\n# Complexity\n- Time complexity: $$O(max(n, m))$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n-...
1
A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`: * `-2`: Turn left `90` degrees. * `-1`: Turn right `90` degrees. * `1 <= k <= 9`: Move forward `k` units, one unit at a time. Some of the grid squares are `obstacl...
null
🔥An Original in 🐍 || Beats 83% || Brute-Force🔥
backspace-string-compare
0
1
![image.png](https://assets.leetcode.com/users/images/ae169d26-738a-4f06-a65f-ef05be08cf0b_1697695438.8865297.png)\n\n\n# Code\n```\nclass Solution:\n def backspaceCompare(self, s: str, t: str) -> bool:\n def rem_(st: str):\n while \'#\' in st:\n a = st.index(\'#\')\n ...
1
Given two strings `s` and `t`, return `true` _if they are equal when both are typed into empty text editors_. `'#'` means a backspace character. Note that after backspacing an empty text, the text will continue empty. **Example 1:** **Input:** s = "ab#c ", t = "ad#c " **Output:** true **Explanation:** Both s and t...
null
🔥An Original in 🐍 || Beats 83% || Brute-Force🔥
backspace-string-compare
0
1
![image.png](https://assets.leetcode.com/users/images/ae169d26-738a-4f06-a65f-ef05be08cf0b_1697695438.8865297.png)\n\n\n# Code\n```\nclass Solution:\n def backspaceCompare(self, s: str, t: str) -> bool:\n def rem_(st: str):\n while \'#\' in st:\n a = st.index(\'#\')\n ...
1
A robot on an infinite XY-plane starts at point `(0, 0)` facing north. The robot can receive a sequence of these three possible types of `commands`: * `-2`: Turn left `90` degrees. * `-1`: Turn right `90` degrees. * `1 <= k <= 9`: Move forward `k` units, one unit at a time. Some of the grid squares are `obstacl...
null
Two Python Solution with O(n) time + O(n) space and second with O(1) space
longest-mountain-in-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some index `i` (**0-indexed**) 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]` Given an integer arr...
null
Two Python Solution with O(n) time + O(n) space and second with O(1) space
longest-mountain-in-array
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours. Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k...
null
[Python 3] Explained Solution (video + code)
longest-mountain-in-array
0
1
[](https://www.youtube.com/watch?v=FpO3fY-1mj8)\nhttps://www.youtube.com/watch?v=FpO3fY-1mj8\n```\nclass Solution:\n def longestMountain(self, A: List[int]) -> int:\n res = 0\n \n for indx in range(1, len(A) - 1):\n if A[indx - 1] < A[indx] > A[indx + 1]:\n \n ...
15
You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some index `i` (**0-indexed**) 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]` Given an integer arr...
null
[Python 3] Explained Solution (video + code)
longest-mountain-in-array
0
1
[](https://www.youtube.com/watch?v=FpO3fY-1mj8)\nhttps://www.youtube.com/watch?v=FpO3fY-1mj8\n```\nclass Solution:\n def longestMountain(self, A: List[int]) -> int:\n res = 0\n \n for indx in range(1, len(A) - 1):\n if A[indx - 1] < A[indx] > A[indx + 1]:\n \n ...
15
Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours. Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k...
null
Solution
longest-mountain-in-array
1
1
```C++ []\nclass Solution {\npublic:\n int longestMountain(vector<int>& arr) {\n int n = arr.size(),ans=0,count;\n vector<int>peaks;\n for(int i=1;i<(n-1);i++){\n if(arr[i]>arr[i-1] && arr[i]>arr[i+1]){\n peaks.push_back(i);\n }\n }\n int m = pe...
2
You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some index `i` (**0-indexed**) 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]` Given an integer arr...
null
Solution
longest-mountain-in-array
1
1
```C++ []\nclass Solution {\npublic:\n int longestMountain(vector<int>& arr) {\n int n = arr.size(),ans=0,count;\n vector<int>peaks;\n for(int i=1;i<(n-1);i++){\n if(arr[i]>arr[i-1] && arr[i]>arr[i+1]){\n peaks.push_back(i);\n }\n }\n int m = pe...
2
Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours. Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k...
null
Python3: One pass, O(1) Auxiliary Space
longest-mountain-in-array
0
1
```\nclass Solution:\n def longestMountain(self, arr: List[int]) -> int:\n increasing = False\n increased = False\n mx = -math.inf\n curr = -math.inf\n for i in range(1, len(arr)):\n if arr[i] > arr[i-1]:\n if increasing:\n curr += 1\n ...
2
You may recall that an array `arr` is a **mountain array** if and only if: * `arr.length >= 3` * There exists some index `i` (**0-indexed**) 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]` Given an integer arr...
null
Python3: One pass, O(1) Auxiliary Space
longest-mountain-in-array
0
1
```\nclass Solution:\n def longestMountain(self, arr: List[int]) -> int:\n increasing = False\n increased = False\n mx = -math.inf\n curr = -math.inf\n for i in range(1, len(arr)):\n if arr[i] > arr[i-1]:\n if increasing:\n curr += 1\n ...
2
Koko loves to eat bananas. There are `n` piles of bananas, the `ith` pile has `piles[i]` bananas. The guards have gone and will come back in `h` hours. Koko can decide her bananas-per-hour eating speed of `k`. Each hour, she chooses some pile of bananas and eats `k` bananas from that pile. If the pile has less than `k...
null
Solution
hand-of-straights
1
1
```C++ []\nclass Solution {\npublic:\n bool isNStraightHand(vector<int>& hand, int sz) \n {\n int n = hand.size();\n if(n % sz) return 0;\n sort(hand.begin(), hand.end());\n for(int i=0; i<n; i++)\n {\n if(hand[i] == -1) continue;\n int k = i;\n for(int j=1; j<sz; j++...
2
Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size `groupSize`, and consists of `groupSize` consecutive cards. Given an integer array `hand` where `hand[i]` is the value written on the `ith` card and an integer `groupSize`, return `true` if she can rearrange t...
null
Solution
hand-of-straights
1
1
```C++ []\nclass Solution {\npublic:\n bool isNStraightHand(vector<int>& hand, int sz) \n {\n int n = hand.size();\n if(n % sz) return 0;\n sort(hand.begin(), hand.end());\n for(int i=0; i<n; i++)\n {\n if(hand[i] == -1) continue;\n int k = i;\n for(int j=1; j<sz; j++...
2
Given the `head` of a singly linked list, return _the middle node of the linked list_. If there are two middle nodes, return **the second middle** node. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[3,4,5\] **Explanation:** The middle node of the list is node 3. **Example 2:** **Input:** head = \[1,...
null
Simple O(n logn) Solution using Hash Table and Min Heap
hand-of-straights
0
1
```\n#####################################################################################################################\n# Problem: Hand of Straights\n# Solution : Hash Table, Min Heap\n# Time Complexity : O(n logn)\n# Space Complexity : O(n)\n#########################################################################...
9
Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size `groupSize`, and consists of `groupSize` consecutive cards. Given an integer array `hand` where `hand[i]` is the value written on the `ith` card and an integer `groupSize`, return `true` if she can rearrange t...
null
Simple O(n logn) Solution using Hash Table and Min Heap
hand-of-straights
0
1
```\n#####################################################################################################################\n# Problem: Hand of Straights\n# Solution : Hash Table, Min Heap\n# Time Complexity : O(n logn)\n# Space Complexity : O(n)\n#########################################################################...
9
Given the `head` of a singly linked list, return _the middle node of the linked list_. If there are two middle nodes, return **the second middle** node. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[3,4,5\] **Explanation:** The middle node of the list is node 3. **Example 2:** **Input:** head = \[1,...
null
Python3 || Hashmap || 15-line easy to understand
hand-of-straights
0
1
```\nclass Solution:\n def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:\n counter = Counter(hand)\n while counter:\n n = groupSize\n start = min(counter.keys())\n while n:\n if start not in counter:\n return False\n ...
6
Alice has some number of cards and she wants to rearrange the cards into groups so that each group is of size `groupSize`, and consists of `groupSize` consecutive cards. Given an integer array `hand` where `hand[i]` is the value written on the `ith` card and an integer `groupSize`, return `true` if she can rearrange t...
null
Python3 || Hashmap || 15-line easy to understand
hand-of-straights
0
1
```\nclass Solution:\n def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:\n counter = Counter(hand)\n while counter:\n n = groupSize\n start = min(counter.keys())\n while n:\n if start not in counter:\n return False\n ...
6
Given the `head` of a singly linked list, return _the middle node of the linked list_. If there are two middle nodes, return **the second middle** node. **Example 1:** **Input:** head = \[1,2,3,4,5\] **Output:** \[3,4,5\] **Explanation:** The middle node of the list is node 3. **Example 2:** **Input:** head = \[1,...
null
✅ 94.74% BFS + Bitmask
shortest-path-visiting-all-nodes
1
1
# Comprehensive Guide to Solving "Shortest Path Visiting All Nodes"\n\n## Introduction & Problem Statement\n\nGreetings, coding enthusiasts! Today we embark on a fascinating journey through the realm of graphs. Our mission is to discover the shortest path that visits every node in an undirected, connected graph. Intrig...
104
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes mul...
null
✅ 94.74% BFS + Bitmask
shortest-path-visiting-all-nodes
1
1
# Comprehensive Guide to Solving "Shortest Path Visiting All Nodes"\n\n## Introduction & Problem Statement\n\nGreetings, coding enthusiasts! Today we embark on a fascinating journey through the realm of graphs. Our mission is to discover the shortest path that visits every node in an undirected, connected graph. Intrig...
104
Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`. The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties. ...
null
PYTHON solution (based on two other solutions) using Bit Masks, Queues, and Named Tuples
shortest-path-visiting-all-nodes
0
1
# **NOTE: This PYTHON solution was written based off two other solutions, linked below.**\n**This is a community where we are all learning together and by no means do I claim this as my own work. I always believe in giving credit to the original authors, especially the first one, who included detailed visuals to help y...
1
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes mul...
null
PYTHON solution (based on two other solutions) using Bit Masks, Queues, and Named Tuples
shortest-path-visiting-all-nodes
0
1
# **NOTE: This PYTHON solution was written based off two other solutions, linked below.**\n**This is a community where we are all learning together and by no means do I claim this as my own work. I always believe in giving credit to the original authors, especially the first one, who included detailed visuals to help y...
1
Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`. The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties. ...
null
Easy solution
shortest-path-visiting-all-nodes
0
1
# Code\n```\nclass Solution:\n def shortestPathLength(self, graph: List[List[int]]) -> int:\n n = len(graph)\n visited = set()\n goal= (1 << n) - 1\n q = deque()\n ans = 0\n\n for i in range(n):\n q.append((i,1<<i))\n while q:\n for _ in range(le...
1
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes mul...
null
Easy solution
shortest-path-visiting-all-nodes
0
1
# Code\n```\nclass Solution:\n def shortestPathLength(self, graph: List[List[int]]) -> int:\n n = len(graph)\n visited = set()\n goal= (1 << n) - 1\n q = deque()\n ans = 0\n\n for i in range(n):\n q.append((i,1<<i))\n while q:\n for _ in range(le...
1
Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`. The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties. ...
null
Python accurated solution
shortest-path-visiting-all-nodes
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes mul...
null
Python accurated solution
shortest-path-visiting-all-nodes
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
Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`. The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties. ...
null
Python O( (n^2) * (2^n) ) by BFS + bitmask
shortest-path-visiting-all-nodes
0
1
[\u4E2D\u6587\u8A73\u89E3 \u89E3\u984C\u6587\u7AE0](https://vocus.cc/article/65069863fd897800018eb145)\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAll edge weight is equal, so we use BFS to find shortest path.\n\nTo avoid repeated traversal and looping in deadlock, we record t...
1
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes mul...
null
Python O( (n^2) * (2^n) ) by BFS + bitmask
shortest-path-visiting-all-nodes
0
1
[\u4E2D\u6587\u8A73\u89E3 \u89E3\u984C\u6587\u7AE0](https://vocus.cc/article/65069863fd897800018eb145)\n\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAll edge weight is equal, so we use BFS to find shortest path.\n\nTo avoid repeated traversal and looping in deadlock, we record t...
1
Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`. The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties. ...
null
Easy Solution || Beginner Friendly || Line By Line Explanation || Beats 95%+ || Python || Java || C+
shortest-path-visiting-all-nodes
1
1
# BEATS\n![image.png](https://assets.leetcode.com/users/images/eedf0ffd-4ac8-42d7-9f1f-7e3373fe3820_1694933374.127867.png)\n\n# Intuition\nThe problem can be approached using Breadth-First Search (BFS) to explore different paths in the graph. The key insight is to use a bitmask to keep track of which nodes have been vi...
28
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes mul...
null
Easy Solution || Beginner Friendly || Line By Line Explanation || Beats 95%+ || Python || Java || C+
shortest-path-visiting-all-nodes
1
1
# BEATS\n![image.png](https://assets.leetcode.com/users/images/eedf0ffd-4ac8-42d7-9f1f-7e3373fe3820_1694933374.127867.png)\n\n# Intuition\nThe problem can be approached using Breadth-First Search (BFS) to explore different paths in the graph. The key insight is to use a bitmask to keep track of which nodes have been vi...
28
Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`. The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties. ...
null
🚀 97.92% || BFS + Bitmask || Explained Intuition || Commented Code 🚀
shortest-path-visiting-all-nodes
1
1
# Probelm Description\nGiven an **undirected**, **connected** graph with `n` nodes labeled from `0` to `n - 1`, represented by an **adjacency list** in the form of an array graph, where `graph[i]` is a **list** of nodes **connected** to node `i`.\nThe task is to find the length of the **shortest path** that visits ever...
47
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes mul...
null
🚀 97.92% || BFS + Bitmask || Explained Intuition || Commented Code 🚀
shortest-path-visiting-all-nodes
1
1
# Probelm Description\nGiven an **undirected**, **connected** graph with `n` nodes labeled from `0` to `n - 1`, represented by an **adjacency list** in the form of an array graph, where `graph[i]` is a **list** of nodes **connected** to node `i`.\nThe task is to find the length of the **shortest path** that visits ever...
47
Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`. The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties. ...
null
Python Simplest solution You will ever find for this problem
shortest-path-visiting-all-nodes
0
1
\n\n# Code\n```\nclass Solution:\n\n def shortestPathLength(self, graph: List[List[int]]) -> int:\n q=deque()\n s=set()\n n=len(graph)\n for i in range(n):\n q.append([i,0,1<<i])\n s.add((i,i<<i))\n reached=(1<<n) - 1\n while len(q)>0:\n node...
0
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes mul...
null
Python Simplest solution You will ever find for this problem
shortest-path-visiting-all-nodes
0
1
\n\n# Code\n```\nclass Solution:\n\n def shortestPathLength(self, graph: List[List[int]]) -> int:\n q=deque()\n s=set()\n n=len(graph)\n for i in range(n):\n q.append([i,0,1<<i])\n s.add((i,i<<i))\n reached=(1<<n) - 1\n while len(q)>0:\n node...
0
Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`. The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties. ...
null
Efficient Algorithm for Shortest Path Visiting All Nodes using Bitmasking and BFS
shortest-path-visiting-all-nodes
1
1
# Intuition\nThe main point of the algorithm is to find the shortest path that visits all nodes in a given graph. This is achieved by utilizing a bitmask to keep track of visited nodes and their states during a breadth-first search (BFS) traversal. The algorithm explores the graph, updating the state of visited nodes u...
10
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes mul...
null
Efficient Algorithm for Shortest Path Visiting All Nodes using Bitmasking and BFS
shortest-path-visiting-all-nodes
1
1
# Intuition\nThe main point of the algorithm is to find the shortest path that visits all nodes in a given graph. This is achieved by utilizing a bitmask to keep track of visited nodes and their states during a breadth-first search (BFS) traversal. The algorithm explores the graph, updating the state of visited nodes u...
10
Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`. The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties. ...
null
Python3 Solution
shortest-path-visiting-all-nodes
0
1
\n```\nclass Solution:\n def shortestPathLength(self, graph: List[List[int]]) -> int:\n n=len(graph)\n queue=deque([(i,1<<i) for i in range(n)])\n seen=set(queue)\n ans=0\n while queue:\n for _ in range(len(queue)):\n u,m=queue.popleft()\n i...
6
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes mul...
null
Python3 Solution
shortest-path-visiting-all-nodes
0
1
\n```\nclass Solution:\n def shortestPathLength(self, graph: List[List[int]]) -> int:\n n=len(graph)\n queue=deque([(i,1<<i) for i in range(n)])\n seen=set(queue)\n ans=0\n while queue:\n for _ in range(len(queue)):\n u,m=queue.popleft()\n i...
6
Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`. The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties. ...
null
🚀Most Efficient Python Code 🐍 || Beats 95% 🔥🔥
shortest-path-visiting-all-nodes
0
1
# Intuition\nThe intuition behind the code is to use a combination of bitmasking and breadth-first search (BFS) to explore all possible paths in the graph efficiently. The goal is to find the shortest path that visits all nodes in the graph at least once. The code maintains a state for each visited node and the bitmask...
3
You have an undirected, connected graph of `n` nodes labeled from `0` to `n - 1`. You are given an array `graph` where `graph[i]` is a list of all the nodes connected with node `i` by an edge. Return _the length of the shortest path that visits every node_. You may start and stop at any node, you may revisit nodes mul...
null
🚀Most Efficient Python Code 🐍 || Beats 95% 🔥🔥
shortest-path-visiting-all-nodes
0
1
# Intuition\nThe intuition behind the code is to use a combination of bitmasking and breadth-first search (BFS) to explore all possible paths in the graph efficiently. The goal is to find the shortest path that visits all nodes in the graph at least once. The code maintains a state for each visited node and the bitmask...
3
Alice and Bob play a game with piles of stones. There are an **even** number of piles arranged in a row, and each pile has a **positive** integer number of stones `piles[i]`. The objective of the game is to end with the most stones. The **total** number of stones across all the piles is **odd**, so there are no ties. ...
null
Python Easy To Understand
shifting-letters
0
1
# Code\n```\nclass Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n sumArr=[shifts[len(s)-1]%26]\n new=""\n for i in range(1,len(s)):\n sumArr.insert(0,(sumArr[0]+shifts[len(s)-i-1])%26)\n for i in range(len(s)):\n n=ord(s[i])+sumArr[i]\n ...
1
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`. Now for each `shif...
null
Python Easy To Understand
shifting-letters
0
1
# Code\n```\nclass Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n sumArr=[shifts[len(s)-1]%26]\n new=""\n for i in range(1,len(s)):\n sumArr.insert(0,(sumArr[0]+shifts[len(s)-i-1])%26)\n for i in range(len(s)):\n n=ord(s[i])+sumArr[i]\n ...
1
A positive integer is _magical_ if it is divisible by either `a` or `b`. Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 1, a = 2, b = 3 **Output:** 2 **Example 2:** **Input:** n = 4, a = ...
null
[Python 3] Reversed prefix sum || beats 100% || 610ms 🥷🏼
shifting-letters
0
1
```python3 []\nclass Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n shifts = list(accumulate(shifts[::-1]))\n\n res = []\n for c, k in zip(s, shifts[::-1]):\n pos = (ord(c) - 97 + k) % 26 + 97\n res.append(chr(pos))\n\n return \'\'.join(re...
3
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`. Now for each `shif...
null
[Python 3] Reversed prefix sum || beats 100% || 610ms 🥷🏼
shifting-letters
0
1
```python3 []\nclass Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n shifts = list(accumulate(shifts[::-1]))\n\n res = []\n for c, k in zip(s, shifts[::-1]):\n pos = (ord(c) - 97 + k) % 26 + 97\n res.append(chr(pos))\n\n return \'\'.join(re...
3
A positive integer is _magical_ if it is divisible by either `a` or `b`. Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 1, a = 2, b = 3 **Output:** 2 **Example 2:** **Input:** n = 4, a = ...
null
python easy to understand solution for beginner
shifting-letters
0
1
```\nclass Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n self.letters = {chr(97+i):i for i in range(26)}\n ans = \'\'\n summ = sum(shifts)\n for elm,i in zip(s,shifts):\n ans += self.shift(elm,summ%26)\n summ -= i\n return ans\n ...
1
You are given a string `s` of lowercase English letters and an integer array `shifts` of the same length. Call the `shift()` of a letter, the next letter in the alphabet, (wrapping around so that `'z'` becomes `'a'`). * For example, `shift('a') = 'b'`, `shift('t') = 'u'`, and `shift('z') = 'a'`. Now for each `shif...
null
python easy to understand solution for beginner
shifting-letters
0
1
```\nclass Solution:\n def shiftingLetters(self, s: str, shifts: List[int]) -> str:\n self.letters = {chr(97+i):i for i in range(26)}\n ans = \'\'\n summ = sum(shifts)\n for elm,i in zip(s,shifts):\n ans += self.shift(elm,summ%26)\n summ -= i\n return ans\n ...
1
A positive integer is _magical_ if it is divisible by either `a` or `b`. Given the three integers `n`, `a`, and `b`, return the `nth` magical number. Since the answer may be very large, **return it modulo** `109 + 7`. **Example 1:** **Input:** n = 1, a = 2, b = 3 **Output:** 2 **Example 2:** **Input:** n = 4, a = ...
null