title
stringlengths
1
100
titleSlug
stringlengths
3
77
Java
int64
0
1
Python3
int64
1
1
content
stringlengths
28
44.4k
voteCount
int64
0
3.67k
question_content
stringlengths
65
5k
question_hints
stringclasses
970 values
Python Recursion
maximize-number-of-nice-divisors
0
1
The idea is similar to other posts but eliminating some IF condition to make it cleaner. \n`3*3 > 2*2*2` is the most important fact to solve the problem. So we would always prefer to use `3` as the factor.\n```\nMOD = 10**9 + 7\nclass Solution:\n def maxNiceDivisors(self, n: int) -> int:\n if n <= 2: return ...
2
You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions: * The number of prime factors of `n` (not necessarily distinct) is **at most** `primeFactors`. * The number of nice divisors of `n` is maximized. Note that a divisor of `n` is...
The constraints are small enough for an N^2 solution. Try using dynamic programming.
Python Recursion
maximize-number-of-nice-divisors
0
1
The idea is similar to other posts but eliminating some IF condition to make it cleaner. \n`3*3 > 2*2*2` is the most important fact to solve the problem. So we would always prefer to use `3` as the factor.\n```\nMOD = 10**9 + 7\nclass Solution:\n def maxNiceDivisors(self, n: int) -> int:\n if n <= 2: return ...
2
You are given a **strictly increasing** integer array `rungs` that represents the **height** of rungs on a ladder. You are currently on the **floor** at height `0`, and you want to reach the last rung. You are also given an integer `dist`. You can only climb to the next highest rung if the distance between where you a...
The number of nice divisors is equal to the product of the count of each prime factor. Then the problem is reduced to: given n, find a sequence of numbers whose sum equals n and whose product is maximized. This sequence can have no numbers that are larger than 4. Proof: if it contains a number x that is larger than 4, ...
[Python3] math
maximize-number-of-nice-divisors
0
1
\n```\nclass Solution:\n def maxNiceDivisors(self, primeFactors: int) -> int:\n mod = 1_000_000_007\n if primeFactors % 3 == 0: return pow(3, primeFactors//3, mod)\n if primeFactors % 3 == 1: return 1 if primeFactors == 1 else 4*pow(3, (primeFactors-4)//3, mod) % mod\n return 2*pow(3, pri...
2
You are given a positive integer `primeFactors`. You are asked to construct a positive integer `n` that satisfies the following conditions: * The number of prime factors of `n` (not necessarily distinct) is **at most** `primeFactors`. * The number of nice divisors of `n` is maximized. Note that a divisor of `n` is...
The constraints are small enough for an N^2 solution. Try using dynamic programming.
[Python3] math
maximize-number-of-nice-divisors
0
1
\n```\nclass Solution:\n def maxNiceDivisors(self, primeFactors: int) -> int:\n mod = 1_000_000_007\n if primeFactors % 3 == 0: return pow(3, primeFactors//3, mod)\n if primeFactors % 3 == 1: return 1 if primeFactors == 1 else 4*pow(3, (primeFactors-4)//3, mod) % mod\n return 2*pow(3, pri...
2
You are given a **strictly increasing** integer array `rungs` that represents the **height** of rungs on a ladder. You are currently on the **floor** at height `0`, and you want to reach the last rung. You are also given an integer `dist`. You can only climb to the next highest rung if the distance between where you a...
The number of nice divisors is equal to the product of the count of each prime factor. Then the problem is reduced to: given n, find a sequence of numbers whose sum equals n and whose product is maximized. This sequence can have no numbers that are larger than 4. Proof: if it contains a number x that is larger than 4, ...
Python || 3 Lines || Eazy to understand beat 98% 🚀
determine-color-of-a-chessboard-square
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 `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return `true` _if the square is white, and_ `false` _if the square is black_. The coordinate will always represent a valid chessboard square. The coordinate will always have t...
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
Python || 3 Lines || Eazy to understand beat 98% 🚀
determine-color-of-a-chessboard-square
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 a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it. A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**). **Example 1:** *...
Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern.
Easiest to Understand Python Solution, beats 99.6% Memory
determine-color-of-a-chessboard-square
0
1
\n# Code\n```\nclass Solution:\n def squareIsWhite(self, coordinates: str) -> bool:\n alfa = "abcdefghijklmnopqrstuvwxyz"\n if alfa.index(coordinates[0]) % 2 == 0:\n if int(coordinates[1]) % 2 == 0:\n return True\n else:\n return False\n else:\...
1
You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return `true` _if the square is white, and_ `false` _if the square is black_. The coordinate will always represent a valid chessboard square. The coordinate will always have t...
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
Easiest to Understand Python Solution, beats 99.6% Memory
determine-color-of-a-chessboard-square
0
1
\n# Code\n```\nclass Solution:\n def squareIsWhite(self, coordinates: str) -> bool:\n alfa = "abcdefghijklmnopqrstuvwxyz"\n if alfa.index(coordinates[0]) % 2 == 0:\n if int(coordinates[1]) % 2 == 0:\n return True\n else:\n return False\n else:\...
1
Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it. A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**). **Example 1:** *...
Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern.
Determine color of a chessboard square
determine-color-of-a-chessboard-square
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 `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return `true` _if the square is white, and_ `false` _if the square is black_. The coordinate will always represent a valid chessboard square. The coordinate will always have t...
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
Determine color of a chessboard square
determine-color-of-a-chessboard-square
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 a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it. A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**). **Example 1:** *...
Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern.
A simple one liner with runtime of only 30 ms and easy to understand (I think so !).
determine-color-of-a-chessboard-square
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)$$ --...
3
You are given `coordinates`, a string that represents the coordinates of a square of the chessboard. Below is a chessboard for your reference. Return `true` _if the square is white, and_ `false` _if the square is black_. The coordinate will always represent a valid chessboard square. The coordinate will always have t...
Discard all the spaces and dashes. Use a while loop. While the string still has digits, check its length and see which rule to apply.
A simple one liner with runtime of only 30 ms and easy to understand (I think so !).
determine-color-of-a-chessboard-square
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)$$ --...
3
Given a **zero-based permutation** `nums` (**0-indexed**), build an array `ans` of the **same length** where `ans[i] = nums[nums[i]]` for each `0 <= i < nums.length` and return it. A **zero-based permutation** `nums` is an array of **distinct** integers from `0` to `nums.length - 1` (**inclusive**). **Example 1:** *...
Convert the coordinates to (x, y) - that is, "a1" is (1, 1), "d7" is (4, 7). Try add the numbers together and look for a pattern.
Python beats 100% | TC: O(s1 + s2) | SC: O(s1 + s2)
sentence-similarity-iii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOnly single sentence can be inserted so only three positions possible\n\n#### Insert Left\nEx: s1 = "now", s2 = "Eating right now"\n\n__"Eating right"__ + "now == "Eating right now"\n\n\n#### Insert Right\nEx: s1 = "Eating", s2 = "Eating ...
1
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, `"Hello World "`, `"HELLO "`, `"hello world hello world "` are all sentences. Words consist of **only** uppercase and lowercase English letters. Two sentences `sentence1` and `sentence2` are **similar** ...
The main point here is for the subarray to contain unique elements for each index. Only the first subarrays starting from that index have unique elements. This can be solved using the two pointers technique
Python beats 100% | TC: O(s1 + s2) | SC: O(s1 + s2)
sentence-similarity-iii
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nOnly single sentence can be inserted so only three positions possible\n\n#### Insert Left\nEx: s1 = "now", s2 = "Eating right now"\n\n__"Eating right"__ + "now == "Eating right now"\n\n\n#### Insert Right\nEx: s1 = "Eating", s2 = "Eating ...
1
There is a country of `n` cities numbered from `0` to `n - 1`. In this country, there is a road connecting **every pair** of cities. There are `m` friends numbered from `0` to `m - 1` who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an inte...
One way to look at it is to find one sentence as a concatenation of a prefix and suffix from the other sentence. Get the longest common prefix between them and the longest common suffix.
USE QUEUE EXPLANATION || PYTHON
sentence-similarity-iii
0
1
# Intuition\nThe basic concept of the question is to fit one sentence in mid of another sentence \ni.e the bigger sentence remaining chars should be the all mid element and smaller sentence takes up the edges words\nso there are 2 conditions to check\neither the smaller sentence(s2) start word is present at s1 start\no...
0
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, `"Hello World "`, `"HELLO "`, `"hello world hello world "` are all sentences. Words consist of **only** uppercase and lowercase English letters. Two sentences `sentence1` and `sentence2` are **similar** ...
The main point here is for the subarray to contain unique elements for each index. Only the first subarrays starting from that index have unique elements. This can be solved using the two pointers technique
USE QUEUE EXPLANATION || PYTHON
sentence-similarity-iii
0
1
# Intuition\nThe basic concept of the question is to fit one sentence in mid of another sentence \ni.e the bigger sentence remaining chars should be the all mid element and smaller sentence takes up the edges words\nso there are 2 conditions to check\neither the smaller sentence(s2) start word is present at s1 start\no...
0
There is a country of `n` cities numbered from `0` to `n - 1`. In this country, there is a road connecting **every pair** of cities. There are `m` friends numbered from `0` to `m - 1` who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an inte...
One way to look at it is to find one sentence as a concatenation of a prefix and suffix from the other sentence. Get the longest common prefix between them and the longest common suffix.
Python3 sol.
sentence-similarity-iii
0
1
\n# Code\n```\nclass Solution:\n def areSentencesSimilar(self, s1: str, s2: str) -> bool:\n def check(a,b):\n a=a.split()\n b=b.split()\n while len(a)>0 and len(b)>0 and a[0]==b[0]:\n a.pop(0)\n b.pop(0)\n while len(a)>0 and len(b)>0 an...
0
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, `"Hello World "`, `"HELLO "`, `"hello world hello world "` are all sentences. Words consist of **only** uppercase and lowercase English letters. Two sentences `sentence1` and `sentence2` are **similar** ...
The main point here is for the subarray to contain unique elements for each index. Only the first subarrays starting from that index have unique elements. This can be solved using the two pointers technique
Python3 sol.
sentence-similarity-iii
0
1
\n# Code\n```\nclass Solution:\n def areSentencesSimilar(self, s1: str, s2: str) -> bool:\n def check(a,b):\n a=a.split()\n b=b.split()\n while len(a)>0 and len(b)>0 and a[0]==b[0]:\n a.pop(0)\n b.pop(0)\n while len(a)>0 and len(b)>0 an...
0
There is a country of `n` cities numbered from `0` to `n - 1`. In this country, there is a road connecting **every pair** of cities. There are `m` friends numbered from `0` to `m - 1` who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an inte...
One way to look at it is to find one sentence as a concatenation of a prefix and suffix from the other sentence. Get the longest common prefix between them and the longest common suffix.
Using Dynamic Programming || Standard Algo for most of the Dynamic Programming Questions
sentence-similarity-iii
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 * m\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nIn this code we have splited the given string to array. \nso it will t...
0
A sentence is a list of words that are separated by a single space with no leading or trailing spaces. For example, `"Hello World "`, `"HELLO "`, `"hello world hello world "` are all sentences. Words consist of **only** uppercase and lowercase English letters. Two sentences `sentence1` and `sentence2` are **similar** ...
The main point here is for the subarray to contain unique elements for each index. Only the first subarrays starting from that index have unique elements. This can be solved using the two pointers technique
Using Dynamic Programming || Standard Algo for most of the Dynamic Programming Questions
sentence-similarity-iii
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 * m\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nIn this code we have splited the given string to array. \nso it will t...
0
There is a country of `n` cities numbered from `0` to `n - 1`. In this country, there is a road connecting **every pair** of cities. There are `m` friends numbered from `0` to `m - 1` who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an inte...
One way to look at it is to find one sentence as a concatenation of a prefix and suffix from the other sentence. Get the longest common prefix between them and the longest common suffix.
🔥HEART BREAKiNG SOLUTiON EVER 🔥 ✅✅✅ by PRODONIK (Java, C#, C++, Python, Ruby) 🔥
count-nice-pairs-in-an-array
1
1
![image.png](https://assets.leetcode.com/users/images/d0dfc90d-174b-40d3-af8b-0dacfccd9fe5_1700541597.6823025.png)\n\n# Intuition\nThe problem involves counting the number of "nice pairs" in an array, where a "nice pair" is defined as a pair of elements whose difference is equal to the difference between the reverse of...
14
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value i...
🔥HEART BREAKiNG SOLUTiON EVER 🔥 ✅✅✅ by PRODONIK (Java, C#, C++, Python, Ruby) 🔥
count-nice-pairs-in-an-array
1
1
![image.png](https://assets.leetcode.com/users/images/d0dfc90d-174b-40d3-af8b-0dacfccd9fe5_1700541597.6823025.png)\n\n# Intuition\nThe problem involves counting the number of "nice pairs" in an array, where a "nice pair" is defined as a pair of elements whose difference is equal to the difference between the reverse of...
14
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`. Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`. **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation**: The square triples are (3,4,5) and (4,3,5). **Example 2...
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map...
💯Faster✅💯 Lesser✅Simple Math🔥Hash Table🔥Simple Explanation🔥Intuition Explained🔥
count-nice-pairs-in-an-array
1
1
# Intuition\n- We have an array of non-negative integers.\n- We\'re looking for pairs of indices (i, j) where a specific condition is satisfied.\n- The condition involves the sum of a number and its reverse (digits reversed).\n- More precisely, for indices i and j (where i < j):\n- Original condition: $$nums[i] + rev(n...
57
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value i...
💯Faster✅💯 Lesser✅Simple Math🔥Hash Table🔥Simple Explanation🔥Intuition Explained🔥
count-nice-pairs-in-an-array
1
1
# Intuition\n- We have an array of non-negative integers.\n- We\'re looking for pairs of indices (i, j) where a specific condition is satisfied.\n- The condition involves the sum of a number and its reverse (digits reversed).\n- More precisely, for indices i and j (where i < j):\n- Original condition: $$nums[i] + rev(n...
57
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`. Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`. **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation**: The square triples are (3,4,5) and (4,3,5). **Example 2...
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map...
[Python3] Two sum approach + number of pairs n(n-1)//2 || beats 99%
count-nice-pairs-in-an-array
0
1
### Number of pairs:\nThe formula `\uD835\uDC5B(\uD835\uDC5B\u22121)/2`for the number of pairs you can form from an `\uD835\uDC5B` element set has many derivations.\n\nOne is to imagine a room with `\uD835\uDC5B` people, each of whom shakes hands with everyone else. If you focus on just one person you see that he parti...
21
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value i...
[Python3] Two sum approach + number of pairs n(n-1)//2 || beats 99%
count-nice-pairs-in-an-array
0
1
### Number of pairs:\nThe formula `\uD835\uDC5B(\uD835\uDC5B\u22121)/2`for the number of pairs you can form from an `\uD835\uDC5B` element set has many derivations.\n\nOne is to imagine a room with `\uD835\uDC5B` people, each of whom shakes hands with everyone else. If you focus on just one person you see that he parti...
21
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`. Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`. **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation**: The square triples are (3,4,5) and (4,3,5). **Example 2...
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map...
✌️Maths+Maps.py🧐
count-nice-pairs-in-an-array
0
1
# Code\n```py\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n ans,mp=0,{}\n for i in nums:\n rev=i-int((str(i)[::-1]))\n if rev not in mp:mp[rev]=1\n else:mp[rev]+=1\n print(mp)\n for i in mp:ans+=((mp[i]*(mp[i]-1)//2))%(10**9+7)\n ...
6
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value i...
✌️Maths+Maps.py🧐
count-nice-pairs-in-an-array
0
1
# Code\n```py\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n ans,mp=0,{}\n for i in nums:\n rev=i-int((str(i)[::-1]))\n if rev not in mp:mp[rev]=1\n else:mp[rev]+=1\n print(mp)\n for i in mp:ans+=((mp[i]*(mp[i]-1)//2))%(10**9+7)\n ...
6
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`. Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`. **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation**: The square triples are (3,4,5) and (4,3,5). **Example 2...
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map...
Easy To Understand || O(N)|| c++|| java|| python
count-nice-pairs-in-an-array
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe given code seems to be solving a problem related to counting "nice pairs" in an array. A "nice pair" is a pair of indices (i, j) where nums[i] - rev(nums[j]) is the same as nums[j] - rev(nums[i]). The approach involves r...
15
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value i...
Easy To Understand || O(N)|| c++|| java|| python
count-nice-pairs-in-an-array
1
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe given code seems to be solving a problem related to counting "nice pairs" in an array. A "nice pair" is a pair of indices (i, j) where nums[i] - rev(nums[j]) is the same as nums[j] - rev(nums[i]). The approach involves r...
15
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`. Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`. **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation**: The square triples are (3,4,5) and (4,3,5). **Example 2...
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map...
✅ One Line Solution
count-nice-pairs-in-an-array
0
1
# Complexity\n- Time complexity: $$O(n)$$.\n\n- Space complexity: $$O(n)$$.\n\n# Code - Oneliner\n```\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n return sum(comb(cnt, 2) for cnt in Counter(num - int(str(num)[::-1]) for num in nums).values())%(10**9 + 7)\n```\n\n# Code - Unwrapped\n`...
3
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value i...
✅ One Line Solution
count-nice-pairs-in-an-array
0
1
# Complexity\n- Time complexity: $$O(n)$$.\n\n- Space complexity: $$O(n)$$.\n\n# Code - Oneliner\n```\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n return sum(comb(cnt, 2) for cnt in Counter(num - int(str(num)[::-1]) for num in nums).values())%(10**9 + 7)\n```\n\n# Code - Unwrapped\n`...
3
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`. Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`. **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation**: The square triples are (3,4,5) and (4,3,5). **Example 2...
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map...
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥
count-nice-pairs-in-an-array
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n### ***Approach 1(Combination)***\n1. The `rev` function reverses a given number.\n1. In `countNicePairs`, it calculates the differences between each number and its reverse, storing the frequencies of these differences in the fre...
2
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value i...
✅☑[C++/Java/Python/JavaScript] || 2 Approaches || EXPLAINED🔥
count-nice-pairs-in-an-array
1
1
# PLEASE UPVOTE IF IT HELPED\n\n---\n\n\n# Approaches\n**(Also explained in the code)**\n\n### ***Approach 1(Combination)***\n1. The `rev` function reverses a given number.\n1. In `countNicePairs`, it calculates the differences between each number and its reverse, storing the frequencies of these differences in the fre...
2
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`. Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`. **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation**: The square triples are (3,4,5) and (4,3,5). **Example 2...
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map...
Python3 Solution
count-nice-pairs-in-an-array
0
1
\n```\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n mod=10**9+7\n ans=0\n count=collections.Counter()\n for num in nums:\n num-=int(str(num)[::-1])\n ans+=count[num]\n count[num]+=1\n return ans%mod \n```
2
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value i...
Python3 Solution
count-nice-pairs-in-an-array
0
1
\n```\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n mod=10**9+7\n ans=0\n count=collections.Counter()\n for num in nums:\n num-=int(str(num)[::-1])\n ans+=count[num]\n count[num]+=1\n return ans%mod \n```
2
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`. Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`. **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation**: The square triples are (3,4,5) and (4,3,5). **Example 2...
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map...
Easy Hashmap + Combination approach
count-nice-pairs-in-an-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. -->rearrange the condition to nums[i] - rev(nums[i]) == nums[j] - rev(nums[j])\ndry run with an example \n* eg - nums = [13,10,35,24,76]\n* create a dictionary and store th...
2
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value i...
Easy Hashmap + Combination approach
count-nice-pairs-in-an-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. -->rearrange the condition to nums[i] - rev(nums[i]) == nums[j] - rev(nums[j])\ndry run with an example \n* eg - nums = [13,10,35,24,76]\n* create a dictionary and store th...
2
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`. Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`. **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation**: The square triples are (3,4,5) and (4,3,5). **Example 2...
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map...
1-liner
count-nice-pairs-in-an-array
0
1
# Code\n```python\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n return sum(i*(i-1)//2 for i in Counter([i-int(str(i)[::-1])for i in nums]).values()) % 1_000_000_007\n```
1
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value i...
1-liner
count-nice-pairs-in-an-array
0
1
# Code\n```python\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int:\n return sum(i*(i-1)//2 for i in Counter([i-int(str(i)[::-1])for i in nums]).values()) % 1_000_000_007\n```
1
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`. Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`. **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation**: The square triples are (3,4,5) and (4,3,5). **Example 2...
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map...
LeetCode 1814 | Shift Terms & Combinatorics Approach | Python3 Solution | ✅99.19%
count-nice-pairs-in-an-array
0
1
# Intuition\n\n### Shift Terms\nLet\'s shift terms in this equation.\n$$n_i + rev(n_j) = n_j + rev(n_i) \\Longleftrightarrow n_i - rev(n_i) = n_j - rev(n_j)$$\n\nAssume difference be $$\\theta_i = n_i - rev(n_i)$$. As a result $$(i, j)$$ will be a nice pair if the difference of $$i$$ and $$j$$ are equal.\n$$(i, j)$$ is...
1
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value i...
LeetCode 1814 | Shift Terms & Combinatorics Approach | Python3 Solution | ✅99.19%
count-nice-pairs-in-an-array
0
1
# Intuition\n\n### Shift Terms\nLet\'s shift terms in this equation.\n$$n_i + rev(n_j) = n_j + rev(n_i) \\Longleftrightarrow n_i - rev(n_i) = n_j - rev(n_j)$$\n\nAssume difference be $$\\theta_i = n_i - rev(n_i)$$. As a result $$(i, j)$$ will be a nice pair if the difference of $$i$$ and $$j$$ are equal.\n$$(i, j)$$ is...
1
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`. Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`. **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation**: The square triples are (3,4,5) and (4,3,5). **Example 2...
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map...
Python solution based on hint 1 || O(n)
count-nice-pairs-in-an-array
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nThe condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])).\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....
1
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value i...
Python solution based on hint 1 || O(n)
count-nice-pairs-in-an-array
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nThe condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])).\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....
1
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`. Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`. **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation**: The square triples are (3,4,5) and (4,3,5). **Example 2...
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map...
0 Line Solution
count-nice-pairs-in-an-array
0
1
# Description\nThe entire code is ran inline for the Solution\'s Function leading to a 2 line solution (0 added lines).\n\n# Code\n```\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int: return sum([(val * (val-1)) // 2 for val in collections.Counter([num - int(str(num)[::-1]) for num in nums]).valu...
1
You are given an array `nums` that consists of non-negative integers. Let us define `rev(x)` as the reverse of the non-negative integer `x`. For example, `rev(123) = 321`, and `rev(120) = 21`. A pair of indices `(i, j)` is **nice** if it satisfies all of the following conditions: * `0 <= i < j < nums.length` * `nu...
Let dp[i] be "the maximum score to reach the end starting at index i". The answer for dp[i] is nums[i] + max{dp[i+j]} for 1 <= j <= k. That gives an O(n*k) solution. Instead of checking every j for every i, keep track of the largest dp[i] values in a heap and calculate dp[i] from right to left. When the largest value i...
0 Line Solution
count-nice-pairs-in-an-array
0
1
# Description\nThe entire code is ran inline for the Solution\'s Function leading to a 2 line solution (0 added lines).\n\n# Code\n```\nclass Solution:\n def countNicePairs(self, nums: List[int]) -> int: return sum([(val * (val-1)) // 2 for val in collections.Counter([num - int(str(num)[::-1]) for num in nums]).valu...
1
A **square triple** `(a,b,c)` is a triple where `a`, `b`, and `c` are **integers** and `a2 + b2 = c2`. Given an integer `n`, return _the number of **square triples** such that_ `1 <= a, b, c <= n`. **Example 1:** **Input:** n = 5 **Output:** 2 **Explanation**: The square triples are (3,4,5) and (4,3,5). **Example 2...
The condition can be rearranged to (nums[i] - rev(nums[i])) == (nums[j] - rev(nums[j])). Transform each nums[i] into (nums[i] - rev(nums[i])). Then, count the number of (i, j) pairs that have equal values. Keep a map storing the frequencies of values that you have seen so far. For each i, check if nums[i] is in the map...
[Python3] No greedy, just DP
maximum-number-of-groups-getting-fresh-donuts
0
1
For each group size, we mod it with batchSize.\nThe greedy way is easy to think of, for those mod==0, make them immediately to single group.\nFor those pairs whose sum mod ==0, we also pair them to one single group.\nFor the rest, we do DP.\nBut the above 2 greedy steps do not change time complexity. Total time complex...
2
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` cust...
All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?
Modular Math and DFS of Ordering Paths
maximum-number-of-groups-getting-fresh-donuts
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst hint is that we have a modular math problem based on batch size. \nNext hint is that we can always satisfy those of batchsize if we put them in the right order.\n\nFirst job then is to remove these from contention and have those in ...
0
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` cust...
All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?
Python (Simple DP + Bitmasking)
maximum-number-of-groups-getting-fresh-donuts
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
There is a donuts shop that bakes donuts in batches of `batchSize`. They have a rule where they must serve **all** of the donuts of a batch before serving any donuts of the next batch. You are given an integer `batchSize` and an integer array `groups`, where `groups[i]` denotes that there is a group of `groups[i]` cust...
All the queries are given in advance. Is there a way you can reorder the queries to avoid repeated computations?
Python One Line Solution Using Split And Join Method .
truncate-sentence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntution is to find trunkate the Sentence given and return it.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe used the split method inside the join method for the single line easy solution .\n\n# Code\n```\nclass...
1
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation). * For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences. You are given a...
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
Python One Line Solution Using Split And Join Method .
truncate-sentence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIntution is to find trunkate the Sentence given and return it.\n# Approach\n<!-- Describe your approach to solving the problem. -->\nWe used the split method inside the join method for the single line easy solution .\n\n# Code\n```\nclass...
1
There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person. A person can **see** another person to their right in the queue if everybody in between is ...
It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence
Simple 2 line python code 🔥
truncate-sentence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
1
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation). * For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences. You are given a...
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
Simple 2 line python code 🔥
truncate-sentence
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
There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person. A person can **see** another person to their right in the queue if everybody in between is ...
It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence
Python Sentence Truncation | 29ms Runtime
truncate-sentence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can parse the string to a list of words and then take the first `k` words as a sentence.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Parse the string to a list of words using space as a separator.\n > ...
3
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation). * For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences. You are given a...
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
Python Sentence Truncation | 29ms Runtime
truncate-sentence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe can parse the string to a list of words and then take the first `k` words as a sentence.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Parse the string to a list of words using space as a separator.\n > ...
3
There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person. A person can **see** another person to their right in the queue if everybody in between is ...
It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence
Python using split() and join()
truncate-sentence
0
1
# Intuition\nI figured it would be easy to convert the string into a list to get the length of the list. Once you have the length you can convert it back to a string and return it.\n\n# Approach\nFirst thing I did was take the string and convert it to a list using .split(" ") with the white space being the separator. I...
0
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation). * For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences. You are given a...
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
Python using split() and join()
truncate-sentence
0
1
# Intuition\nI figured it would be easy to convert the string into a list to get the length of the list. Once you have the length you can convert it back to a string and return it.\n\n# Approach\nFirst thing I did was take the string and convert it to a list using .split(" ") with the white space being the separator. I...
0
There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person. A person can **see** another person to their right in the queue if everybody in between is ...
It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence
Shortest 1 line solution
truncate-sentence
0
1
\n# Code\n```\nclass Solution:\n def truncateSentence(self, s: str, k: int) -> str:\n return " ".join(s.split(" ")[:k])\n```\n# Line by Line\n```\nclass Solution:\n def truncateSentence(self, s: str, k: int) -> str:\n words_list = s.split(" ")\n truncated_list = words_list[:k]\n result...
3
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation). * For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences. You are given a...
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
Shortest 1 line solution
truncate-sentence
0
1
\n# Code\n```\nclass Solution:\n def truncateSentence(self, s: str, k: int) -> str:\n return " ".join(s.split(" ")[:k])\n```\n# Line by Line\n```\nclass Solution:\n def truncateSentence(self, s: str, k: int) -> str:\n words_list = s.split(" ")\n truncated_list = words_list[:k]\n result...
3
There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person. A person can **see** another person to their right in the queue if everybody in between is ...
It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence
simple python 100% effective solution
truncate-sentence
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation). * For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences. You are given a...
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
simple python 100% effective solution
truncate-sentence
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
There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person. A person can **see** another person to their right in the queue if everybody in between is ...
It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence
3 different approach in Python
truncate-sentence
0
1
\n# 1 liner\n```\nclass Solution:\n def truncateSentence(self, s: str, k: int) -> str:\n return \' \'.join(s.split()[:k])\n```\n\n# Count space and do slicing\n```\nclass Solution:\n def truncateSentence(self, s: str, k: int) -> str:\n count=0\n for i,c in enumerate(s):\n if c==\' ...
9
A **sentence** is a list of words that are separated by a single space with no leading or trailing spaces. Each of the words consists of **only** uppercase and lowercase English letters (no punctuation). * For example, `"Hello World "`, `"HELLO "`, and `"hello world hello world "` are all sentences. You are given a...
Starting from the root, traverse the left and the right subtrees, checking if one of the nodes exist there. If one of the subtrees doesn't contain any given node, the LCA can be the node returned from the other subtree If both subtrees contain nodes, the LCA node is the current node.
3 different approach in Python
truncate-sentence
0
1
\n# 1 liner\n```\nclass Solution:\n def truncateSentence(self, s: str, k: int) -> str:\n return \' \'.join(s.split()[:k])\n```\n\n# Count space and do slicing\n```\nclass Solution:\n def truncateSentence(self, s: str, k: int) -> str:\n count=0\n for i,c in enumerate(s):\n if c==\' ...
9
There are `n` people standing in a queue, and they numbered from `0` to `n - 1` in **left to right** order. You are given an array `heights` of **distinct** integers where `heights[i]` represents the height of the `ith` person. A person can **see** another person to their right in the queue if everybody in between is ...
It's easier to solve this problem on an array of strings so parse the string to an array of words After return the first k words as a sentence
[Python 3] Using set and dictionary || beats 98% || 826ms 🥷🏼
finding-the-users-active-minutes
0
1
```python3 []\nclass Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n res, seen, d = [0] * k, set(), defaultdict(int)\n\n for user, time in logs:\n if (user, time) in seen: continue\n d[user] += 1\n seen.add((user, time))\...
2
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can...
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
[Python 3] Using set and dictionary || beats 98% || 826ms 🥷🏼
finding-the-users-active-minutes
0
1
```python3 []\nclass Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n res, seen, d = [0] * k, set(), defaultdict(int)\n\n for user, time in logs:\n if (user, time) in seen: continue\n d[user] += 1\n seen.add((user, time))\...
2
You are given a string `s` consisting of lowercase English letters, and an integer `k`. First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum ...
Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user.
BITMASK | EXPLOIT PYTHON
finding-the-users-active-minutes
0
1
# Note\nWe can\'t use this method in JAVA or CPP. We did use here cuz number in python have very large limit.\n# Code\n```\nclass Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n mp,freq,ans = {},{},[0] * k\n\n for log in logs: mp[log[0]] = mp.get(log[0],0)...
1
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can...
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
BITMASK | EXPLOIT PYTHON
finding-the-users-active-minutes
0
1
# Note\nWe can\'t use this method in JAVA or CPP. We did use here cuz number in python have very large limit.\n# Code\n```\nclass Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n mp,freq,ans = {},{},[0] * k\n\n for log in logs: mp[log[0]] = mp.get(log[0],0)...
1
You are given a string `s` consisting of lowercase English letters, and an integer `k`. First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum ...
Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user.
Python Easy Solution
finding-the-users-active-minutes
0
1
# Code\n```\nclass Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n dic={}\n temp=[]\n res=[0]*k\n for i in range(len(logs)):\n if logs[i][0] in dic:\n if logs[i][1] not in dic[logs[i][0]]:\n dic[lo...
1
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can...
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
Python Easy Solution
finding-the-users-active-minutes
0
1
# Code\n```\nclass Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n dic={}\n temp=[]\n res=[0]*k\n for i in range(len(logs)):\n if logs[i][0] in dic:\n if logs[i][1] not in dic[logs[i][0]]:\n dic[lo...
1
You are given a string `s` consisting of lowercase English letters, and an integer `k`. First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum ...
Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user.
Python3 O(N) solution with dictionary (91.46% Runtime)
finding-the-users-active-minutes
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n![image.png](https://assets.leetcode.com/users/images/67593fc0-5cde-48b6-b5f1-2dd84753b504_1702030113.1675375.png)\nUtilize dictionary and set to handle value updates with duplicates\n\n# Approach\n<!-- Describe your approach to solving t...
1
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can...
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
Python3 O(N) solution with dictionary (91.46% Runtime)
finding-the-users-active-minutes
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n![image.png](https://assets.leetcode.com/users/images/67593fc0-5cde-48b6-b5f1-2dd84753b504_1702030113.1675375.png)\nUtilize dictionary and set to handle value updates with duplicates\n\n# Approach\n<!-- Describe your approach to solving t...
1
You are given a string `s` consisting of lowercase English letters, and an integer `k`. First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum ...
Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user.
Python with dictionary | Time O(n) | Space O(n + k)
finding-the-users-active-minutes
0
1
# Code\n```\nclass Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n # hash map of id -> set(time)\n user = {}\n # answer array with the k length\n ans = [0]*k\n\n for id, time in logs:\n # if the user id don\'t exist in user\...
1
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can...
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
Python with dictionary | Time O(n) | Space O(n + k)
finding-the-users-active-minutes
0
1
# Code\n```\nclass Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n # hash map of id -> set(time)\n user = {}\n # answer array with the k length\n ans = [0]*k\n\n for id, time in logs:\n # if the user id don\'t exist in user\...
1
You are given a string `s` consisting of lowercase English letters, and an integer `k`. First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum ...
Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user.
[Python3] hash map
finding-the-users-active-minutes
0
1
\n```\nclass Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n mp = {}\n for i, t in logs: \n mp.setdefault(i, set()).add(t)\n \n ans = [0]*k\n for v in mp.values(): \n if len(v) <= k: \n ans[len(...
9
You are given the logs for users' actions on LeetCode, and an integer `k`. The logs are represented by a 2D integer array `logs` where each `logs[i] = [IDi, timei]` indicates that the user with `IDi` performed an action at the minute `timei`. **Multiple users** can perform actions simultaneously, and a single user can...
Simulate the process by keeping track of how much money John is putting in and which day of the week it is, and use this information to deduce how much money John will put in the next day.
[Python3] hash map
finding-the-users-active-minutes
0
1
\n```\nclass Solution:\n def findingUsersActiveMinutes(self, logs: List[List[int]], k: int) -> List[int]:\n mp = {}\n for i, t in logs: \n mp.setdefault(i, set()).add(t)\n \n ans = [0]*k\n for v in mp.values(): \n if len(v) <= k: \n ans[len(...
9
You are given a string `s` consisting of lowercase English letters, and an integer `k`. First, **convert** `s` into an integer by replacing each letter with its position in the alphabet (i.e., replace `'a'` with `1`, `'b'` with `2`, ..., `'z'` with `26`). Then, **transform** the integer by replacing it with the **sum ...
Try to find the number of different minutes when action happened for each user. For each user increase the value of the answer array index which matches the UAM for this user.
[Python] + Fully Explained + Best Solution ✔
minimum-absolute-sum-difference
0
1
![image](https://assets.leetcode.com/users/images/9ab838ea-0ae8-4003-bbea-44e0812a0790_1643019892.44807.png)\n\n\tclass Solution:\n\t\tdef minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:\n\t\t\tn = len(nums1)\n\t\t\tdiff = []\n\t\t\tsum = 0\n\t\t\tfor i in range(n):\n\t\t\t\ttemp = abs(nums1[i]-num...
12
You are given two positive integer arrays `nums1` and `nums2`, both of length `n`. The **absolute sum difference** of arrays `nums1` and `nums2` is defined as the **sum** of `|nums1[i] - nums2[i]|` for each `0 <= i < n` (**0-indexed**). You can replace **at most one** element of `nums1` with **any** other element in ...
Note that it is always more optimal to take one type of substring before another You can use a stack to handle erasures
[Python] + Fully Explained + Best Solution ✔
minimum-absolute-sum-difference
0
1
![image](https://assets.leetcode.com/users/images/9ab838ea-0ae8-4003-bbea-44e0812a0790_1643019892.44807.png)\n\n\tclass Solution:\n\t\tdef minAbsoluteSumDiff(self, nums1: List[int], nums2: List[int]) -> int:\n\t\t\tn = len(nums1)\n\t\t\tdiff = []\n\t\t\tsum = 0\n\t\t\tfor i in range(n):\n\t\t\t\ttemp = abs(nums1[i]-num...
12
You are given a string `num`, which represents a large integer. You are also given a **0-indexed** integer array `change` of length `10` that maps each digit `0-9` to another digit. More formally, digit `d` maps to digit `change[d]`. You may **choose** to **mutate a single substring** of `num`. To mutate a substring, ...
Go through each element and test the optimal replacements. There are only 2 possible replacements for each element (higher and lower) that are optimal.
🤯 [Python] Easy Logic | Explained | Sort + Binary Search | Codeplug
minimum-absolute-sum-difference
0
1
# Intuition\nWe first calculate the absolute differences for all the indices and the current sum of those differences.\n\nWe need to reduce this sum in the end.\n\n# Approach\nfor each value in nums2, we try to find the closest value in nums1 so that the difference becomes 0. In order to find it efficiently we can sort...
3
You are given two positive integer arrays `nums1` and `nums2`, both of length `n`. The **absolute sum difference** of arrays `nums1` and `nums2` is defined as the **sum** of `|nums1[i] - nums2[i]|` for each `0 <= i < n` (**0-indexed**). You can replace **at most one** element of `nums1` with **any** other element in ...
Note that it is always more optimal to take one type of substring before another You can use a stack to handle erasures
🤯 [Python] Easy Logic | Explained | Sort + Binary Search | Codeplug
minimum-absolute-sum-difference
0
1
# Intuition\nWe first calculate the absolute differences for all the indices and the current sum of those differences.\n\nWe need to reduce this sum in the end.\n\n# Approach\nfor each value in nums2, we try to find the closest value in nums1 so that the difference becomes 0. In order to find it efficiently we can sort...
3
You are given a string `num`, which represents a large integer. You are also given a **0-indexed** integer array `change` of length `10` that maps each digit `0-9` to another digit. More formally, digit `d` maps to digit `change[d]`. You may **choose** to **mutate a single substring** of `num`. To mutate a substring, ...
Go through each element and test the optimal replacements. There are only 2 possible replacements for each element (higher and lower) that are optimal.
simple - replace number with closest
minimum-absolute-sum-difference
0
1
\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n for each pair (a,b) find the number in nums1 that is cloest to b via binary search\n after replacing a with that number keep track of the smallest absolute_sum_difference for each replacment\n\n# Code\n```\nclass Solution:\n def minAbsol...
0
You are given two positive integer arrays `nums1` and `nums2`, both of length `n`. The **absolute sum difference** of arrays `nums1` and `nums2` is defined as the **sum** of `|nums1[i] - nums2[i]|` for each `0 <= i < n` (**0-indexed**). You can replace **at most one** element of `nums1` with **any** other element in ...
Note that it is always more optimal to take one type of substring before another You can use a stack to handle erasures
simple - replace number with closest
minimum-absolute-sum-difference
0
1
\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n for each pair (a,b) find the number in nums1 that is cloest to b via binary search\n after replacing a with that number keep track of the smallest absolute_sum_difference for each replacment\n\n# Code\n```\nclass Solution:\n def minAbsol...
0
You are given a string `num`, which represents a large integer. You are also given a **0-indexed** integer array `change` of length `10` that maps each digit `0-9` to another digit. More formally, digit `d` maps to digit `change[d]`. You may **choose** to **mutate a single substring** of `num`. To mutate a substring, ...
Go through each element and test the optimal replacements. There are only 2 possible replacements for each element (higher and lower) that are optimal.
[Python3] enumerate all possibilities
number-of-different-subsequences-gcds
0
1
\n```\nclass Solution:\n def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int:\n nums = set(nums)\n \n ans = 0\n m = max(nums)\n for x in range(1, m+1): \n g = 0\n for xx in range(x, m+1, x): \n if xx in nums: \n g ...
4
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed...
Heuristic algorithm may work.
[Python3] enumerate all possibilities
number-of-different-subsequences-gcds
0
1
\n```\nclass Solution:\n def countDifferentSubsequenceGCDs(self, nums: List[int]) -> int:\n nums = set(nums)\n \n ans = 0\n m = max(nums)\n for x in range(1, m+1): \n g = 0\n for xx in range(x, m+1, x): \n if xx in nums: \n g ...
4
There is a survey that consists of `n` questions where each question's answer is either `0` (no) or `1` (yes). The survey was given to `m` students numbered from `0` to `m - 1` and `m` mentors numbered from `0` to `m - 1`. The answers of the students are represented by a 2D integer array `students` where `students[i]`...
Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a v...
Factor Presence Mathematics | Commented and Explained | O(max(N, maxnum log maxnum)) T O(N) S
number-of-different-subsequences-gcds
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst, our problem space is not ideal, so we need to restructure for that. \nThe first way to reconstruct this more usefully is to consider only unique values of nums. This is because the unique values are what will form distinct subseque...
0
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed...
Heuristic algorithm may work.
Factor Presence Mathematics | Commented and Explained | O(max(N, maxnum log maxnum)) T O(N) S
number-of-different-subsequences-gcds
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst, our problem space is not ideal, so we need to restructure for that. \nThe first way to reconstruct this more usefully is to consider only unique values of nums. This is because the unique values are what will form distinct subseque...
0
There is a survey that consists of `n` questions where each question's answer is either `0` (no) or `1` (yes). The survey was given to `m` students numbered from `0` to `m - 1` and `m` mentors numbered from `0` to `m - 1`. The answers of the students are represented by a 2D integer array `students` where `students[i]`...
Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a v...
Number of Different Subsequences GCDs
number-of-different-subsequences-gcds
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 array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed...
Heuristic algorithm may work.
Number of Different Subsequences GCDs
number-of-different-subsequences-gcds
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
There is a survey that consists of `n` questions where each question's answer is either `0` (no) or `1` (yes). The survey was given to `m` students numbered from `0` to `m - 1` and `m` mentors numbered from `0` to `m - 1`. The answers of the students are represented by a 2D integer array `students` where `students[i]`...
Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a v...
Python (Simple Maths)
number-of-different-subsequences-gcds
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 array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed...
Heuristic algorithm may work.
Python (Simple Maths)
number-of-different-subsequences-gcds
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
There is a survey that consists of `n` questions where each question's answer is either `0` (no) or `1` (yes). The survey was given to `m` students numbered from `0` to `m - 1` and `m` mentors numbered from `0` to `m - 1`. The answers of the students are represented by a 2D integer array `students` where `students[i]`...
Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a v...
[Python3] - Testing all possible GCDs - Thought Process in the Comments
number-of-different-subsequences-gcds
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs it will be very tedious to build a ll possible subarrays and check for their gcd, we can inverse the problem and check for all possbile gcds as the number of those is limited by the maximum number.\n\nThere are severy things about the ...
0
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed...
Heuristic algorithm may work.
[Python3] - Testing all possible GCDs - Thought Process in the Comments
number-of-different-subsequences-gcds
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nAs it will be very tedious to build a ll possible subarrays and check for their gcd, we can inverse the problem and check for all possbile gcds as the number of those is limited by the maximum number.\n\nThere are severy things about the ...
0
There is a survey that consists of `n` questions where each question's answer is either `0` (no) or `1` (yes). The survey was given to `m` students numbered from `0` to `m - 1` and `m` mentors numbered from `0` to `m - 1`. The answers of the students are represented by a 2D integer array `students` where `students[i]`...
Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a v...
python iterative solution beats 100%
number-of-different-subsequences-gcds
0
1
# Intuition\nOne of the things I noticed, was that the max size of `nums` is almost as big (half) as the maximum number in nums.\nThis means, iterating over all values is approx. as expensive as iterating the array.\nWe can also construct a set from `nums` making membership testing (almost) $$O(1)$$.\n\n# Approach\nWe ...
0
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed...
Heuristic algorithm may work.
python iterative solution beats 100%
number-of-different-subsequences-gcds
0
1
# Intuition\nOne of the things I noticed, was that the max size of `nums` is almost as big (half) as the maximum number in nums.\nThis means, iterating over all values is approx. as expensive as iterating the array.\nWe can also construct a set from `nums` making membership testing (almost) $$O(1)$$.\n\n# Approach\nWe ...
0
There is a survey that consists of `n` questions where each question's answer is either `0` (no) or `1` (yes). The survey was given to `m` students numbered from `0` to `m - 1` and `m` mentors numbered from `0` to `m - 1`. The answers of the students are represented by a 2D integer array `students` where `students[i]`...
Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a v...
🌟Fully Explained Extremly Fast Beat 100% Elegant Clean Solution🌟
number-of-different-subsequences-gcds
0
1
*Runtime: 5036 ms, faster than 100.00% of Python3 online submissions for Number of Different Subsequences GCDs.\nMemory Usage: 34.4 MB, less than 100.00% of Python3 online submissions for Number of Different Subsequences GCDs.*\n\n**Algorithm Steps:**\n1. Iterate over the possible GCD values (from 1 to maximal value in...
2
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed...
Heuristic algorithm may work.
🌟Fully Explained Extremly Fast Beat 100% Elegant Clean Solution🌟
number-of-different-subsequences-gcds
0
1
*Runtime: 5036 ms, faster than 100.00% of Python3 online submissions for Number of Different Subsequences GCDs.\nMemory Usage: 34.4 MB, less than 100.00% of Python3 online submissions for Number of Different Subsequences GCDs.*\n\n**Algorithm Steps:**\n1. Iterate over the possible GCD values (from 1 to maximal value in...
2
There is a survey that consists of `n` questions where each question's answer is either `0` (no) or `1` (yes). The survey was given to `m` students numbered from `0` to `m - 1` and `m` mentors numbered from `0` to `m - 1`. The answers of the students are represented by a 2D integer array `students` where `students[i]`...
Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a v...
Python || easy to understand || conceptual
number-of-different-subsequences-gcds
0
1
```\n# written by : dhruv vavliya\n\n\n\ndef gcd(a,b): # log(n)\n while b:\n a,b = b,a%b\n return a\n\t\nimport math\n\n# right but not accepted in python\ndef go(nums):\n b = max(nums)+1\n factor = [0]*b\n\n for i in range(len(nums)):\n for j in range(1,int(math.sqrt(nums[i...
1
You are given an array `nums` that consists of positive integers. The **GCD** of a sequence of numbers is defined as the greatest integer that divides **all** the numbers in the sequence evenly. * For example, the GCD of the sequence `[4,6,16]` is `2`. A **subsequence** of an array is a sequence that can be formed...
Heuristic algorithm may work.
Python || easy to understand || conceptual
number-of-different-subsequences-gcds
0
1
```\n# written by : dhruv vavliya\n\n\n\ndef gcd(a,b): # log(n)\n while b:\n a,b = b,a%b\n return a\n\t\nimport math\n\n# right but not accepted in python\ndef go(nums):\n b = max(nums)+1\n factor = [0]*b\n\n for i in range(len(nums)):\n for j in range(1,int(math.sqrt(nums[i...
1
There is a survey that consists of `n` questions where each question's answer is either `0` (no) or `1` (yes). The survey was given to `m` students numbered from `0` to `m - 1` and `m` mentors numbered from `0` to `m - 1`. The answers of the students are represented by a 2D integer array `students` where `students[i]`...
Think of how to check if a number x is a gcd of a subsequence. If there is such subsequence, then all of it will be divisible by x. Moreover, if you divide each number in the subsequence by x , then the gcd of the resulting numbers will be 1. Adding a number to a subsequence cannot increase its gcd. So, if there is a v...
[c++ & Python] short and concise
sign-of-the-product-of-an-array
0
1
Count total number of negetive numbers in array \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# C++\n```\nclass Solution {\npublic:\n int arraySign(vector<int>& nums) {\n ...
1
There is a function `signFunc(x)` that returns: * `1` if `x` is positive. * `-1` if `x` is negative. * `0` if `x` is equal to `0`. You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`. Return `signFunc(product)`. **Example 1:** **Input:** nums = \[-1,-2,-3,-4,...
As with any good dp problem that uses palindromes, try building the palindrome from the edges The prime point is to check that no two adjacent characters are equal, so save the past character while building the palindrome.
[c++ & Python] short and concise
sign-of-the-product-of-an-array
0
1
Count total number of negetive numbers in array \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# C++\n```\nclass Solution {\npublic:\n int arraySign(vector<int>& nums) {\n ...
1
You are given an integer array `nums` of size `n`. You are asked to solve `n` queries for each integer `i` in the range `0 <= i < n`. To solve the `ith` query: 1. Find the **minimum value** in each possible subarray of size `i + 1` of the array `nums`. 2. Find the **maximum** of those minimum values. This maximum i...
If there is a 0 in the array the answer is 0 To avoid overflow make all the negative numbers -1 and all positive numbers 1 and calculate the prod
[Python, Java] Elegant & Short | One Pass
sign-of-the-product-of-an-array
0
1
# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n\n```python []\nclass Solution:\n def arraySign(self, nums: List[int]) -> int:\n sign = 1\n\n for num in nums:\n if num < 0:\n sign *= -1\n if num == 0:\n return 0\n\n ...
1
There is a function `signFunc(x)` that returns: * `1` if `x` is positive. * `-1` if `x` is negative. * `0` if `x` is equal to `0`. You are given an integer array `nums`. Let `product` be the product of all values in the array `nums`. Return `signFunc(product)`. **Example 1:** **Input:** nums = \[-1,-2,-3,-4,...
As with any good dp problem that uses palindromes, try building the palindrome from the edges The prime point is to check that no two adjacent characters are equal, so save the past character while building the palindrome.