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 |
|---|---|---|---|---|---|---|---|
Solution | powerful-integers | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n vector<int> powerfulIntegers(int x, int y, int bound) {\n vector<int>powx;\n vector<int>powy;\n powx.push_back(1);\n powy.push_back(1);\n if(x!=1){\n int pow=x;\n while(pow<bound){\n powx.push_back(pow);\n ... | 1 | You are given a list of songs where the `ith` song has a duration of `time[i]` seconds.
Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`.
**Example 1:**
**Input... | null |
970. Powerful Integers | powerful-integers | 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 three integers `x`, `y`, and `bound`, return _a list of all the **powerful integers** that have a value less than or equal to_ `bound`.
An integer is **powerful** if it can be represented as `xi + yj` for some integers `i >= 0` and `j >= 0`.
You may return the answer in **any order**. In your answer, each value... | null |
970. Powerful Integers | powerful-integers | 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 list of songs where the `ith` song has a duration of `time[i]` seconds.
Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`.
**Example 1:**
**Input... | null |
[Python3] Brutal Force | powerful-integers | 0 | 1 | # Code\n```\nclass Solution:\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n x_max = 0\n while x!=1 and x**x_max < bound:\n x_max+=1\n \n y_max = 0\n while y!=1 and y**y_max < bound:\n y_max+=1\n \n hs = set()\n fo... | 0 | Given three integers `x`, `y`, and `bound`, return _a list of all the **powerful integers** that have a value less than or equal to_ `bound`.
An integer is **powerful** if it can be represented as `xi + yj` for some integers `i >= 0` and `j >= 0`.
You may return the answer in **any order**. In your answer, each value... | null |
[Python3] Brutal Force | powerful-integers | 0 | 1 | # Code\n```\nclass Solution:\n def powerfulIntegers(self, x: int, y: int, bound: int) -> List[int]:\n x_max = 0\n while x!=1 and x**x_max < bound:\n x_max+=1\n \n y_max = 0\n while y!=1 and y**y_max < bound:\n y_max+=1\n \n hs = set()\n fo... | 0 | You are given a list of songs where the `ith` song has a duration of `time[i]` seconds.
Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`.
**Example 1:**
**Input... | null |
[35ms] Use min heap to find minimum sum 1 by 1 | powerful-integers | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nincrease i and j by 1 to find minimum sum till over-bound\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. use a min-heap q to store sum and i,j with tuple (v, i, j)\n2. use a seen set to store (i, j) avoiding re... | 0 | Given three integers `x`, `y`, and `bound`, return _a list of all the **powerful integers** that have a value less than or equal to_ `bound`.
An integer is **powerful** if it can be represented as `xi + yj` for some integers `i >= 0` and `j >= 0`.
You may return the answer in **any order**. In your answer, each value... | null |
[35ms] Use min heap to find minimum sum 1 by 1 | powerful-integers | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nincrease i and j by 1 to find minimum sum till over-bound\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. use a min-heap q to store sum and i,j with tuple (v, i, j)\n2. use a seen set to store (i, j) avoiding re... | 0 | You are given a list of songs where the `ith` song has a duration of `time[i]` seconds.
Return _the number of pairs of songs for which their total duration in seconds is divisible by_ `60`. Formally, we want the number of indices `i`, `j` such that `i < j` with `(time[i] + time[j]) % 60 == 0`.
**Example 1:**
**Input... | null |
Solution | flip-binary-tree-to-match-preorder-traversal | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n bool helper(int &ind, TreeNode *root, vector<int> &voyage, vector<int> &ans){\n if(root == NULL || ind == voyage.size()){\n ind--;\n return true;\n }\n if(root->val != voyage[ind]){\n ans.clear();\n ans.push_back(-... | 1 | You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree.
Any node in the bi... | null |
Solution | flip-binary-tree-to-match-preorder-traversal | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n bool helper(int &ind, TreeNode *root, vector<int> &voyage, vector<int> &ans){\n if(root == NULL || ind == voyage.size()){\n ind--;\n return true;\n }\n if(root->val != voyage[ind]){\n ans.clear();\n ans.push_back(-... | 1 | A conveyor belt has packages that must be shipped from one port to another within `days` days.
The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capaci... | null |
Python3 Clear Solution with stack | Pre-Order Traversal | flip-binary-tree-to-match-preorder-traversal | 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 the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree.
Any node in the bi... | null |
Python3 Clear Solution with stack | Pre-Order Traversal | flip-binary-tree-to-match-preorder-traversal | 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 | A conveyor belt has packages that must be shipped from one port to another within `days` days.
The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capaci... | null |
Simple Python DFS Explained | Beats 97 % | flip-binary-tree-to-match-preorder-traversal | 0 | 1 | # Intuition\nProrder Traversal -> mid , left, right\nWe are given that any point of time we can flip the binary tree. This rises three cases\n`1. flip is not required`\n`2. flip is required -> add the root node of the subtree in ans`\n`3. even with and without flipping cant match the pattern return -1`\n\n***So how to ... | 0 | You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree.
Any node in the bi... | null |
Simple Python DFS Explained | Beats 97 % | flip-binary-tree-to-match-preorder-traversal | 0 | 1 | # Intuition\nProrder Traversal -> mid , left, right\nWe are given that any point of time we can flip the binary tree. This rises three cases\n`1. flip is not required`\n`2. flip is required -> add the root node of the subtree in ans`\n`3. even with and without flipping cant match the pattern return -1`\n\n***So how to ... | 0 | A conveyor belt has packages that must be shipped from one port to another within `days` days.
The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capaci... | null |
Use DFS | flip-binary-tree-to-match-preorder-traversal | 0 | 1 | ```\nclass Solution:\n def flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]:\n self.flips = []\n self.index = 0\n\n def dfs(root):\n if root:\n if root.val != voyage[self.index]:\n self.flips = [-1]\n ... | 0 | You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree.
Any node in the bi... | null |
Use DFS | flip-binary-tree-to-match-preorder-traversal | 0 | 1 | ```\nclass Solution:\n def flipMatchVoyage(self, root: Optional[TreeNode], voyage: List[int]) -> List[int]:\n self.flips = []\n self.index = 0\n\n def dfs(root):\n if root:\n if root.val != voyage[self.index]:\n self.flips = [-1]\n ... | 0 | A conveyor belt has packages that must be shipped from one port to another within `days` days.
The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capaci... | null |
Python3 🐍 concise solution beats 99% | flip-binary-tree-to-match-preorder-traversal | 0 | 1 | \n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def traverse(self,node,index,n):\n res = []\n if not node: \n ... | 0 | You are given the `root` of a binary tree with `n` nodes, where each node is uniquely assigned a value from `1` to `n`. You are also given a sequence of `n` values `voyage`, which is the **desired** [**pre-order traversal**](https://en.wikipedia.org/wiki/Tree_traversal#Pre-order) of the binary tree.
Any node in the bi... | null |
Python3 🐍 concise solution beats 99% | flip-binary-tree-to-match-preorder-traversal | 0 | 1 | \n# Code\n```\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def traverse(self,node,index,n):\n res = []\n if not node: \n ... | 0 | A conveyor belt has packages that must be shipped from one port to another within `days` days.
The `ith` package on the conveyor belt has a weight of `weights[i]`. Each day, we load the ship with packages on the conveyor belt (in the order given by `weights`). We may not load more weight than the maximum weight capaci... | null |
Solution | equal-rational-numbers | 1 | 1 | ```C++ []\nclass Solution {\n public:\n bool isRationalEqual(string S, string T) {\n return abs(valueOf(S) - valueOf(T)) < 1e-9;\n }\n private:\n vector<double> ratios{1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999};\n\n double valueOf(const string& s) {\n if (s.find(\'(\') == string::npos)\n return stod(... | 2 | Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.
A **rational number** can be represented using up to three parts: , , and a . The num... | null |
Solution | equal-rational-numbers | 1 | 1 | ```C++ []\nclass Solution {\n public:\n bool isRationalEqual(string S, string T) {\n return abs(valueOf(S) - valueOf(T)) < 1e-9;\n }\n private:\n vector<double> ratios{1.0, 1.0 / 9, 1.0 / 99, 1.0 / 999, 1.0 / 9999};\n\n double valueOf(const string& s) {\n if (s.find(\'(\') == string::npos)\n return stod(... | 2 | Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_.
**Example 1:**
**Input:** n = 20
**Output:** 1
**Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11.
**Example 2:**
**Input:** n = 100
**Output:** 10
**... | null |
[Python3] Solution with explanation | equal-rational-numbers | 0 | 1 | The main idea is to represent strings as **float** numbers, and then **rounding** down and comparing with each other.\nFirst we **separate** the periodic part of the fraction, then **remove** the brackets from the string. Finally, we add the periodic part to the end of the string several times (8) in order to avoid err... | 2 | Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.
A **rational number** can be represented using up to three parts: , , and a . The num... | null |
[Python3] Solution with explanation | equal-rational-numbers | 0 | 1 | The main idea is to represent strings as **float** numbers, and then **rounding** down and comparing with each other.\nFirst we **separate** the periodic part of the fraction, then **remove** the brackets from the string. Finally, we add the periodic part to the end of the string several times (8) in order to avoid err... | 2 | Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_.
**Example 1:**
**Input:** n = 20
**Output:** 1
**Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11.
**Example 2:**
**Input:** n = 100
**Output:** 10
**... | null |
Mainly to do with string parsing and special cases | equal-rational-numbers | 0 | 1 | # Intuition\nSeems like we just need to parse the strings and handle the special cases -- particularly the one mentioned in the description about .(9) converging to 1.\n\n# Approach\nDivide and conquer, and do it all with string manipulation. First parse out the constituent integer, non-repeating decimal, and repeating... | 0 | Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.
A **rational number** can be represented using up to three parts: , , and a . The num... | null |
Mainly to do with string parsing and special cases | equal-rational-numbers | 0 | 1 | # Intuition\nSeems like we just need to parse the strings and handle the special cases -- particularly the one mentioned in the description about .(9) converging to 1.\n\n# Approach\nDivide and conquer, and do it all with string manipulation. First parse out the constituent integer, non-repeating decimal, and repeating... | 0 | Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_.
**Example 1:**
**Input:** n = 20
**Output:** 1
**Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11.
**Example 2:**
**Input:** n = 100
**Output:** 10
**... | null |
Python3 🐍 concise solution beats 99% | equal-rational-numbers | 0 | 1 | # Code\n```\nclass Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n \n def fn(s):\n """Return normalized string."""\n if "." not in s: return s # edge case - xxx \n xxx, frac = s.split(\'.\')\n if not frac: return xxx # edge case - xxx.\n ... | 0 | Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.
A **rational number** can be represented using up to three parts: , , and a . The num... | null |
Python3 🐍 concise solution beats 99% | equal-rational-numbers | 0 | 1 | # Code\n```\nclass Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n \n def fn(s):\n """Return normalized string."""\n if "." not in s: return s # edge case - xxx \n xxx, frac = s.split(\'.\')\n if not frac: return xxx # edge case - xxx.\n ... | 0 | Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_.
**Example 1:**
**Input:** n = 20
**Output:** 1
**Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11.
**Example 2:**
**Input:** n = 100
**Output:** 10
**... | null |
Fraction Expansion using Stack python | equal-rational-numbers | 0 | 1 | I just expanded the fraction then truncated it and compared the float value of each. \n\n```py\nclass Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n repeat = 1000\n \n res = []\n \n for word in (s, t):\n stack = []\n for char in word... | 0 | Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.
A **rational number** can be represented using up to three parts: , , and a . The num... | null |
Fraction Expansion using Stack python | equal-rational-numbers | 0 | 1 | I just expanded the fraction then truncated it and compared the float value of each. \n\n```py\nclass Solution:\n def isRationalEqual(self, s: str, t: str) -> bool:\n repeat = 1000\n \n res = []\n \n for word in (s, t):\n stack = []\n for char in word... | 0 | Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_.
**Example 1:**
**Input:** n = 20
**Output:** 1
**Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11.
**Example 2:**
**Input:** n = 100
**Output:** 10
**... | null |
Python 3 (beats ~99%) (six lines) | equal-rational-numbers | 0 | 1 | ```\nclass Solution:\n def isRationalEqual(self, S: str, T: str) -> bool:\n L, A = [len(S), len(T)], [S,T]\n for i,p in enumerate([S,T]):\n if \'(\' in p:\n I = p.index(\'(\')\n A[i] = p[0:I] + 7*p[I+1:L[i]-1]\n return abs(float(A[0])-float(A[1])) < 1E-7\... | 1 | Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.
A **rational number** can be represented using up to three parts: , , and a . The num... | null |
Python 3 (beats ~99%) (six lines) | equal-rational-numbers | 0 | 1 | ```\nclass Solution:\n def isRationalEqual(self, S: str, T: str) -> bool:\n L, A = [len(S), len(T)], [S,T]\n for i,p in enumerate([S,T]):\n if \'(\' in p:\n I = p.index(\'(\')\n A[i] = p[0:I] + 7*p[I+1:L[i]-1]\n return abs(float(A[0])-float(A[1])) < 1E-7\... | 1 | Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_.
**Example 1:**
**Input:** n = 20
**Output:** 1
**Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11.
**Example 2:**
**Input:** n = 100
**Output:** 10
**... | null |
Python solution with extra class | equal-rational-numbers | 0 | 1 | ```\nclass frac:\n def __init__(self, num, denom):\n self.num = num\n self.denom = denom\n\n def __add__(self, other):\n a = self.num * other.denom + other.num * self.denom\n b = self.denom * other.denom\n gcd = self.hcf(a, b)\n\n self.num = a // gcd\n self.denom =... | 0 | Given two strings `s` and `t`, each of which represents a non-negative rational number, return `true` if and only if they represent the same number. The strings may use parentheses to denote the repeating part of the rational number.
A **rational number** can be represented using up to three parts: , , and a . The num... | null |
Python solution with extra class | equal-rational-numbers | 0 | 1 | ```\nclass frac:\n def __init__(self, num, denom):\n self.num = num\n self.denom = denom\n\n def __add__(self, other):\n a = self.num * other.denom + other.num * self.denom\n b = self.denom * other.denom\n gcd = self.hcf(a, b)\n\n self.num = a // gcd\n self.denom =... | 0 | Given an integer `n`, return _the number of positive integers in the range_ `[1, n]` _that have **at least one** repeated digit_.
**Example 1:**
**Input:** n = 20
**Output:** 1
**Explanation:** The only positive number (<= 20) with at least 1 repeated digit is 11.
**Example 2:**
**Input:** n = 100
**Output:** 10
**... | null |
Easy to read Python min heap solution ( beat 99% python solutions ) | k-closest-points-to-origin | 0 | 1 | We keep a min heap of size K.\nFor each item, we insert an item to our heap.\nIf inserting an item makes heap size larger than k, then we immediately pop an item after inserting ( `heappushpop` ).\n\nRuntime: \nInserting an item to a heap of size k take `O(logK)` time.\nAnd we do this for each item points.\nSo runtime ... | 332 | Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`.
The distance between two points on the **X-Y** plane is the Euclidean distance (i.e., `√(x1 - x2)2 + (y1 - y2)2`).
You may return the answer in **an... | null |
Easy to read Python min heap solution ( beat 99% python solutions ) | k-closest-points-to-origin | 0 | 1 | We keep a min heap of size K.\nFor each item, we insert an item to our heap.\nIf inserting an item makes heap size larger than k, then we immediately pop an item after inserting ( `heappushpop` ).\n\nRuntime: \nInserting an item to a heap of size k take `O(logK)` time.\nAnd we do this for each item points.\nSo runtime ... | 332 | You are given an integer array `values` where values\[i\] represents the value of the `ith` sightseeing spot. Two sightseeing spots `i` and `j` have a **distance** `j - i` between them.
The score of a pair (`i < j`) of sightseeing spots is `values[i] + values[j] + i - j`: the sum of the values of the sightseeing spots... | null |
Easy to Understand Well Commented Python Code | k-closest-points-to-origin | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. We are calculating the distance of every point from orgin using the\ndistance formula.\n2. Sorting the values on the basis of their distance from Orign in ascending order using lambda function.\n3. Finally getting the ... | 1 | Given an array of `points` where `points[i] = [xi, yi]` represents a point on the **X-Y** plane and an integer `k`, return the `k` closest points to the origin `(0, 0)`.
The distance between two points on the **X-Y** plane is the Euclidean distance (i.e., `√(x1 - x2)2 + (y1 - y2)2`).
You may return the answer in **an... | null |
Easy to Understand Well Commented Python Code | k-closest-points-to-origin | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. We are calculating the distance of every point from orgin using the\ndistance formula.\n2. Sorting the values on the basis of their distance from Orign in ascending order using lambda function.\n3. Finally getting the ... | 1 | You are given an integer array `values` where values\[i\] represents the value of the `ith` sightseeing spot. Two sightseeing spots `i` and `j` have a **distance** `j - i` between them.
The score of a pair (`i < j`) of sightseeing spots is `values[i] + values[j] + i - j`: the sum of the values of the sightseeing spots... | null |
[Python] O(N) 1 Liner solution, Prefix sum | subarray-sums-divisible-by-k | 0 | 1 | # Complexity\n- Time complexity: O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nfrom collections import Counter\nfrom itertools import accumulate\n\nclass Solution:\n def subarraysDivByK(self, nums: List[... | 1 | Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible b... | null |
Python | Prefix Mod Sum | O(n) | subarray-sums-divisible-by-k | 0 | 1 | # Code\n```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n cur = 0\n counter = Counter()\n for num in nums:\n cur = (cur + num) % k\n counter[cur] += 1\n res = 0\n for e in counter:\n res += counter[e]*(counter[e]-1)... | 1 | Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible b... | null |
Python Simple Solution using Dictionary | subarray-sums-divisible-by-k | 0 | 1 | ```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n cur, count, d = 0, 0, defaultdict(int, {0:1})\n for i in nums:\n cur += i \n rem = cur % k\n count += d[rem]\n d[rem]+=1\n return count\n \n``` | 1 | Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible b... | null |
Faster than 99% | subarray-sums-divisible-by-k | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIt suffices to compute all partial sums starting at 0 and see how many have the same remainder modulo k.\nIf l partial sums have the same remainder modulo k, this corresponds to l(l-1)/2 subarrays whose sum is divisible by k.\n\n# Approac... | 1 | Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible b... | null |
Python faster than 99.8%, linear, combinations without repetition | subarray-sums-divisible-by-k | 0 | 1 | # Intuition\nIt is based on a prefix sums solutions. The intuition bases on the fact two arrays which are divisible by $$k$$ can only differ by elements that sum up to a number also divisible by $$k$$.\n\n##### Example\nGiven an array $$[4,5,0,-2,-3,1]$$ and $$k=5$$ we know that the whole array is divisible by $$k$$. W... | 1 | Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible b... | null |
Python (Prefix sums + Hashmap) 0(N) | subarray-sums-divisible-by-k | 0 | 1 | # Code\n```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n ans=0\n d=defaultdict(lambda:0)\n nums=list(accumulate(nums))\n for i in range(len(nums)):\n nums[i]=((k+nums[i]%k) if nums[i]<0 else (nums[i]%k))%k\n d[0]+=1\n for i in nu... | 1 | Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible b... | null |
Easy python solution | subarray-sums-divisible-by-k | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n count = 0\n s = 0\n sum_map = {}\n for i in nums:\n s+=i \n s= s%k\n if s in sum_map:\n sum_map[s]+=1\n else:\n sum_map... | 1 | Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible b... | null |
Python3 One Pass Solution | subarray-sums-divisible-by-k | 0 | 1 | \n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n pref_sums = [0] * k\n count =... | 1 | Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible b... | null |
Python Easy solution || Beats 90% || Time complex O(n) | subarray-sums-divisible-by-k | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)... | 1 | Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible b... | null |
Brute Force to Optimised intuition . | subarray-sums-divisible-by-k | 0 | 1 | # Intuition\n**Bruteforce to Optimization** \n\n- The na\xEFve bruteforce solution would be - for all possible subarray start and end indexes, calculate the sum. So, the algorithm becomes O(n3).\n- We can optimize this using the prefix sum idea. SubarraySum(i,j)=PrefixSum(j)\u2212PrefixSum(i\u22121) This reduces the ti... | 1 | Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible b... | null |
prefixSum || Easiest || | subarray-sums-divisible-by-k | 0 | 1 | \n\n# Code\n```\nimport math\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n freq_ar=[0]*k\n freq_ar[0]=1\n sum=0\n count=0\n for no in range(len(nums)):\n sum+=nums[no]\n remainder=sum%k\n if remainder<0:\n ... | 1 | Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible b... | null |
My Python Solution | subarray-sums-divisible-by-k | 0 | 1 | \n\n# What is prefix sum?\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- What is prefix sum?\n\nprefix sum also called cumulative sum, is an array with the same size as the original array, where the ith element represents the sum of the elements in the origianl array up to the ith positio... | 1 | Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible b... | null |
Python Easy Solution | subarray-sums-divisible-by-k | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def subarraysDivByK(self, nums: List[int], k: int) -> int:\n # frequency table to store the frequency of the remainder\n remainderFrq = defaultdict(int)\n # Empty sub array will have a sum of 0 and remainder of 0, thus the frequency of 0 is 1 before we go into ... | 1 | Given an integer array `nums` and an integer `k`, return _the number of non-empty **subarrays** that have a sum divisible by_ `k`.
A **subarray** is a **contiguous** part of an array.
**Example 1:**
**Input:** nums = \[4,5,0,-2,-3,1\], k = 5
**Output:** 7
**Explanation:** There are 7 subarrays with a sum divisible b... | null |
Solution | odd-even-jump | 1 | 1 | ```C++ []\nconst int FAIL_LO=-1, FAIL_HI=1e5+1;\nint dp[2][20001];\nclass Solution {\npublic:\n int oddEvenJumps(vector<int>& arr) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int n=arr.size(), ans=1;\n map<int, int> sts;\n map<int, int>::iterator it;\n sts[arr[n-1... | 438 | You are given an integer array `arr`. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called **odd-numbered jumps**, and the (2nd, 4th, 6th, ...) jumps in the series are called **even-numbered jumps**. Note that the **jumps** are numbered, not the indices.
You... | null |
Solution | odd-even-jump | 1 | 1 | ```C++ []\nconst int FAIL_LO=-1, FAIL_HI=1e5+1;\nint dp[2][20001];\nclass Solution {\npublic:\n int oddEvenJumps(vector<int>& arr) {\n ios::sync_with_stdio(false);\n cin.tie(nullptr);\n int n=arr.size(), ans=1;\n map<int, int> sts;\n map<int, int>::iterator it;\n sts[arr[n-1... | 438 | Given an integer `n`, return _a binary string representing its representation in base_ `-2`.
**Note** that the returned string should not have leading zeros unless the string is `"0 "`.
**Example 1:**
**Input:** n = 2
**Output:** "110 "
**Explantion:** (-2)2 + (-2)1 = 2
**Example 2:**
**Input:** n = 3
**Output:**... | null |
Monotonic Stacks and Size Ordering Of Indices | odd-even-jump | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can build the correctly ordered sorted indices of the array based on increasing and decreasing size for the odd and even styled jumps by sorting based on their actual values for the index keys. This lets us generate abstracted versions... | 1 | You are given an integer array `arr`. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called **odd-numbered jumps**, and the (2nd, 4th, 6th, ...) jumps in the series are called **even-numbered jumps**. Note that the **jumps** are numbered, not the indices.
You... | null |
Monotonic Stacks and Size Ordering Of Indices | odd-even-jump | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can build the correctly ordered sorted indices of the array based on increasing and decreasing size for the odd and even styled jumps by sorting based on their actual values for the index keys. This lets us generate abstracted versions... | 1 | Given an integer `n`, return _a binary string representing its representation in base_ `-2`.
**Note** that the returned string should not have leading zeros unless the string is `"0 "`.
**Example 1:**
**Input:** n = 2
**Output:** "110 "
**Explantion:** (-2)2 + (-2)1 = 2
**Example 2:**
**Input:** n = 3
**Output:**... | null |
Python O(nlogn) bottom-up DP easy to understand 260ms | odd-even-jump | 0 | 1 | ```\nclass Solution:\n def oddEvenJumps(self, A: List[int]) -> int:\n \n\t\t# find next index of current index that is the least larger/smaller\n def getNextIndex(sortedIdx):\n stack = []\n result = [None] * len(sortedIdx)\n \n for i in sortedIdx:\n ... | 13 | You are given an integer array `arr`. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called **odd-numbered jumps**, and the (2nd, 4th, 6th, ...) jumps in the series are called **even-numbered jumps**. Note that the **jumps** are numbered, not the indices.
You... | null |
Python O(nlogn) bottom-up DP easy to understand 260ms | odd-even-jump | 0 | 1 | ```\nclass Solution:\n def oddEvenJumps(self, A: List[int]) -> int:\n \n\t\t# find next index of current index that is the least larger/smaller\n def getNextIndex(sortedIdx):\n stack = []\n result = [None] * len(sortedIdx)\n \n for i in sortedIdx:\n ... | 13 | Given an integer `n`, return _a binary string representing its representation in base_ `-2`.
**Note** that the returned string should not have leading zeros unless the string is `"0 "`.
**Example 1:**
**Input:** n = 2
**Output:** "110 "
**Explantion:** (-2)2 + (-2)1 = 2
**Example 2:**
**Input:** n = 3
**Output:**... | null |
[Python3] dp | odd-even-jump | 0 | 1 | \n```\nclass Solution:\n def oddEvenJumps(self, arr: List[int]) -> int:\n large = [-1] * len(arr)\n small = [-1] * len(arr)\n \n stack = []\n for i, x in sorted(enumerate(arr), key=lambda x: (x[1], x[0])): \n while stack and stack[-1] < i: large[stack.pop()] = i \n ... | 4 | You are given an integer array `arr`. From some starting index, you can make a series of jumps. The (1st, 3rd, 5th, ...) jumps in the series are called **odd-numbered jumps**, and the (2nd, 4th, 6th, ...) jumps in the series are called **even-numbered jumps**. Note that the **jumps** are numbered, not the indices.
You... | null |
[Python3] dp | odd-even-jump | 0 | 1 | \n```\nclass Solution:\n def oddEvenJumps(self, arr: List[int]) -> int:\n large = [-1] * len(arr)\n small = [-1] * len(arr)\n \n stack = []\n for i, x in sorted(enumerate(arr), key=lambda x: (x[1], x[0])): \n while stack and stack[-1] < i: large[stack.pop()] = i \n ... | 4 | Given an integer `n`, return _a binary string representing its representation in base_ `-2`.
**Note** that the returned string should not have leading zeros unless the string is `"0 "`.
**Example 1:**
**Input:** n = 2
**Output:** "110 "
**Explantion:** (-2)2 + (-2)1 = 2
**Example 2:**
**Input:** n = 3
**Output:**... | null |
Python: A comparison of lots of approaches! [Sorting, two pointers, deque, iterator, generator] | squares-of-a-sorted-array | 0 | 1 | This question is a cool one in that there is lots of different approaches, each with its own pros and cons. And then there\'s also different ways of implementing them, depending on whether you are after raw performance or beautiful code.\n\nSomething slightly irritating is that leetcode isn\'t testing with big enough t... | 552 | Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_.
**Example 1:**
**Input:** nums = \[-4,-1,0,3,10\]
**Output:** \[0,1,9,16,100\]
**Explanation:** After squaring, the array becomes \[16,1,0,9,100\].
After sorting, it be... | null |
Python: A comparison of lots of approaches! [Sorting, two pointers, deque, iterator, generator] | squares-of-a-sorted-array | 0 | 1 | This question is a cool one in that there is lots of different approaches, each with its own pros and cons. And then there\'s also different ways of implementing them, depending on whether you are after raw performance or beautiful code.\n\nSomething slightly irritating is that leetcode isn\'t testing with big enough t... | 552 | You are given the `head` of a linked list with `n` nodes.
For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it.
Return an integer array `answer` where `answer[i]` is the value of ... | null |
Python3 solution (runtime is faster than 94.92%, memory is less than 49.24%) | squares-of-a-sorted-array | 0 | 1 | Hi everyone. In my solution I used lambda functions because I wanted to make the solution shorter.\nSurprisingly, after a successfull run, it became faster than the most submitted.\nHere you are.\n```\n def sortedSquares(self, nums: List[int]) -> List[int]:\n sq_nums = list(map(lambda n: n**2, nums))\n ... | 2 | Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_.
**Example 1:**
**Input:** nums = \[-4,-1,0,3,10\]
**Output:** \[0,1,9,16,100\]
**Explanation:** After squaring, the array becomes \[16,1,0,9,100\].
After sorting, it be... | null |
Python3 solution (runtime is faster than 94.92%, memory is less than 49.24%) | squares-of-a-sorted-array | 0 | 1 | Hi everyone. In my solution I used lambda functions because I wanted to make the solution shorter.\nSurprisingly, after a successfull run, it became faster than the most submitted.\nHere you are.\n```\n def sortedSquares(self, nums: List[int]) -> List[int]:\n sq_nums = list(map(lambda n: n**2, nums))\n ... | 2 | You are given the `head` of a linked list with `n` nodes.
For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it.
Return an integer array `answer` where `answer[i]` is the value of ... | null |
with out loops Square of a sorted array | squares-of-a-sorted-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 | Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_.
**Example 1:**
**Input:** nums = \[-4,-1,0,3,10\]
**Output:** \[0,1,9,16,100\]
**Explanation:** After squaring, the array becomes \[16,1,0,9,100\].
After sorting, it be... | null |
with out loops Square of a sorted array | squares-of-a-sorted-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 are given the `head` of a linked list with `n` nodes.
For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it.
Return an integer array `answer` where `answer[i]` is the value of ... | null |
Python | one line of code | and Two pointers | squares-of-a-sorted-array | 0 | 1 | **One line of code**\n\n\tclass Solution:\n\t\tdef sortedSquares(self, nums: List[int]) -> List[int]:\n\t\t\treturn sorted(list(map(lambda x:x**2,nums)))\n\t\t\t\n\t\t\t\nusing Two pointer\n\n\t\tclass Solution:\n\t\t\tdef sortedSquares(self, nums: List[int]) -> List[int]:\n\t\t\t\tl,r=0,len(nums)-1\n\t\t\t\toutput=[]\... | 1 | Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_.
**Example 1:**
**Input:** nums = \[-4,-1,0,3,10\]
**Output:** \[0,1,9,16,100\]
**Explanation:** After squaring, the array becomes \[16,1,0,9,100\].
After sorting, it be... | null |
Python | one line of code | and Two pointers | squares-of-a-sorted-array | 0 | 1 | **One line of code**\n\n\tclass Solution:\n\t\tdef sortedSquares(self, nums: List[int]) -> List[int]:\n\t\t\treturn sorted(list(map(lambda x:x**2,nums)))\n\t\t\t\n\t\t\t\nusing Two pointer\n\n\t\tclass Solution:\n\t\t\tdef sortedSquares(self, nums: List[int]) -> List[int]:\n\t\t\t\tl,r=0,len(nums)-1\n\t\t\t\toutput=[]\... | 1 | You are given the `head` of a linked list with `n` nodes.
For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it.
Return an integer array `answer` where `answer[i]` is the value of ... | null |
[Python] - Two Pointer - Clean & Simple - O(n) Solution | squares-of-a-sorted-array | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nHere, We are having many solutions but here i am showing you just 2. \n1. We are having a **Two Pointer** approach which should work well.\n - Here we had one pointer $$i$$ at $$start$$ index, second pointer $$j$$ at $$end$$ index , a list $$ans$$ ... | 20 | Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_.
**Example 1:**
**Input:** nums = \[-4,-1,0,3,10\]
**Output:** \[0,1,9,16,100\]
**Explanation:** After squaring, the array becomes \[16,1,0,9,100\].
After sorting, it be... | null |
[Python] - Two Pointer - Clean & Simple - O(n) Solution | squares-of-a-sorted-array | 0 | 1 | # Approach\n<!-- Describe your approach to solving the problem. -->\nHere, We are having many solutions but here i am showing you just 2. \n1. We are having a **Two Pointer** approach which should work well.\n - Here we had one pointer $$i$$ at $$start$$ index, second pointer $$j$$ at $$end$$ index , a list $$ans$$ ... | 20 | You are given the `head` of a linked list with `n` nodes.
For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it.
Return an integer array `answer` where `answer[i]` is the value of ... | null |
Very simple 1 liner | squares-of-a-sorted-array | 0 | 1 | \n# Code\n```\nclass Solution:\n\tdef sortedSquares(self, nums: List[int]) -> List[int]:\n\t\treturn sorted(list(map(lambda x:x**2,nums)))\t\n```\n# Line by line \n\n```py\nclass Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n for i in range(len(nums)):\n nums[i] = nums[i]**2\... | 1 | Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_.
**Example 1:**
**Input:** nums = \[-4,-1,0,3,10\]
**Output:** \[0,1,9,16,100\]
**Explanation:** After squaring, the array becomes \[16,1,0,9,100\].
After sorting, it be... | null |
Very simple 1 liner | squares-of-a-sorted-array | 0 | 1 | \n# Code\n```\nclass Solution:\n\tdef sortedSquares(self, nums: List[int]) -> List[int]:\n\t\treturn sorted(list(map(lambda x:x**2,nums)))\t\n```\n# Line by line \n\n```py\nclass Solution:\n def sortedSquares(self, nums: List[int]) -> List[int]:\n for i in range(len(nums)):\n nums[i] = nums[i]**2\... | 1 | You are given the `head` of a linked list with `n` nodes.
For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it.
Return an integer array `answer` where `answer[i]` is the value of ... | null |
Python || 96% beats || easy solution..... | squares-of-a-sorted-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)$$ --... | 2 | Given an integer array `nums` sorted in **non-decreasing** order, return _an array of **the squares of each number** sorted in non-decreasing order_.
**Example 1:**
**Input:** nums = \[-4,-1,0,3,10\]
**Output:** \[0,1,9,16,100\]
**Explanation:** After squaring, the array becomes \[16,1,0,9,100\].
After sorting, it be... | null |
Python || 96% beats || easy solution..... | squares-of-a-sorted-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)$$ --... | 2 | You are given the `head` of a linked list with `n` nodes.
For each node in the list, find the value of the **next greater node**. That is, for each node, find the value of the first node that is next to it and has a **strictly larger** value than it.
Return an integer array `answer` where `answer[i]` is the value of ... | null |
Solution | longest-turbulent-subarray | 1 | 1 | ```C++ []\nclass Solution {\npublic:\nSolution(){\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n }\n int maxTurbulenceSize(vector<int>& arr) {\n int flag=0,n=arr.size(),res=0,i=0,j=1;\n if(arr.size()==1)\n return n;\n if(n==2&&arr[i]==arr[j])\n return 1;\n ... | 1 | Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`.
A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray.
More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only i... | It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and yo... |
Solution | longest-turbulent-subarray | 1 | 1 | ```C++ []\nclass Solution {\npublic:\nSolution(){\n ios_base::sync_with_stdio(false);\n cin.tie(0);\n }\n int maxTurbulenceSize(vector<int>& arr) {\n int flag=0,n=arr.size(),res=0,i=0,j=1;\n if(arr.size()==1)\n return n;\n if(n==2&&arr[i]==arr[j])\n return 1;\n ... | 1 | You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cann... | null |
XOR with DP bottom up with optimization; DP Beginner friendly; | longest-turbulent-subarray | 0 | 1 | \n# Approach 1: Bottom up, Linear Space\n<!-- Describe your approach to solving the problem. -->\n\nMy intuition when i see turbuelnce subarry is that \n```\n> < > < > < > <\n```\nFor a simple array [a, b, c] to be a turbulent array, we could have\n```\nSituation1: a > b < c\nSituation2: a < b > c\n``` \nThe signs are ... | 3 | Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`.
A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray.
More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only i... | It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and yo... |
XOR with DP bottom up with optimization; DP Beginner friendly; | longest-turbulent-subarray | 0 | 1 | \n# Approach 1: Bottom up, Linear Space\n<!-- Describe your approach to solving the problem. -->\n\nMy intuition when i see turbuelnce subarry is that \n```\n> < > < > < > <\n```\nFor a simple array [a, b, c] to be a turbulent array, we could have\n```\nSituation1: a > b < c\nSituation2: a < b > c\n``` \nThe signs are ... | 3 | You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cann... | null |
Function Iterator | longest-turbulent-subarray | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n count = 1\n maxi = 1\n comp = cycle([gt, lt])\n for a, b in pairwise(arr):\n if next(comp)(a, b):\n count += 1\n else:\n maxi = max(maxi, count)\n ... | 1 | Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`.
A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray.
More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only i... | It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and yo... |
Function Iterator | longest-turbulent-subarray | 0 | 1 | \n\n# Code\n```\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n count = 1\n maxi = 1\n comp = cycle([gt, lt])\n for a, b in pairwise(arr):\n if next(comp)(a, b):\n count += 1\n else:\n maxi = max(maxi, count)\n ... | 1 | You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cann... | null |
Python | Even easier explanation, O(n) time, O(1) space | longest-turbulent-subarray | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEvery non-empty subarray has a starting length of 1. If we \'flop\' a subarray, or we\'ve destroyed our streak, we should restart the count at 1. \n\nThere are only 2 states that we need to keep track of (exluding the result, of course): ... | 2 | Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`.
A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray.
More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only i... | It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and yo... |
Python | Even easier explanation, O(n) time, O(1) space | longest-turbulent-subarray | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nEvery non-empty subarray has a starting length of 1. If we \'flop\' a subarray, or we\'ve destroyed our streak, we should restart the count at 1. \n\nThere are only 2 states that we need to keep track of (exluding the result, of course): ... | 2 | You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cann... | null |
python3 sliding window | longest-turbulent-subarray | 0 | 1 | ```\ndef maxTurbulenceSize(self, arr):\n n = len(arr)\n l, r = 0, 0\n ans = 1\n if n == 1:\n\t\t\treturn 1\n while r < n:\n while l < n - 1 and arr[l] == arr[l+1]: # to handle duplicates\n l += 1\n while r < n - 1 and (arr[r-1] > arr[r] < arr[r+1] ... | 9 | Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`.
A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray.
More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only i... | It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and yo... |
python3 sliding window | longest-turbulent-subarray | 0 | 1 | ```\ndef maxTurbulenceSize(self, arr):\n n = len(arr)\n l, r = 0, 0\n ans = 1\n if n == 1:\n\t\t\treturn 1\n while r < n:\n while l < n - 1 and arr[l] == arr[l+1]: # to handle duplicates\n l += 1\n while r < n - 1 and (arr[r-1] > arr[r] < arr[r+1] ... | 9 | You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cann... | null |
Python T/C : 97% S/C: O(1) | longest-turbulent-subarray | 0 | 1 | ```\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n l, r ,output, n =0, 0, 0, len(arr)\n if n==1:\n return 1\n while r < n:\n while r<n-1 and (arr[r-1]>arr[r]<arr[r+1] or arr[r-1]<arr[r]>arr[r+1]):\n r+=1\n while l < r and ... | 2 | Given an integer array `arr`, return _the length of a maximum size turbulent subarray of_ `arr`.
A subarray is **turbulent** if the comparison sign flips between each adjacent pair of elements in the subarray.
More formally, a subarray `[arr[i], arr[i + 1], ..., arr[j]]` of `arr` is said to be turbulent if and only i... | It's very easy to keep track of a monotonically increasing or decreasing ordering of elements. You just need to be able to determine the start of the valley in the mountain and from that point onwards, it should be a valley i.e. no mini-hills after that. Use this information in regards to the values in the array and yo... |
Python T/C : 97% S/C: O(1) | longest-turbulent-subarray | 0 | 1 | ```\nclass Solution:\n def maxTurbulenceSize(self, arr: List[int]) -> int:\n l, r ,output, n =0, 0, 0, len(arr)\n if n==1:\n return 1\n while r < n:\n while r<n-1 and (arr[r-1]>arr[r]<arr[r+1] or arr[r-1]<arr[r]>arr[r+1]):\n r+=1\n while l < r and ... | 2 | You are given an `m x n` binary matrix `grid`, where `0` represents a sea cell and `1` represents a land cell.
A **move** consists of walking from one land cell to another adjacent (**4-directionally**) land cell or walking off the boundary of the `grid`.
Return _the number of land cells in_ `grid` _for which we cann... | null |
Solution | distribute-coins-in-binary-tree | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int balance(TreeNode* node,int &moves){\n if(node==NULL) return 0;\n int l=balance(node->left,moves),r=balance(node->right,moves);\n moves+=abs(l)+abs(r);\n return node->val+l+r-1;\n }\n int distributeCoins(TreeNode* root) {\n int ans=0;... | 1 | You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree.
In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.
Re... | null |
Solution | distribute-coins-in-binary-tree | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int balance(TreeNode* node,int &moves){\n if(node==NULL) return 0;\n int l=balance(node->left,moves),r=balance(node->right,moves);\n moves+=abs(l)+abs(r);\n return node->val+l+r-1;\n }\n int distributeCoins(TreeNode* root) {\n int ans=0;... | 1 | A valid parentheses string is either empty `" "`, `"( " + A + ") "`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation.
* For example, `" "`, `"() "`, `"(())() "`, and `"(()(())) "` are all valid parentheses strings.
A valid parentheses string `s` is primitive if i... | null |
Single post-order traversal. O(N) | distribute-coins-in-binary-tree | 0 | 1 | # Intuition\nSince to re-distribute coins evenly, we need to first check distribution of left and right children, the idea is to traverse the tree in DFS fashion like this: Left Child -> Right Child -> Parent Node aka post-order traversal\n\n# Approach\n1. If a child has 0 coins, move 1 coin through the parent to the c... | 2 | You are given the `root` of a binary tree with `n` nodes where each `node` in the tree has `node.val` coins. There are `n` coins in total throughout the whole tree.
In one move, we may choose two adjacent nodes and move one coin from one node to another. A move may be from parent to child, or from child to parent.
Re... | null |
Single post-order traversal. O(N) | distribute-coins-in-binary-tree | 0 | 1 | # Intuition\nSince to re-distribute coins evenly, we need to first check distribution of left and right children, the idea is to traverse the tree in DFS fashion like this: Left Child -> Right Child -> Parent Node aka post-order traversal\n\n# Approach\n1. If a child has 0 coins, move 1 coin through the parent to the c... | 2 | A valid parentheses string is either empty `" "`, `"( " + A + ") "`, or `A + B`, where `A` and `B` are valid parentheses strings, and `+` represents string concatenation.
* For example, `" "`, `"() "`, `"(())() "`, and `"(()(())) "` are all valid parentheses strings.
A valid parentheses string `s` is primitive if i... | null |
Solution with Backtracking on Python3 / TypeScript | unique-paths-iii | 0 | 1 | # Intuition\nHere\'s the brief explanation of the problem:\n- there\'s a `grid`\n- the cells of this grid has it\'s own notation (`-1` for obstacle, `0` for free cell, `1` is robot **starting** point, `2` is **ending** point)\n- the goal is to find **HOW many** distinct ways are exist to visit **all cells** from **star... | 1 | You are given an `m x n` integer array `grid` where `grid[i][j]` could be:
* `1` representing the starting square. There is exactly one starting square.
* `2` representing the ending square. There is exactly one ending square.
* `0` representing empty squares we can walk over.
* `-1` representing obstacles tha... | null |
Solution with Backtracking on Python3 / TypeScript | unique-paths-iii | 0 | 1 | # Intuition\nHere\'s the brief explanation of the problem:\n- there\'s a `grid`\n- the cells of this grid has it\'s own notation (`-1` for obstacle, `0` for free cell, `1` is robot **starting** point, `2` is **ending** point)\n- the goal is to find **HOW many** distinct ways are exist to visit **all cells** from **star... | 1 | You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit.
* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`.
For all leaves in the tree, c... | null |
EASY PYTHON SOLUTION | unique-paths-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nDFS TRAVERSAL\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(M*N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(M*N)\n<!-- Add your space compl... | 1 | You are given an `m x n` integer array `grid` where `grid[i][j]` could be:
* `1` representing the starting square. There is exactly one starting square.
* `2` representing the ending square. There is exactly one ending square.
* `0` representing empty squares we can walk over.
* `-1` representing obstacles tha... | null |
EASY PYTHON SOLUTION | unique-paths-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nDFS TRAVERSAL\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:O(M*N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(M*N)\n<!-- Add your space compl... | 1 | You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit.
* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`.
For all leaves in the tree, c... | null |
Python Solution Explained ✅ | 93.79% | unique-paths-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing DFS backtracking is the the obvious solution\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe first find the `start` squar and `end` square and `path` length which contains all squares except the blocked.\nth... | 1 | You are given an `m x n` integer array `grid` where `grid[i][j]` could be:
* `1` representing the starting square. There is exactly one starting square.
* `2` representing the ending square. There is exactly one ending square.
* `0` representing empty squares we can walk over.
* `-1` representing obstacles tha... | null |
Python Solution Explained ✅ | 93.79% | unique-paths-iii | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nUsing DFS backtracking is the the obvious solution\n# Approach\n<!-- Describe your approach to solving the problem. -->\nwe first find the `start` squar and `end` square and `path` length which contains all squares except the blocked.\nth... | 1 | You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit.
* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`.
For all leaves in the tree, c... | null |
Simple Python - DFS solution | unique-paths-iii | 0 | 1 | # Intuition\nStart the solution and track from the starting position where the grid found 1 and calculate all the non obstacle path. This can be achieved by using DFS.\n\n# Approach\nFind the start, end path and the count of non-obstacles and find the paths all the directions to reach the end and it must visit all the ... | 1 | You are given an `m x n` integer array `grid` where `grid[i][j]` could be:
* `1` representing the starting square. There is exactly one starting square.
* `2` representing the ending square. There is exactly one ending square.
* `0` representing empty squares we can walk over.
* `-1` representing obstacles tha... | null |
Simple Python - DFS solution | unique-paths-iii | 0 | 1 | # Intuition\nStart the solution and track from the starting position where the grid found 1 and calculate all the non obstacle path. This can be achieved by using DFS.\n\n# Approach\nFind the start, end path and the count of non-obstacles and find the paths all the directions to reach the end and it must visit all the ... | 1 | You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit.
* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`.
For all leaves in the tree, c... | null |
Beats 92% | CodeDominar Solution | unique-paths-iii | 0 | 1 | # Code\n```\nclass Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n rows,cols = len(grid),len(grid[0])\n sr, sc, zeros = [(r, c, sum(1 for row in grid for element in row if element == 0)) for r in range(len(grid)) for c in range(len(grid[0])) if grid[r][c] == 1][0]\n def dfs... | 2 | You are given an `m x n` integer array `grid` where `grid[i][j]` could be:
* `1` representing the starting square. There is exactly one starting square.
* `2` representing the ending square. There is exactly one ending square.
* `0` representing empty squares we can walk over.
* `-1` representing obstacles tha... | null |
Beats 92% | CodeDominar Solution | unique-paths-iii | 0 | 1 | # Code\n```\nclass Solution:\n def uniquePathsIII(self, grid: List[List[int]]) -> int:\n rows,cols = len(grid),len(grid[0])\n sr, sc, zeros = [(r, c, sum(1 for row in grid for element in row if element == 0)) for r in range(len(grid)) for c in range(len(grid[0])) if grid[r][c] == 1][0]\n def dfs... | 2 | You are given the `root` of a binary tree where each node has a value `0` or `1`. Each root-to-leaf path represents a binary number starting with the most significant bit.
* For example, if the path is `0 -> 1 -> 1 -> 0 -> 1`, then this could represent `01101` in binary, which is `13`.
For all leaves in the tree, c... | null |
Two dictionaries | time-based-key-value-store | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:0(logn) per get operation -->0(klogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(n)\n<!-- Add you... | 1 | Design a time-based key-value data structure that can store multiple values for the same key at different time stamps and retrieve the key's value at a certain timestamp.
Implement the `TimeMap` class:
* `TimeMap()` Initializes the object of the data structure.
* `void set(String key, String value, int timestamp)... | null |
Two dictionaries | time-based-key-value-store | 0 | 1 | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:0(logn) per get operation -->0(klogn)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:0(n)\n<!-- Add you... | 1 | Given an array of strings `queries` and a string `pattern`, return a boolean array `answer` where `answer[i]` is `true` if `queries[i]` matches `pattern`, and `false` otherwise.
A query word `queries[i]` matches `pattern` if you can insert lowercase English letters pattern so that it equals the query. You may insert e... | null |
Solution | triples-with-bitwise-and-equal-to-zero | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int countTriplets(vector<int>& nums) {\n int table[1<<16] = {0};\n int n = nums.size();\n for (int i = 0; i < n; ++i) {\n ++table[nums[i]];\n for (int j = i+1; j < n; ++j) {\n table[nums[i]&nums[j]]+= 2;\n }\n... | 1 | Given an integer array nums, return _the number of **AND triples**_.
An **AND triple** is a triple of indices `(i, j, k)` such that:
* `0 <= i < nums.length`
* `0 <= j < nums.length`
* `0 <= k < nums.length`
* `nums[i] & nums[j] & nums[k] == 0`, where `&` represents the bitwise-AND operator.
**Example 1:**
... | null |
Solution | triples-with-bitwise-and-equal-to-zero | 1 | 1 | ```C++ []\nclass Solution {\npublic:\n int countTriplets(vector<int>& nums) {\n int table[1<<16] = {0};\n int n = nums.size();\n for (int i = 0; i < n; ++i) {\n ++table[nums[i]];\n for (int j = i+1; j < n; ++j) {\n table[nums[i]&nums[j]]+= 2;\n }\n... | 1 | You are given a series of video clips from a sporting event that lasted `time` seconds. These video clips can be overlapping with each other and have varying lengths.
Each video clip is described by an array `clips` where `clips[i] = [starti, endi]` indicates that the ith clip started at `starti` and ended at `endi`.
... | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.