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 |
|---|---|---|---|---|---|---|---|
Two python solutions using dp and a straightforward soln | longest-continuous-increasing-subsequence | 0 | 1 | 1. DP solution.\n```class Solution:\n def findLengthOfLCIS(self, nums: List[int]) -> int:\n dp=[1]*len(nums)\n for i in range(1,len(nums)):\n if nums[i]>nums[i-1]:\n dp[i]+=dp[i-1]\n return max(dp)\n ```\n2\n```\nclass Solution:\n def findLengthOfLCIS(self, nums: Lis... | 6 | Given an unsorted array of integers `nums`, return _the length of the longest **continuous increasing subsequence** (i.e. subarray)_. The subsequence must be **strictly** increasing.
A **continuous increasing subsequence** is defined by two indices `l` and `r` (`l < r`) such that it is `[nums[l], nums[l + 1], ..., num... | null |
Python O(n) Solution - O(1) Space Complexity | longest-continuous-increasing-subsequence | 0 | 1 | ```\nclass Solution:\n def findLengthOfLCIS(self, nums: List[int]) -> int:\n if not nums:\n return 0\n \n cur_len = 1\n max_len = 1\n \n for i in range(1,len(nums)):\n if nums[i] > nums[i-1]:\n cur_len += 1\n else:\n ... | 19 | Given an unsorted array of integers `nums`, return _the length of the longest **continuous increasing subsequence** (i.e. subarray)_. The subsequence must be **strictly** increasing.
A **continuous increasing subsequence** is defined by two indices `l` and `r` (`l < r`) such that it is `[nums[l], nums[l + 1], ..., num... | null |
674: Solution with step by step explanation | longest-continuous-increasing-subsequence | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. We handle the base cases where the input list is empty or has only one element. In both cases, the length of the longest continuous in1.creasing subsequence is the length of the input list itself, so we simply return that... | 4 | Given an unsorted array of integers `nums`, return _the length of the longest **continuous increasing subsequence** (i.e. subarray)_. The subsequence must be **strictly** increasing.
A **continuous increasing subsequence** is defined by two indices `l` and `r` (`l < r`) such that it is `[nums[l], nums[l + 1], ..., num... | null |
O(N) solution | longest-continuous-increasing-subsequence | 0 | 1 | ```\nclass Solution:\n def findLengthOfLCIS(self, nums: List[int]) -> int:\n maxLen = count = 1\n for i in range(len(nums) - 1):\n if nums[i] < nums[i + 1]:\n count += 1\n else:\n count = 1\n \n maxLen = max(count, maxLen)\n ... | 2 | Given an unsorted array of integers `nums`, return _the length of the longest **continuous increasing subsequence** (i.e. subarray)_. The subsequence must be **strictly** increasing.
A **continuous increasing subsequence** is defined by two indices `l` and `r` (`l < r`) such that it is `[nums[l], nums[l + 1], ..., num... | null |
Solution | longest-continuous-increasing-subsequence | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int findLengthOfLCIS(vector<int>& nums) {\n int maxlength = 1;\n int length = 1;\n int n = nums.size();\n for(int i= 1; i<n;i++){\n if (nums[i-1]<nums[i]){\n length++;\n }\n else{\n if(ma... | 2 | Given an unsorted array of integers `nums`, return _the length of the longest **continuous increasing subsequence** (i.e. subarray)_. The subsequence must be **strictly** increasing.
A **continuous increasing subsequence** is defined by two indices `l` and `r` (`l < r`) such that it is `[nums[l], nums[l + 1], ..., num... | null |
python3 || easy | longest-continuous-increasing-subsequence | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->easy \n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n)\n<!-- Add your space complexity here, e.g... | 0 | Given an unsorted array of integers `nums`, return _the length of the longest **continuous increasing subsequence** (i.e. subarray)_. The subsequence must be **strictly** increasing.
A **continuous increasing subsequence** is defined by two indices `l` and `r` (`l < r`) such that it is `[nums[l], nums[l + 1], ..., num... | null |
Python 3 || 19 lines bfs || T/M: 91% / 21% | cut-off-trees-for-golf-event | 0 | 1 | This code is similar to those in other posts, with one exception. We use `unseen` to prune out the zero cells initially, and then keep track of the cells *not* visited.\n```\nclass Solution:\n\n def cutOffTree(self, forest: List[List[int]]) -> int:\n\n def bfs(beg, end):\n queue, uns = deque([(beg,... | 4 | You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an `m x n` matrix. In this matrix:
* `0` means the cell cannot be walked through.
* `1` represents an empty cell that can be walked through.
* A number greater than `1` represents a tree in a cell that can be walked... | null |
Solution | cut-off-trees-for-golf-event | 1 | 1 | ```C++ []\nclass Solution {\n static constexpr int DIR[4][2] = {{-1,0},{1,0},{0,-1},{0,1}};\n struct Cell {\n short r : 8;\n short c : 8;\n };\n int doit(const vector<vector<int>>& forest, Cell start, vector<int> &curr, vector<int> &prev, vector<Cell> &bfs) {\n const int M = forest.size... | 2 | You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an `m x n` matrix. In this matrix:
* `0` means the cell cannot be walked through.
* `1` represents an empty cell that can be walked through.
* A number greater than `1` represents a tree in a cell that can be walked... | null |
675: Solution with step by step explanation | cut-off-trees-for-golf-event | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. We first initialize the size of the forest m and n. We also create an empty list called trees which will contain tuples of (height, x, y) where x and y are the coordinates of the tree in the forest.\n\n2. We iterate throu... | 2 | You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an `m x n` matrix. In this matrix:
* `0` means the cell cannot be walked through.
* `1` represents an empty cell that can be walked through.
* A number greater than `1` represents a tree in a cell that can be walked... | null |
[Python] BFS & PriorityQueue - w/ comments and prints for visualization | cut-off-trees-for-golf-event | 0 | 1 | Approach: \nHave priority queue that stores (height,x,y) for each tree in order of min to max.\nUse BFS to find the next available smallest height in priority queue.\n\nComplexity:\nLet m=len(forest), n=len(forest[0])\nO(mnlog(mn) + 3^(m+n)) runtime - 692ms (45.50%)\nO(mn) space - 14.9MB (56.88%)\n\n```Python\nfrom typ... | 8 | You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an `m x n` matrix. In this matrix:
* `0` means the cell cannot be walked through.
* `1` represents an empty cell that can be walked through.
* A number greater than `1` represents a tree in a cell that can be walked... | null |
Python, normal and priority BFS, faster than 99% and faster than 77% | cut-off-trees-for-golf-event | 0 | 1 | ## normal bfs\n\n\n```\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n forest.append([0] * len(forest[0]))\n for row in forest: row.append(0)\n def bfs(end, st... | 4 | You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an `m x n` matrix. In this matrix:
* `0` means the cell cannot be walked through.
* `1` represents an empty cell that can be walked through.
* A number greater than `1` represents a tree in a cell that can be walked... | null |
Average solution | cut-off-trees-for-golf-event | 0 | 1 | # Intuition\n1. Sort order of trees\n2. Call bfs to reach next tree from current pos\n - Increment total steps whilst doing so\n \n# Code\n```\nclass Solution:\n def cutOffTree(self, forest: List[List[int]]) -> int:\n order = []\n m = len(forest)\n n = len(forest[0])\n directions = ... | 0 | You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an `m x n` matrix. In this matrix:
* `0` means the cell cannot be walked through.
* `1` represents an empty cell that can be walked through.
* A number greater than `1` represents a tree in a cell that can be walked... | null |
Python BFS Solution using `deque` | cut-off-trees-for-golf-event | 0 | 1 | # Intuition\n<!-- -->\nConduct BFS repeatedly to find each point in ascending order, next time starting from the point you found in previous execution of BFS.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Sort all tree position in ascending order\n2. Set initial node = `(0, 0)`\n3. Run BFS t... | 0 | You are asked to cut off all the trees in a forest for a golf event. The forest is represented as an `m x n` matrix. In this matrix:
* `0` means the cell cannot be walked through.
* `1` represents an empty cell that can be walked through.
* A number greater than `1` represents a tree in a cell that can be walked... | null |
Solution | implement-magic-dictionary | 1 | 1 | ```C++ []\nclass MagicDictionary {\n public:\n void buildDict(vector<string> dictionary) {\n for (const string& word : dictionary)\n for (int i = 0; i < word.length(); ++i) {\n const string replaced = getReplaced(word, i);\n dict[replaced] = dict.count(replaced) ? \'*\' : word[i];\n }\n }\n... | 1 | Design a data structure that is initialized with a list of **different** words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the `MagicDictionary` class:
* `MagicDictionary()` Initializes the object.
* `void build... | null |
[Python 3] - Trie - Simple Solution | implement-magic-dictionary | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(N*K)$$ with N is the number of word and K is length of each word\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Spa... | 3 | Design a data structure that is initialized with a list of **different** words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the `MagicDictionary` class:
* `MagicDictionary()` Initializes the object.
* `void build... | null |
676: Solution with step by step explanation | implement-magic-dictionary | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. __init__ method\n 1. Create an empty dictionary to hold the words and their replacements.\n 2. Store the dictionary in the class attribute self.dict.\n2. buildDict method\n 1. For each word in the dictionary argu... | 3 | Design a data structure that is initialized with a list of **different** words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the `MagicDictionary` class:
* `MagicDictionary()` Initializes the object.
* `void build... | null |
2 Solution Beginner Friendly Set and simple array using Zip (Python3) | implement-magic-dictionary | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\n- 1. Array and Zip \n- 2. Set method\n\n# Complexity\n\n- Array and Zip\n - Time complexity: O(n * m)\n\n - Space complexity: O(n + m)\n- Set \n - Time complexity: O(26M) \n\n - Space complexity: O(n * m)\n\n# 1. Simple Array and zip meth... | 3 | Design a data structure that is initialized with a list of **different** words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the `MagicDictionary` class:
* `MagicDictionary()` Initializes the object.
* `void build... | null |
Python 97.27% speed | Hashmap only | Simple code | implement-magic-dictionary | 0 | 1 | For each word, length is the key. For each searchWord, only need to check the words with same length\n\n```\nclass MagicDictionary:\n\n def __init__(self):\n self.myDict = defaultdict(set)\n\n def buildDict(self, dictionary: List[str]) -> None:\n for word in dictionary:\n n = len(word)\n ... | 5 | Design a data structure that is initialized with a list of **different** words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the `MagicDictionary` class:
* `MagicDictionary()` Initializes the object.
* `void build... | null |
My fast Python solution | implement-magic-dictionary | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thoughts on how to solve this problem is to create a data structure that stores all the words in the dictionary. Then, when searching for a word, I will iterate through each word in the data structure and compare it to the search... | 2 | Design a data structure that is initialized with a list of **different** words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the `MagicDictionary` class:
* `MagicDictionary()` Initializes the object.
* `void build... | null |
Easy to read solution using a dictionary of set of candidate words with a length as key | implement-magic-dictionary | 0 | 1 | \n# Code\n```\nclass MagicDictionary:\n\n def __init__(self):\n self.dct = collections.defaultdict(set) # key:value = length:set of words with length\n \n\n def buildDict(self, dictionary: List[str]) -> None:\n for word in dictionary:\n n = len(word)\n self.dct[n].add(wo... | 0 | Design a data structure that is initialized with a list of **different** words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the `MagicDictionary` class:
* `MagicDictionary()` Initializes the object.
* `void build... | null |
Python | Trie | implement-magic-dictionary | 0 | 1 | # Code\n```\nclass MagicDictionary:\n\n def __init__(self):\n self.trie = {}\n\n def buildDict(self, dictionary: List[str]) -> None:\n for word in dictionary:\n node = self.trie\n for ch in word:\n if ch not in node:\n node[ch] = {}\n ... | 0 | Design a data structure that is initialized with a list of **different** words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the `MagicDictionary` class:
* `MagicDictionary()` Initializes the object.
* `void build... | null |
use hashmap and hamming distance | implement-magic-dictionary | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. we first build a hashmap using string length as key and a list of strings in the dictionary of that length as the value\n2. we then build a mini function to calculate hamming distance of two strings with equal length\n3. ... | 0 | Design a data structure that is initialized with a list of **different** words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the `MagicDictionary` class:
* `MagicDictionary()` Initializes the object.
* `void build... | null |
easy and fast python solution. | implement-magic-dictionary | 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:\nworst case `O(N*k)` where N is num of words in dictionary, k is the length of the search word. Worst case == we must search all dic... | 0 | Design a data structure that is initialized with a list of **different** words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the `MagicDictionary` class:
* `MagicDictionary()` Initializes the object.
* `void build... | null |
Python Trie BFS Solution 🎄 | implement-magic-dictionary | 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 | Design a data structure that is initialized with a list of **different** words. Provided a string, you should determine if you can change exactly one character in this string to match any word in the data structure.
Implement the `MagicDictionary` class:
* `MagicDictionary()` Initializes the object.
* `void build... | null |
677: Solution with step by step explanation | map-sum-pairs | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nDefine a TrieNode class with two attributes: children (a dictionary mapping characters to child nodes) and value (an integer representing the sum of values stored at or below this node in the Trie).\n\nDefine a MapSum class ... | 2 | Design a map that allows you to do the following:
* Maps a string key to a given value.
* Returns the sum of the values that have a key with a prefix equal to a given string.
Implement the `MapSum` class:
* `MapSum()` Initializes the `MapSum` object.
* `void insert(String key, int val)` Inserts the `key-val`... | null |
Solution | map-sum-pairs | 1 | 1 | ```C++ []\nstruct TrieNode {\n vector<shared_ptr<TrieNode>> children;\n int sum = 0;\n TrieNode() : children(26) {}\n};\nclass MapSum {\n public:\n void insert(string key, int val) {\n const int diff = val - keyToVal[key];\n shared_ptr<TrieNode> node = root;\n for (const char c : key) {\n const int i ... | 2 | Design a map that allows you to do the following:
* Maps a string key to a given value.
* Returns the sum of the values that have a key with a prefix equal to a given string.
Implement the `MapSum` class:
* `MapSum()` Initializes the `MapSum` object.
* `void insert(String key, int val)` Inserts the `key-val`... | null |
[Python] TRIE Solution easy to understand | map-sum-pairs | 0 | 1 | ```\nclass TrieNode:\n def __init__(self):\n self.children = {}\n self.prefixCount = 0\n \n \nclass MapSum: \n\n def __init__(self):\n self.root = TrieNode()\n self.dic = {}\n\n def insert(self, key: str, val: int) -> None: \n delta = val\n if key in sel... | 6 | Design a map that allows you to do the following:
* Maps a string key to a given value.
* Returns the sum of the values that have a key with a prefix equal to a given string.
Implement the `MapSum` class:
* `MapSum()` Initializes the `MapSum` object.
* `void insert(String key, int val)` Inserts the `key-val`... | null |
88% TC and 92% SC easy python solution using map | map-sum-pairs | 0 | 1 | ```\nclass MapSum:\n def __init__(self):\n self.d = defaultdict(int)\n self.s = dict()\n\n def insert(self, key: str, val: int) -> None:\n if(key in self.s):\n val, self.s[key] = val - self.s[key], val\n else:\n self.s[key] = val\n for i in range(1, len(key... | 1 | Design a map that allows you to do the following:
* Maps a string key to a given value.
* Returns the sum of the values that have a key with a prefix equal to a given string.
Implement the `MapSum` class:
* `MapSum()` Initializes the `MapSum` object.
* `void insert(String key, int val)` Inserts the `key-val`... | null |
Python - Modifying the standard Trie concept | map-sum-pairs | 0 | 1 | ```\nclass TrieNode:\n def __init__(self):\n self.children = collections.defaultdict(TrieNode)\n self.value = 0\n \nclass MapSum:\n def __init__(self):\n self.t = TrieNode()\n self.m = {}\n\n def insert(self, key: str, val: int) -> None:\n delta = val - self.m.get(key,... | 6 | Design a map that allows you to do the following:
* Maps a string key to a given value.
* Returns the sum of the values that have a key with a prefix equal to a given string.
Implement the `MapSum` class:
* `MapSum()` Initializes the `MapSum` object.
* `void insert(String key, int val)` Inserts the `key-val`... | null |
✅ Easy Python 3 O(k) Beats 90% Trie + Dictionary ✅ | map-sum-pairs | 0 | 1 | # Intuition\nWe use a trie to store all the keys. The trie nodes are associated with their corresponding character but also holds a value field. This value feild tracks the sum of all keys who uses this particular node in the trie.\n\n# Approach\nWrite a separate TrieNode class: the children field is implemented with a... | 0 | Design a map that allows you to do the following:
* Maps a string key to a given value.
* Returns the sum of the values that have a key with a prefix equal to a given string.
Implement the `MapSum` class:
* `MapSum()` Initializes the `MapSum` object.
* `void insert(String key, int val)` Inserts the `key-val`... | null |
Python Trie | map-sum-pairs | 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 | Design a map that allows you to do the following:
* Maps a string key to a given value.
* Returns the sum of the values that have a key with a prefix equal to a given string.
Implement the `MapSum` class:
* `MapSum()` Initializes the `MapSum` object.
* `void insert(String key, int val)` Inserts the `key-val`... | null |
Python 3, Brute Force Recursive + memo | valid-parenthesis-string | 0 | 1 | # Intuition\nrecursive + memo\n\n\n# Complexity\n- Time complexity: O(n^3)\n- Space complexity: O(n^3)\n\n# Code\n```\nclass Solution:\n def checkValidString(self, s: str) -> bool:\n n: int = len(s)\n\n memo = {}\n def f(i: int, left: int):\n\n if (i, left) in memo:\n r... | 1 | Given a string `s` containing only three types of characters: `'('`, `')'` and `'*'`, return `true` _if_ `s` _is **valid**_.
The following rules define a **valid** string:
* Any left parenthesis `'('` must have a corresponding right parenthesis `')'`.
* Any right parenthesis `')'` must have a corresponding left p... | null |
Python O(n) by stack. 85%+ [w/ Comment] | valid-parenthesis-string | 0 | 1 | [\u4E2D\u6587\u8A73\u89E3 \u89E3\u984C\u6587\u7AE0](https://vocus.cc/article/6541ed1afd89780001044ee2)\n\nPython O(n) by stack. \n\n---\n\n```\nclass Solution:\n def checkValidString(self, s: str) -> bool:\n \n # store the indices of \'(\'\n stk = []\n \n # store the indices of \'*... | 48 | Given a string `s` containing only three types of characters: `'('`, `')'` and `'*'`, return `true` _if_ `s` _is **valid**_.
The following rules define a **valid** string:
* Any left parenthesis `'('` must have a corresponding right parenthesis `')'`.
* Any right parenthesis `')'` must have a corresponding left p... | null |
678: Solution with step by step explanation | valid-parenthesis-string | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nInitialize two empty stacks, left_paren_stack and asterisk_stack, to keep track of indices of left parentheses and asterisks, respectively.\n\nIterate through each character s[i] in the string:\n\nIf s[i] is \'(\', append th... | 9 | Given a string `s` containing only three types of characters: `'('`, `')'` and `'*'`, return `true` _if_ `s` _is **valid**_.
The following rules define a **valid** string:
* Any left parenthesis `'('` must have a corresponding right parenthesis `')'`.
* Any right parenthesis `')'` must have a corresponding left p... | null |
Python Time O(n) Space O(1) Greedy Solution with Detailed Explanation and some proof | valid-parenthesis-string | 0 | 1 | \nFirst, if we do not have asterisk\uFF0Cin order to be vaild\n* obs1: "(" should be more or equal to ")" when we check the string from left to right\n* obs2: At the end, there is no open "(" ( i.e. equal number of "(" and ")")\n\nFor example,\n* "(()))("-> False, index = 4, two "(" and three ")" then ")" at index 4 w... | 19 | Given a string `s` containing only three types of characters: `'('`, `')'` and `'*'`, return `true` _if_ `s` _is **valid**_.
The following rules define a **valid** string:
* Any left parenthesis `'('` must have a corresponding right parenthesis `')'`.
* Any right parenthesis `')'` must have a corresponding left p... | null |
Python 3 || 9 lines, dfs || T/M: 37% / 99% | 24-game | 0 | 1 | ```\ndiv = lambda x,y: reduce(truediv,(x,y)) if y else inf\nops = (add, sub, mul, div)\n\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n\n def dfs(c: list) -> bool:\n\n if len(c) <2 : return isclose(c[0], 24)\n \n for p in set(permutations(c)):\n ... | 3 | You are given an integer array `cards` of length `4`. You have four cards, each containing a number in the range `[1, 9]`. You should arrange the numbers on these cards in a mathematical expression using the operators `['+', '-', '*', '/']` and the parentheses `'('` and `')'` to get the value 24.
You are restricted wi... | null |
Python || Solver can optionally print *all* solutions | 24-game | 0 | 1 | # Intuition\nPick any two numbers apply any operation, and replace the two numbers with their result. We now have a smaller problem.\n\n# Code\n```\nclass Solution:\n def judgePoint24(self, cards: List[int]) -> bool:\n def compute(a,b,op):\n if op==0:\n return a+b\n if op=... | 1 | You are given an integer array `cards` of length `4`. You have four cards, each containing a number in the range `[1, 9]`. You should arrange the numbers on these cards in a mathematical expression using the operators `['+', '-', '*', '/']` and the parentheses `'('` and `')'` to get the value 24.
You are restricted wi... | null |
Python - 80ms | 24-game | 0 | 1 | ```\nimport itertools as it\n\nclass Solution:\n def judgePoint24(self, nums: List[int]) -> bool:\n if len(nums) == 1:\n return round(nums[0], 4) == 24\n else:\n for (i, m), (j, n) in it.combinations(enumerate(nums), 2):\n new_nums = [x for t, x in enumerate(num... | 20 | You are given an integer array `cards` of length `4`. You have four cards, each containing a number in the range `[1, 9]`. You should arrange the numbers on these cards in a mathematical expression using the operators `['+', '-', '*', '/']` and the parentheses `'('` and `')'` to get the value 24.
You are restricted wi... | null |
679: Solution with step by step explanation | 24-game | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define a helper function called "generate" that takes in two float values "a" and "b" and returns a list of float values that represent all possible arithmetic combinations of "a" and "b".\n2. Define another helper functi... | 4 | You are given an integer array `cards` of length `4`. You have four cards, each containing a number in the range `[1, 9]`. You should arrange the numbers on these cards in a mathematical expression using the operators `['+', '-', '*', '/']` and the parentheses `'('` and `')'` to get the value 24.
You are restricted wi... | null |
Python: DFS (Very fast) | 24-game | 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 an integer array `cards` of length `4`. You have four cards, each containing a number in the range `[1, 9]`. You should arrange the numbers on these cards in a mathematical expression using the operators `['+', '-', '*', '/']` and the parentheses `'('` and `')'` to get the value 24.
You are restricted wi... | null |
[Python3] 9 lines, DFS | runtime 94 ms; beats 46.15% | 24-game | 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 an integer array `cards` of length `4`. You have four cards, each containing a number in the range `[1, 9]`. You should arrange the numbers on these cards in a mathematical expression using the operators `['+', '-', '*', '/']` and the parentheses `'('` and `')'` to get the value 24.
You are restricted wi... | null |
python solution | 24-game | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nI don\'t know whether i over complicated the problem....\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... | 0 | You are given an integer array `cards` of length `4`. You have four cards, each containing a number in the range `[1, 9]`. You should arrange the numbers on these cards in a mathematical expression using the operators `['+', '-', '*', '/']` and the parentheses `'('` and `')'` to get the value 24.
You are restricted wi... | null |
Python 3 || Two Pointer Approach || Self-Understandable | valid-palindrome-ii | 0 | 1 | ```\nclass Solution:\n def validPalindrome(self, s: str) -> bool:\n p1=0\n p2=len(s)-1\n while p1<=p2:\n if s[p1]!=s[p2]:\n string1=s[:p1]+s[p1+1:]\n string2=s[:p2]+s[p2+1:]\n return string1==string1[::-1] or str... | 115 | Given a string `s`, return `true` _if the_ `s` _can be palindrome after deleting **at most one** character from it_.
**Example 1:**
**Input:** s = "aba "
**Output:** true
**Example 2:**
**Input:** s = "abca "
**Output:** true
**Explanation:** You could delete the character 'c'.
**Example 3:**
**Input:** s = "a... | null |
Simple python Two-Pointer approach | valid-palindrome-ii | 0 | 1 | # Approach\nApply two pointer and increment the left pointer whenever the left value != right value\nRepeat the same by decrementing the right value.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nc... | 2 | Given a string `s`, return `true` _if the_ `s` _can be palindrome after deleting **at most one** character from it_.
**Example 1:**
**Input:** s = "aba "
**Output:** true
**Example 2:**
**Input:** s = "abca "
**Output:** true
**Explanation:** You could delete the character 'c'.
**Example 3:**
**Input:** s = "a... | null |
Python Readable and Intuitive Solution (Generalizable to n deletes) | valid-palindrome-ii | 0 | 1 | Simply checking if character at left matches corresponding right until it doesn\'t. At that point we have a choice of either deleting the left or right character. If either returns Palindrome, we return true. To generalize this to more than one deletes, we can simply replace the flag "deleted" to be a counter initializ... | 130 | Given a string `s`, return `true` _if the_ `s` _can be palindrome after deleting **at most one** character from it_.
**Example 1:**
**Input:** s = "aba "
**Output:** true
**Example 2:**
**Input:** s = "abca "
**Output:** true
**Explanation:** You could delete the character 'c'.
**Example 3:**
**Input:** s = "a... | null |
Easy python recursive solution, easy to understand | valid-palindrome-ii | 0 | 1 | \n# Code\n```\nclass Solution:\n\n def ispalindrome(self,s,i,j,skip1):\n while(i<j):\n if s[i]==s[j]:\n i+=1\n j-=1\n elif s[i]!=s[j] and not skip1:\n return self.ispalindrome(s,i+1,j,skip1=True) or self.ispalindrome(s,i,j-1,skip1=True)\n ... | 1 | Given a string `s`, return `true` _if the_ `s` _can be palindrome after deleting **at most one** character from it_.
**Example 1:**
**Input:** s = "aba "
**Output:** true
**Example 2:**
**Input:** s = "abca "
**Output:** true
**Explanation:** You could delete the character 'c'.
**Example 3:**
**Input:** s = "a... | null |
PythonnohtyP Palindrome Solution | valid-palindrome-ii | 0 | 1 | ```\nclass Solution:\n # Classic 2 pointer solution\n # Start travelling from start and ends\n # The first mismatch gives us 2 options\n # We can either remove the first or the end character and the remaining string must be a plindrome\n # Else return False\n def validPalindrome(self, s: str) -> bool:... | 1 | Given a string `s`, return `true` _if the_ `s` _can be palindrome after deleting **at most one** character from it_.
**Example 1:**
**Input:** s = "aba "
**Output:** true
**Example 2:**
**Input:** s = "abca "
**Output:** true
**Explanation:** You could delete the character 'c'.
**Example 3:**
**Input:** s = "a... | null |
Python 94.65% faster ||Simplest solution with explanation|| Beg to Adv|| Two Pointer | valid-palindrome-ii | 0 | 1 | ```python\nclass Solution:\n def validPalindrome(self, s: str) -> bool:\n left = 0 # pointer one\n right = len(s) - 1 # pointer two\n \n while left < right: # index should be less then right one, not even equal, as we dont need to compare same index\n if s[left] == s[right]: #... | 31 | Given a string `s`, return `true` _if the_ `s` _can be palindrome after deleting **at most one** character from it_.
**Example 1:**
**Input:** s = "aba "
**Output:** true
**Example 2:**
**Input:** s = "abca "
**Output:** true
**Explanation:** You could delete the character 'c'.
**Example 3:**
**Input:** s = "a... | null |
using stack | baseball-game | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def calPoints(self, operations: List[str]) -> int:\n stack=[]\n for i in operations:\n if i ==\'D\':\n stack.append(2*stack[-1])\n elif i==\'C\':\n stack.pop()\n elif i==\'+\':\n stack.appen... | 1 | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following:
* An integer `x`.
* Record a new... | null |
Easy python solution using stack | baseball-game | 0 | 1 | \n# Code\n```\nclass Solution:\n def calPoints(self, operations: List[str]) -> int:\n lst=[]\n for i in operations:\n if i=="C":\n lst.pop()\n elif i=="D":\n lst.append(lst[-1]*2)\n elif i=="+":\n sm=lst[-2]+lst[-1]\n ... | 3 | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following:
* An integer `x`.
* Record a new... | null |
baseball-game | baseball-game | 0 | 1 | \n# Code\n```\nclass Solution:\n def calPoints(self, o: List[str]) -> int:\n i = 0\n l = []\n p = []\n while i<len(o):\n if o[i]!= "C" and o[i]!= "D" and o[i]!= "+":\n l.append(int(o[i]))\n # print(l)\n elif o[i]=="C":\n l... | 1 | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following:
* An integer `x`.
* Record a new... | null |
Python Easy Solution | baseball-game | 0 | 1 | # Code\n```\nclass Solution:\n def calPoints(self, operations: List[str]) -> int:\n res=[]\n for i in operations:\n if i=="C":\n res.pop()\n elif i=="D":\n res.append(2*(res[len(res)-1]))\n elif i=="+":\n res.append(res[len(r... | 1 | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following:
* An integer `x`.
* Record a new... | null |
Easy python solution got 98%run time|| Using Stacks | baseball-game | 0 | 1 | # Code\n```\nclass Solution:\n def calPoints(self, operations: List[str]) -> int:\n lst=[]\n for i in operations:\n if i=="C":\n lst.pop()\n elif i=="D":\n lst.append(lst[-1]*2)\n elif i=="+":\n sm=lst[-2]+lst[-1]\n ... | 4 | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following:
* An integer `x`.
* Record a new... | null |
Stack Solution beats 98% | baseball-game | 0 | 1 | \n# Code\n```\nclass Solution:\n def calPoints(self, operations: List[str]) -> int:\n stack = []\n for operation in operations:\n if operation == \'+\':\n stack.append(stack[-1] + stack[-2])\n elif operation == \'D\':\n stack.append(stack[-1]*2)\n ... | 1 | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following:
* An integer `x`.
* Record a new... | null |
Easy Python🐍 code!! | baseball-game | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def calPoints(self, operations: List[str]) -> int:\n stack = []\n for i in range(len(operations)):\n if operations[i]=="D":\n stack.append(stack[-1]*2)\n elif operations[i]=="C":\n stack.pop(-1)\n elif ope... | 1 | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following:
* An integer `x`.
* Record a new... | null |
Solution | baseball-game | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int calPoints(vector<string>&o)\n {\n stack<int>s;\n for(int i=0;i<o.size();i++)\n {\n if(o[i]=="C")\n s.pop();\n else if(o[i]=="D")\n s.push(s.top()*2);\n else if(o[i]=="+")\n {\n ... | 3 | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following:
* An integer `x`.
* Record a new... | null |
Very Simple Python Solution | baseball-game | 0 | 1 | Time and Space Complexcity O(n)\n```\nclass Solution:\n def calPoints(self, operations: List[str]) -> int:\n ans=[]\n a=0\n for i in operations:\n if i=="C":\n a=ans.pop()\n elif i=="D":\n ans.append(2*ans[-1])\n elif i=="+":\n ... | 2 | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following:
* An integer `x`.
* Record a new... | null |
Baseball Game | baseball-game | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 2 | You are keeping the scores for a baseball game with strange rules. At the beginning of the game, you start with an empty record.
You are given a list of strings `operations`, where `operations[i]` is the `ith` operation you must apply to the record and is one of the following:
* An integer `x`.
* Record a new... | null |
Simple intuition explained. | redundant-connection | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWith `n` edges and `n` vertices we are guaranteed to have a cycle. To find the redundant edge we can apply the "union-find" data structure. union-find is the most optimal data structure for combining disjoint graphs. We can keep unioning ... | 1 | In this problem, a tree is an **undirected graph** that is connected and has no cycles.
You are given a graph that started as a tree with `n` nodes labeled from `1` to `n`, with one additional edge added. The added edge has two **different** vertices chosen from `1` to `n`, and was not an edge that already existed. Th... | null |
SIMPLE PYTHON SOLUTION | redundant-connection | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n$$ Disjoint Set $$\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(N)$$\n<!-- Add your s... | 1 | In this problem, a tree is an **undirected graph** that is connected and has no cycles.
You are given a graph that started as a tree with `n` nodes labeled from `1` to `n`, with one additional edge added. The added edge has two **different** vertices chosen from `1` to `n`, and was not an edge that already existed. Th... | null |
Easy union-find solution in python🐍 | redundant-connection | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def findRedundantConnection(self, edges: List[List[int]]) -> List[int]:\n parent = [i for i in range(len(edges)+1)]\n rank = [1]* (len(edges)+1)\n\n def find(n):\n temp = parent[n]\n while temp!=parent[temp]:\n temp=parent[t... | 1 | In this problem, a tree is an **undirected graph** that is connected and has no cycles.
You are given a graph that started as a tree with `n` nodes labeled from `1` to `n`, with one additional edge added. The added edge has two **different** vertices chosen from `1` to `n`, and was not an edge that already existed. Th... | null |
Python short and clean solution. DSU (Disjoint-Set-Union | Union-Find) | redundant-connection | 0 | 1 | # Approach\n1. Initialize a Disjoint-Set-Union (`DSU`) data structure.\n2. Iterate through the `edges` in the graph.\n3. Check if the edge makes a cycle by checking if the two vertices of the edge are already `connected`. If they are connected then return that edge as it is the edge that causes a cycle in the tree.\n4.... | 1 | In this problem, a tree is an **undirected graph** that is connected and has no cycles.
You are given a graph that started as a tree with `n` nodes labeled from `1` to `n`, with one additional edge added. The added edge has two **different** vertices chosen from `1` to `n`, and was not an edge that already existed. Th... | null |
Python3 | DFS | with clear explanation | redundant-connection | 0 | 1 | # Intuition\nRedundant edge will always be the one which is responsible for forming a cycle within graph. And we can be ensured that a cycle will be formed because number of edges >= number of nodes. \n\n\nLet\'s consider the input -\n[[1,2],[1,3],[2,3]]\n\nLet\'s form the graph - \n:\n def findRedundantConnection(self, edges):\n self.parent = dict()\n \n for e in edges:\n \n f0 = self.find(e[0])\n f1 = self.find(e[1])\n if f0 == f1:\n return e\n \n self.parent[f0] = ... | 1 | In this problem, a tree is an **undirected graph** that is connected and has no cycles.
You are given a graph that started as a tree with `n` nodes labeled from `1` to `n`, with one additional edge added. The added edge has two **different** vertices chosen from `1` to `n`, and was not an edge that already existed. Th... | null |
Solution | redundant-connection-ii | 1 | 1 | ```C++ []\nclass DSU{\n private:\n vector<int>parent,size;\n public:\n DSU(int n){\n parent.resize(n + 1);\n size.resize(n + 1, 1);\n for(int i = 0; i <= n; i++)\n parent[i] = i;\n }\n int findPar(int a){\n if(a == parent[a])\n... | 2 | In this problem, a rooted tree is a **directed** graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.
The given input is a directed graph that started as a rooted tree with `n... | null |
685: Solution with step by step explanation | redundant-connection-ii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nCreate a UnionFind object with a size equal to the number of edges in the input graph plus one.\n\nCreate a parent list of size n+1, initialized to all zeros.\n\nInitialize two variables candidate1 and candidate2 to None.\n\... | 4 | In this problem, a rooted tree is a **directed** graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents.
The given input is a directed graph that started as a rooted tree with `n... | null |
Solution | repeated-string-match | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n void filllps(vector<int> &lps,string B){\n lps[0] = 0;\n int len = 0;\n\n for(int i=1; i<B.size();){\n if(B[i]==B[len]) {\n len++;\n lps[i++] = len; \n }\n else {\n if(len == 0) lps[i... | 2 | Given two strings `a` and `b`, return _the minimum number of times you should repeat string_ `a` _so that string_ `b` _is a substring of it_. If it is impossible for `b` to be a substring of `a` after repeating it, return `-1`.
**Notice:** string `"abc "` repeated 0 times is `" "`, repeated 1 time is `"abc "` an... | null |
686: Solution with step by step explanation | repeated-string-match | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nCompute the number of times a needs to be repeated to have a string with length at least as long as b.\nCheck if b is a substring of the repeated a string of length n. If yes, return n.\nIf b is not a substring of a repeated... | 4 | Given two strings `a` and `b`, return _the minimum number of times you should repeat string_ `a` _so that string_ `b` _is a substring of it_. If it is impossible for `b` to be a substring of `a` after repeating it, return `-1`.
**Notice:** string `"abc "` repeated 0 times is `" "`, repeated 1 time is `"abc "` an... | null |
Python || Easy || 96.76% Faster || O(n) Solution | repeated-string-match | 0 | 1 | ```\nclass Solution:\n def repeatedStringMatch(self, a: str, b: str) -> int:\n if b in a:\n return 1\n c,n=1,len(b)\n t=a\n while b!=t and len(t)<=n:\n c+=1\n t=a*c\n if b in t:\n return c\n if b in a*(c+1):\n return c+1... | 2 | Given two strings `a` and `b`, return _the minimum number of times you should repeat string_ `a` _so that string_ `b` _is a substring of it_. If it is impossible for `b` to be a substring of `a` after repeating it, return `-1`.
**Notice:** string `"abc "` repeated 0 times is `" "`, repeated 1 time is `"abc "` an... | null |
[Python3] Knuth Morris Pratt Algorithm - O(|a| + |b|) time, O(|b|) space | repeated-string-match | 0 | 1 | View the \'a\' string as a circular object. In the normal KMP algorithm, the string \'a\' will have an end. But in this case \'a\' is circular, how do you know when to stop searching for a match? Well, you know if there exists a match, b[0] must match with one of the characters in the first copy of \'a\' (otherwise you... | 2 | Given two strings `a` and `b`, return _the minimum number of times you should repeat string_ `a` _so that string_ `b` _is a substring of it_. If it is impossible for `b` to be a substring of `a` after repeating it, return `-1`.
**Notice:** string `"abc "` repeated 0 times is `" "`, repeated 1 time is `"abc "` an... | null |
Simple C++ & Python solution with explanation | longest-univalue-path | 0 | 1 | This question is definitely not `easy` question. Its `medium` at best.\nWe will do post-order traversal to compute paths so that at each parent node there will be information about the paths from left and right child.\nWe will maintain following variables:\nglobal: `max_val` which will always have the max value.\nlocal... | 30 | Given the `root` of a binary tree, return _the length of the longest path, where each node in the path has the same value_. This path may or may not pass through the root.
**The length of the path** between two nodes is represented by the number of edges between them.
**Example 1:**
**Input:** root = \[5,4,5,1,1,nul... | null |
Solution | longest-univalue-path | 1 | 1 | ```C++ []\nclass Solution {\n int maxi;\npublic:\n int longestUnivaluePath(TreeNode* root) {\n if(!root)\n return maxi;\n DFS(root, root->val);\n return maxi-1;\n }\nprivate:\n int DFS(TreeNode* root, int prev){\n if(!root)\n return 0;\n int l = DFS(r... | 2 | Given the `root` of a binary tree, return _the length of the longest path, where each node in the path has the same value_. This path may or may not pass through the root.
**The length of the path** between two nodes is represented by the number of edges between them.
**Example 1:**
**Input:** root = \[5,4,5,1,1,nul... | null |
Recursion || Python3 | longest-univalue-path | 0 | 1 | ```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def longestUnivaluePath(self, root: Optional[TreeNode]) -> int:\n max_len = 0 \n ... | 1 | Given the `root` of a binary tree, return _the length of the longest path, where each node in the path has the same value_. This path may or may not pass through the root.
**The length of the path** between two nodes is represented by the number of edges between them.
**Example 1:**
**Input:** root = \[5,4,5,1,1,nul... | null |
687: Solution with step by step explanation | longest-univalue-path | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nInside the function, define a variable max_len and initialize it to 0.\nDefine a nested function helper that takes node and parent_val as parameters.\nIf the node is None, return 0.\nRecursively call the helper function on t... | 3 | Given the `root` of a binary tree, return _the length of the longest path, where each node in the path has the same value_. This path may or may not pass through the root.
**The length of the path** between two nodes is represented by the number of edges between them.
**Example 1:**
**Input:** root = \[5,4,5,1,1,nul... | null |
Ex-Amazon explains a solution with a video, Python, JavaScript and Java | knight-probability-in-chessboard | 1 | 1 | # Intuition\nCreating two boards and keep current and next probability.\nThis Python solution beats 92%.\n\n\n\n---\n\n# Solution Video\n... | 8 | On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`.
A chess knight has eight possible moves it can make, as illustrated below. Each move is ... | null |
EASY PYTHON SOLUTION USING DFS | knight-probability-in-chessboard | 0 | 1 | # Code\n```\nclass Solution:\n def dp(self,x,y,n,visited,k):\n if k<0:\n return 1\n if (x<0 or x>=n) or (y<0 or y>=n):\n return 0\n if (x,y,k) in visited:\n return visited[(x,y,k)]\n a=self.dp(x+2,y+1,n,visited,k-1)*1/8\n b=self.dp(x+2,y-1,n,visited... | 4 | On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`.
A chess knight has eight possible moves it can make, as illustrated below. Each move is ... | null |
🔥 [VIDEO] Conquer The Chess Knight Challenge with Python and Dynamic Programming! | knight-probability-in-chessboard | 1 | 1 | # Intuition\nWhen first approaching this problem, I thought of the knight\'s eight possible moves on a chessboard and how some of these moves can cause it to fall off the board. I recognized the probability aspect of the problem and the fact that each move the knight makes is independent of the others. This made me thi... | 2 | On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`.
A chess knight has eight possible moves it can make, as illustrated below. Each move is ... | null |
Python3 Solution | knight-probability-in-chessboard | 0 | 1 | \n```\nclass Solution:\n def knightProbability(self, n: int, k: int, row: int, column: int) -> float:\n @lru_cache(None)\n def dp(cur_r,cur_c,k):\n if k==0:\n return 1\n\n else:\n ans=0\n for r,c in moves:\n now_r=cur... | 5 | On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`.
A chess knight has eight possible moves it can make, as illustrated below. Each move is ... | null |
Python short and clean. Multiple solutions. Functional programming. | knight-probability-in-chessboard | 0 | 1 | # Approach 1:\n###### Top-Down, Recursive, Functional DP\nGiven a board `n * n`. Let `on_board_prob` be a function which returns the probability of knight to stay on the board after `k` steps, starting from row `i` and column `j`. (Exactly what the problem asks)\n\nIf `k > 0`, i.e some moves are left: Try out the `8` e... | 1 | On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`.
A chess knight has eight possible moves it can make, as illustrated below. Each move is ... | null |
10 lines Python3 | knight-probability-in-chessboard | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUse DFS and sum the probabilities of in each step.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUse DFS and cache to accelerate.\n\n# Complexity\n- Time complexity: $$O(n^2k)$$\n<!-- Add your time complexity her... | 1 | On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`.
A chess knight has eight possible moves it can make, as illustrated below. Each move is ... | null |
Python 3 || BFS in a linearised grid | Very efficient | knight-probability-in-chessboard | 0 | 1 | \n\n## Intuition\nWe use a linearised grid for fast access and low memory use.\nValue in the graph is probability to attend the case.\nWhen a knight move from a white cas... | 1 | On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`.
A chess knight has eight possible moves it can make, as illustrated below. Each move is ... | null |
Python | DFS | Easy to Understand | Optimal Solution | 688. Knight Probability in Chessboard | knight-probability-in-chessboard | 0 | 1 | # Python | DFS | Easy to Understand | Optimal Solution | Medium Problem | 688. Knight Probability in Chessboard\n```\nclass Solution:\n def knightProbability(self, n: int, k: int, row: int, column: int) -> float:\n if k == 0:\n return 1\n\n @cache\n def dfs(r: int, c: int, cur_moves: ... | 1 | On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`.
A chess knight has eight possible moves it can make, as illustrated below. Each move is ... | null |
✅DP + Memoization || JAVA/C++/Python Beginner Friendly🔥🔥🔥 | knight-probability-in-chessboard | 1 | 1 | # Approach\nThe `knightProbability` function initializes a memoization array `memo`, and then calls the recursive function `dp`. The dp function calculates the probability of the knight remaining on the board after k moves from a given position. It considers all eight possible moves and recursively calls itself for eac... | 1 | On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`.
A chess knight has eight possible moves it can make, as illustrated below. Each move is ... | null |
[Python3] Two Different Techniques. Double The Fun. | knight-probability-in-chessboard | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOne can solve this problem with either of these techniques.\n1. Dynamic Programming - DP[i][j] means the probability for a knight to stay on board with index (i, j). \n2. Graph with DFS - Construct an adjacency list of all indexes that a ... | 1 | On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`.
A chess knight has eight possible moves it can make, as illustrated below. Each move is ... | null |
Very Simple DP Soultion | knight-probability-in-chessboard | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe just needs to count the number times the knight will end up in board after all the moves and divide it by total possible moves.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nThe base condition would be we have... | 1 | On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are **0-indexed**, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`.
A chess knight has eight possible moves it can make, as illustrated below. Each move is ... | null |
689: Solution with step by step explanation | maximum-sum-of-3-non-overlapping-subarrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Get the length of the input list nums.\n2. Create an array sums to store the sums of all possible subarrays of length k in nums. The array will have length n - k + 1.\n3. Loop through the indices i of sums, where i ranges... | 1 | Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (**0-indexed**). If there are multiple answers, return the lexicographically smallest one.
*... | null |
Standard Python Knapsack DP -- generalized max_sum_of_d_subarrays | maximum-sum-of-3-non-overlapping-subarrays | 0 | 1 | key idea:\n- calculate all subarray sums efficiently, select d (or 3 in this case) with the largest sum such that they don\'t overlap\n- "calculate all subarray sums efficiently" should imply prefix sums\n- "select d elements such that X" should imply knapsack\n\n```python\nclass Solution:\n def maxSumOfThreeSubarra... | 2 | Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (**0-indexed**). If there are multiple answers, return the lexicographically smallest one.
*... | null |
Python 3 || 10 lines, prefix sum, zip || T/S: 100% / 98% | maximum-sum-of-3-non-overlapping-subarrays | 0 | 1 | Here\'s the plan:\n\n- We use `acc`, a prefix-sum array, in lieu of a sliding window.\n\n- We iterate though an enumerated zip to determine the sums of three contiguous subarrays starting at index `i`. The three subarrays are demarcated by `a0, a1, a2, a3`.\n\n- We initialize and update `sm1`, `sm2`, `sm3` to keep trac... | 4 | Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (**0-indexed**). If there are multiple answers, return the lexicographically smallest one.
*... | null |
Python top down DP in various forms | maximum-sum-of-3-non-overlapping-subarrays | 0 | 1 | If you\'re like me, you probably didn\'t easily understand the problem, or understand the greedy window solutions. A more intuitive approach is outlined below. Maybe this is one you might actually be able to remember in an interview.\n\n**Brute force**\nThis will TLE but it helps to see the brute force and how it might... | 16 | Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (**0-indexed**). If there are multiple answers, return the lexicographically smallest one.
*... | null |
Solution | maximum-sum-of-3-non-overlapping-subarrays | 1 | 1 | ```C++ []\n#include<iostream>\nusing namespace std;\n\nclass Solution {\npublic:\n vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) {\n int n = nums.size()-k+1;\n int subArraySum[n];\n subArraySum[0] = 0;\n for (int i = 0; i < k; i++)\n subArraySum[0] += nums[i];\n ... | 3 | Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (**0-indexed**). If there are multiple answers, return the lexicographically smallest one.
*... | null |
Generalized DP Solution - Maximum of N Non Overlapping Subarrays with length K | maximum-sum-of-3-non-overlapping-subarrays | 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:\nO(m*n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\nO(m*n)\n<!-- Add your space complexity here, ... | 0 | Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (**0-indexed**). If there are multiple answers, return the lexicographically smallest one.
*... | null |
General DP Solution | maximum-sum-of-3-non-overlapping-subarrays | 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- O(n*k)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(n*K)\n<!-- Add your space complexity he... | 0 | Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (**0-indexed**). If there are multiple answers, return the lexicographically smallest one.
*... | null |
DP, O(n) here but generalizes to any k | maximum-sum-of-3-non-overlapping-subarrays | 0 | 1 | # Intuition\nThis is a typical dynamic programming question: at every index `i`, we can either use the last k-sized array ending at `i` or skip it. Some additional tricks are that: \n- We store the locations of the 3 arrays in the dp table itself. \n- We use cumulative sums to precompute the sums of the subarrays.\n\n#... | 0 | Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (**0-indexed**). If there are multiple answers, return the lexicographically smallest one.
*... | null |
Time: O(n)O(n) Space: O(n)O(n) | maximum-sum-of-3-non-overlapping-subarrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --... | 0 | Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (**0-indexed**). If there are multiple answers, return the lexicographically smallest one.
*... | null |
Sliding Windows and Lexicographic Indexing | Commented and Explained | maximum-sum-of-3-non-overlapping-subarrays | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe want to keep track of all of the sliding window subarrays of size k in our array. So, we want to set up a list of windows in order index wise. We then want to track arrays going from left to right by sum and find the strictly best firs... | 0 | Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (**0-indexed**). If there are multiple answers, return the lexicographically smallest one.
*... | null |
[Python] Generic K Non overlapping Subarrays DP | Clean | maximum-sum-of-3-non-overlapping-subarrays | 0 | 1 | \n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(N)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(N)$$\n\n# Code\n```\nclass Solution:\n def maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]:\n K,n = 3,len(num... | 0 | Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them.
Return the result as a list of indices representing the starting position of each interval (**0-indexed**). If there are multiple answers, return the lexicographically smallest one.
*... | null |
97% Readable Python DFS | employee-importance | 0 | 1 | # Intuition\nThis is a graph problem, where there is a directed edge between an employee and their subordinate; specifically, this is a tree. We can solve this with DFS and just keep a running sum of the importance values.\n\n# Approach\nThe non-trivial part is defining the graph. I assumed earlier that the index posit... | 0 | You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.
You are given an array of employees `employees` where:
* `employees[i].id` is the ID of the `ith` employee.
* `employees[i].importance` is the importance value of the `ith` employ... | null |
690: Time 98.69% and Space 100%, Solution with step by step explanation | employee-importance | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Define a class called Employee with attributes: id, importance, and subordinates.\n2. Define a class called Solution.\n3. In the Solution class, define a method called getImportance that takes two arguments: employees (a ... | 2 | You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.
You are given an array of employees `employees` where:
* `employees[i].id` is the ID of the `ith` employee.
* `employees[i].importance` is the importance value of the `ith` employ... | null |
Python, a short and easy DFS solution. | employee-importance | 0 | 1 | ```\nclass Solution:\n def getImportance(self, employees: List[\'Employee\'], id: int) -> int:\n def dfs(emp):\n imp = emps[emp].importance \n for s in emps[emp].subordinates:\n imp += dfs(s)\n return imp\n \n emps= {emp.id: emp for emp ... | 17 | You have a data structure of employee information, including the employee's unique ID, importance value, and direct subordinates' IDs.
You are given an array of employees `employees` where:
* `employees[i].id` is the ID of the `ith` employee.
* `employees[i].importance` is the importance value of the `ith` employ... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.