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
Python3 🐍 concise solution beats 99%
set-intersection-size-at-least-two
0
1
# Code\n```\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n ans = []\n for x, y in sorted(intervals, key=lambda x: (x[1], -x[0])): \n if not ans or ans[-2] < x: \n if ans and x <= ans[-1]: ans.append(y)\n else: ans.extend([...
0
We are given a list `schedule` of employees, which represents the working time for each employee. Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order. Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted...
null
Python | Greedy Fast Short Documented
set-intersection-size-at-least-two
0
1
# Intuition\r\n- If A contains B, A is fulfilled as long as B is fulfilled, ignore A\r\n- now we have only partially overlapped (or not) intervals, sorted\r\n- what needs to be done should be done, just greedily choose number to added to `nums` from each intervals\r\n- according to `nums` we can know how much shortage ...
0
You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively. A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`. * For example, if `intervals = [[1,3], [3,7], [8,9...
null
Python | Greedy Fast Short Documented
set-intersection-size-at-least-two
0
1
# Intuition\r\n- If A contains B, A is fulfilled as long as B is fulfilled, ignore A\r\n- now we have only partially overlapped (or not) intervals, sorted\r\n- what needs to be done should be done, just greedily choose number to added to `nums` from each intervals\r\n- according to `nums` we can know how much shortage ...
0
We are given a list `schedule` of employees, which represents the working time for each employee. Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order. Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted...
null
[Python3] greedy
set-intersection-size-at-least-two
0
1
\n```\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n ans = []\n for x, y in sorted(intervals, key=lambda x: (x[1], -x[0])): \n if not ans or ans[-2] < x: \n if ans and x <= ans[-1]: ans.append(y)\n else: ans.extend([y-1, y...
1
You are given a 2D integer array `intervals` where `intervals[i] = [starti, endi]` represents all the integers from `starti` to `endi` inclusively. A **containing set** is an array `nums` where each interval from `intervals` has **at least two** integers in `nums`. * For example, if `intervals = [[1,3], [3,7], [8,9...
null
[Python3] greedy
set-intersection-size-at-least-two
0
1
\n```\nclass Solution:\n def intersectionSizeTwo(self, intervals: List[List[int]]) -> int:\n ans = []\n for x, y in sorted(intervals, key=lambda x: (x[1], -x[0])): \n if not ans or ans[-2] < x: \n if ans and x <= ans[-1]: ans.append(y)\n else: ans.extend([y-1, y...
1
We are given a list `schedule` of employees, which represents the working time for each employee. Each employee has a list of non-overlapping `Intervals`, and these intervals are in sorted order. Return the list of finite intervals representing **common, positive-length free time** for _all_ employees, also in sorted...
null
Solution
special-binary-string
1
1
```C++ []\nclass Solution {\n public:\n string makeLargestSpecial(string S) {\n vector<string> specials;\n int count = 0;\n\n for (int i = 0, j = 0; j < S.length(); ++j) {\n count += S[j] == \'1\' ? 1 : -1;\n if (count == 0) {\n const string& inner = S.substr(i + 1, j - i - 1);\n speci...
1
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, s...
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
Solution
special-binary-string
1
1
```C++ []\nclass Solution {\n public:\n string makeLargestSpecial(string S) {\n vector<string> specials;\n int count = 0;\n\n for (int i = 0, j = 0; j < S.length(); ++j) {\n count += S[j] == \'1\' ? 1 : -1;\n if (count == 0) {\n const string& inner = S.substr(i + 1, j - i - 1);\n speci...
1
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these ...
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coord...
761: Solution with step by step explanation
special-binary-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\ncount = i = 0\nres = []\n```\n\nHere, we initialize:\n\ncount to track the balance of the 1s and 0s.\ni to remember the starting point of a chunk.\nres to store all the special chunks we find.\n```\nfor j, c in enumerat...
1
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, s...
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
761: Solution with step by step explanation
special-binary-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\ncount = i = 0\nres = []\n```\n\nHere, we initialize:\n\ncount to track the balance of the 1s and 0s.\ni to remember the starting point of a chunk.\nres to store all the special chunks we find.\n```\nfor j, c in enumerat...
1
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these ...
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coord...
📌📌 Easy-Approach || Well-Explained || Substring 🐍
special-binary-string
0
1
## IDEA:\n* If we regard 1, 0 in the definition of the special string as \'(\' and \')\' separately,\n\n* The problem is actually to get the string which is so-called valid parenthesis and meanwhile is the lexicographically largest.\n\n* It is intuitive that we prefer deeper valid parenthesis to sit in front (deeper me...
6
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, s...
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
📌📌 Easy-Approach || Well-Explained || Substring 🐍
special-binary-string
0
1
## IDEA:\n* If we regard 1, 0 in the definition of the special string as \'(\' and \')\' separately,\n\n* The problem is actually to get the string which is so-called valid parenthesis and meanwhile is the lexicographically largest.\n\n* It is intuitive that we prefer deeper valid parenthesis to sit in front (deeper me...
6
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these ...
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coord...
100% memory beats
special-binary-string
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
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, s...
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
100% memory beats
special-binary-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
0
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these ...
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coord...
Simple Explained Solution
special-binary-string
1
1
\n```\nclass Solution {\n public String makeLargestSpecial(String S) {\n int count = 0, i = 0;\n List<String> res = new ArrayList<String>();\n for (int j = 0; j < S.length(); ++j) {\n if (S.charAt(j) == \'1\') count++;\n else count--;\n if (count == 0) {\n r...
0
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, s...
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
Simple Explained Solution
special-binary-string
1
1
\n```\nclass Solution {\n public String makeLargestSpecial(String S) {\n int count = 0, i = 0;\n List<String> res = new ArrayList<String>();\n for (int j = 0; j < S.length(); ++j) {\n if (S.charAt(j) == \'1\') count++;\n else count--;\n if (count == 0) {\n r...
0
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these ...
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coord...
Fast python sol
special-binary-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought is that this problem can be solved using a recursive approach. We can divide the string into smaller substrings that are surrounded by \'1\' and \'0\' characters, and then recursively solve the problem for each substring....
0
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, s...
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
Fast python sol
special-binary-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nMy first thought is that this problem can be solved using a recursive approach. We can divide the string into smaller substrings that are surrounded by \'1\' and \'0\' characters, and then recursively solve the problem for each substring....
0
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these ...
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coord...
Python3 🐍 concise solution beats 99%
special-binary-string
0
1
# Code\n```\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n \n l = 0\n balance = 0\n sublist = []\n for r in range(len(s)):\n balance += 1 if s[r]==\'1\' else -1\n if balance==0:\n sublist.append("1" + self.makeLargestSpecial(s...
0
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, s...
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
Python3 🐍 concise solution beats 99%
special-binary-string
0
1
# Code\n```\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n \n l = 0\n balance = 0\n sublist = []\n for r in range(len(s)):\n balance += 1 if s[r]==\'1\' else -1\n if balance==0:\n sublist.append("1" + self.makeLargestSpecial(s...
0
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these ...
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coord...
[Python3] partition via recursion
special-binary-string
0
1
\n```\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n \n def fn(lo, hi): \n if lo == hi: return ""\n vals = []\n ii, prefix = lo, 0\n for i in range(lo, hi):\n prefix += 1 if s[i] == "1" else -1 \n if prefix == ...
1
**Special binary strings** are binary strings with the following two properties: * The number of `0`'s is equal to the number of `1`'s. * Every prefix of the binary string has at least as many `1`'s as `0`'s. You are given a **special binary** string `s`. A move consists of choosing two consecutive, non-empty, s...
Take all the intervals and do an "events" (or "line sweep") approach - an event of (x, OPEN) increases the number of active intervals, while (x, CLOSE) decreases it. Processing in sorted order from left to right, if the number of active intervals is zero, then you crossed a region of common free time.
[Python3] partition via recursion
special-binary-string
0
1
\n```\nclass Solution:\n def makeLargestSpecial(self, s: str) -> str:\n \n def fn(lo, hi): \n if lo == hi: return ""\n vals = []\n ii, prefix = lo, 0\n for i in range(lo, hi):\n prefix += 1 if s[i] == "1" else -1 \n if prefix == ...
1
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these ...
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coord...
762: Beats 91.74%, Solution with step by step explanation
prime-number-of-set-bits-in-binary-representation
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n```\n\nWe create a set of prime numbers which are less than 20. Since the maximum number of bits we are concerned with is 20 (for the given problem constraints), we only ne...
1
Given two integers `left` and `right`, return _the **count** of numbers in the **inclusive** range_ `[left, right]` _having a **prime number of set bits** in their binary representation_. Recall that the **number of set bits** an integer has is the number of `1`'s present when written in binary. * For example, `21`...
Create a hashmap so that D[x] = i whenever B[i] = x. Then, the answer is [D[x] for x in A].
762: Beats 91.74%, Solution with step by step explanation
prime-number-of-set-bits-in-binary-representation
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\n primes = {2, 3, 5, 7, 11, 13, 17, 19}\n```\n\nWe create a set of prime numbers which are less than 20. Since the maximum number of bits we are concerned with is 20 (for the given problem constraints), we only ne...
1
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * ...
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
Python one-liner
prime-number-of-set-bits-in-binary-representation
0
1
# Intuition\nJust iterate and sum\n\nNote that 10**6 has 20 bits, so we need only primes <= 20.\nAlso, python 3.10 introduced int.bit_count() that is more or less equivalent to bin(x).count("1") but obviously much faster.\n\n\n# Complexity\n- Time complexity: O(n) - iterating over the left..right range.\n\n- Space comp...
1
Given two integers `left` and `right`, return _the **count** of numbers in the **inclusive** range_ `[left, right]` _having a **prime number of set bits** in their binary representation_. Recall that the **number of set bits** an integer has is the number of `1`'s present when written in binary. * For example, `21`...
Create a hashmap so that D[x] = i whenever B[i] = x. Then, the answer is [D[x] for x in A].
Python one-liner
prime-number-of-set-bits-in-binary-representation
0
1
# Intuition\nJust iterate and sum\n\nNote that 10**6 has 20 bits, so we need only primes <= 20.\nAlso, python 3.10 introduced int.bit_count() that is more or less equivalent to bin(x).count("1") but obviously much faster.\n\n\n# Complexity\n- Time complexity: O(n) - iterating over the left..right range.\n\n- Space comp...
1
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * ...
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
Solution
prime-number-of-set-bits-in-binary-representation
1
1
```C++ []\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n int ans=0;\n while(left<=right) {\n int cnt=__builtin_popcount(left);\n if(cnt==2 || cnt==3 || cnt==5 || cnt==7 || cnt==11 || cnt==13 || cnt==17 || cnt==19)\n ++ans;\n +...
2
Given two integers `left` and `right`, return _the **count** of numbers in the **inclusive** range_ `[left, right]` _having a **prime number of set bits** in their binary representation_. Recall that the **number of set bits** an integer has is the number of `1`'s present when written in binary. * For example, `21`...
Create a hashmap so that D[x] = i whenever B[i] = x. Then, the answer is [D[x] for x in A].
Solution
prime-number-of-set-bits-in-binary-representation
1
1
```C++ []\nclass Solution {\npublic:\n int countPrimeSetBits(int left, int right) {\n int ans=0;\n while(left<=right) {\n int cnt=__builtin_popcount(left);\n if(cnt==2 || cnt==3 || cnt==5 || cnt==7 || cnt==11 || cnt==13 || cnt==17 || cnt==19)\n ++ans;\n +...
2
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * ...
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
prime-number-of-set-bits-in-binary-representation
prime-number-of-set-bits-in-binary-representation
0
1
# Code\n```\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n count = 0\n for i in range(left,right + 1):\n a = bin(i)[2:]\n t = a.count("1")\n l = []\n if t==1:\n pass\n else:\n for i in ...
1
Given two integers `left` and `right`, return _the **count** of numbers in the **inclusive** range_ `[left, right]` _having a **prime number of set bits** in their binary representation_. Recall that the **number of set bits** an integer has is the number of `1`'s present when written in binary. * For example, `21`...
Create a hashmap so that D[x] = i whenever B[i] = x. Then, the answer is [D[x] for x in A].
prime-number-of-set-bits-in-binary-representation
prime-number-of-set-bits-in-binary-representation
0
1
# Code\n```\nclass Solution:\n def countPrimeSetBits(self, left: int, right: int) -> int:\n count = 0\n for i in range(left,right + 1):\n a = bin(i)[2:]\n t = a.count("1")\n l = []\n if t==1:\n pass\n else:\n for i in ...
1
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * ...
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
Easy Python solution
prime-number-of-set-bits-in-binary-representation
0
1
```\ndef countPrimeSetBits(self, left: int, right: int) -> int:\n count=0\n for i in range(left,right+1):\n c=0\n n=bin(i).count("1")\n for j in range(1,n+1):\n if n%j==0:\n c+=1\n if c==2:\n count+=1\n ret...
4
Given two integers `left` and `right`, return _the **count** of numbers in the **inclusive** range_ `[left, right]` _having a **prime number of set bits** in their binary representation_. Recall that the **number of set bits** an integer has is the number of `1`'s present when written in binary. * For example, `21`...
Create a hashmap so that D[x] = i whenever B[i] = x. Then, the answer is [D[x] for x in A].
Easy Python solution
prime-number-of-set-bits-in-binary-representation
0
1
```\ndef countPrimeSetBits(self, left: int, right: int) -> int:\n count=0\n for i in range(left,right+1):\n c=0\n n=bin(i).count("1")\n for j in range(1,n+1):\n if n%j==0:\n c+=1\n if c==2:\n count+=1\n ret...
4
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * ...
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
✔️ [Python3] GREEDY VALIDATION ヾ(^-^)ノ, Explained
partition-labels
0
1
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nSince each letter can appear only in one part, we cannot form a part shorter than the index of the last appearance of a letter subtracted by an index of the first appearance. For example here (**a**bsf**a**b) the len...
90
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these ...
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coo...
✔️ [Python3] GREEDY VALIDATION ヾ(^-^)ノ, Explained
partition-labels
0
1
**UPVOTE if you like (\uD83C\uDF38\u25E0\u203F\u25E0), If you have any question, feel free to ask.**\n\nSince each letter can appear only in one part, we cannot form a part shorter than the index of the last appearance of a letter subtracted by an index of the first appearance. For example here (**a**bsf**a**b) the len...
90
You are given an integer array `arr`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[5,4,3,2...
Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
Python 91% O(n) intuitive implementation; simple counter solution
partition-labels
0
1
# Intuition\n\nPartitions are defined such that all characters in a partition are only found in this specific partition; any character in one partition must not be in any other partition. \n\nThe \'greedy\' idea is always adding the first character to the partition, and keeping track of how many of this character we ha...
1
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these ...
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coo...
Python 91% O(n) intuitive implementation; simple counter solution
partition-labels
0
1
# Intuition\n\nPartitions are defined such that all characters in a partition are only found in this specific partition; any character in one partition must not be in any other partition. \n\nThe \'greedy\' idea is always adding the first character to the partition, and keeping track of how many of this character we ha...
1
You are given an integer array `arr`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[5,4,3,2...
Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
763: Solution with step by step explanation
partition-labels
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\n last_occurrence = {char: index for index, char in enumerate(s)}\n```\n\nUsing a dictionary comprehension, we create a dictionary called last_occurrence. The keys are the characters in the string s, and the value...
4
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these ...
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coo...
763: Solution with step by step explanation
partition-labels
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\n last_occurrence = {char: index for index, char in enumerate(s)}\n```\n\nUsing a dictionary comprehension, we create a dictionary called last_occurrence. The keys are the characters in the string s, and the value...
4
You are given an integer array `arr`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[5,4,3,2...
Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
Simple O(n) Python Solution || With Explanation
partition-labels
0
1
# Intuition\n###### This algorithm iterates through the string, tracking the last occurrence index of each character. It creates partitions by extending them from the start character to the last occurrence of any character within the current partition. When the end of a partition is reached, its length is added to the ...
2
You are given a string `s`. We want to partition the string into as many parts as possible so that each letter appears in at most one part. Note that the partition is done so that after concatenating all the parts in order, the resultant string should be `s`. Return _a list of integers representing the size of these ...
Draw a line from (x, y) to (x+1, y+1) if we see a "1", else to (x+1, y-1). A special substring is just a line that starts and ends at the same y-coordinate, and that is the lowest y-coordinate reached. Call a mountain a special substring with no special prefixes - ie. only at the beginning and end is the lowest y-coo...
Simple O(n) Python Solution || With Explanation
partition-labels
0
1
# Intuition\n###### This algorithm iterates through the string, tracking the last occurrence index of each character. It creates partitions by extending them from the start character to the last occurrence of any character within the current partition. When the end of a partition is reached, its length is added to the ...
2
You are given an integer array `arr`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[5,4,3,2...
Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
Solution
largest-plus-sign
1
1
```C++ []\nclass Solution {\npublic:\n int orderOfLargestPlusSign(int N, vector<vector<int>>& mines) {\n int ans=0,s,i,j,k;\n int dp[N+2][N+2][4],v[N][N];\n for(i=0;i<N;i++)for(j=0;j<N;j++)v[i][j]=1;\n for(i=0;i<mines.size();i++)v[mines[i][0]][mines[i][1]]=0;\n memset(dp,0,sizeof d...
1
You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`. Return _the order of the largest **axis-aligned** plus sign of_ ...
null
Solution
largest-plus-sign
1
1
```C++ []\nclass Solution {\npublic:\n int orderOfLargestPlusSign(int N, vector<vector<int>>& mines) {\n int ans=0,s,i,j,k;\n int dp[N+2][N+2][4],v[N][N];\n for(i=0;i<N;i++)for(j=0;j<N;j++)v[i][j]=1;\n for(i=0;i<mines.size();i++)v[mines[i][0]][mines[i][1]]=0;\n memset(dp,0,sizeof d...
1
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number...
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
764: Memory Beats 91.40%, Solution with step by step explanation
largest-plus-sign
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\ngrid = [[n] * n for _ in range(n)]\n```\nWe initialize a grid with all values set to n. Why? Because in the best case, if a cell isn\'t blocked (by a mine), its maximum potential reach in any direction is n (from one ed...
3
You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`. Return _the order of the largest **axis-aligned** plus sign of_ ...
null
764: Memory Beats 91.40%, Solution with step by step explanation
largest-plus-sign
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\ngrid = [[n] * n for _ in range(n)]\n```\nWe initialize a grid with all values set to n. Why? Because in the best case, if a cell isn\'t blocked (by a mine), its maximum potential reach in any direction is n (from one ed...
3
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number...
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
Python (Simple DP)
largest-plus-sign
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n^2)\n\n- Space complexity: O(n^2)\n\n# Code\n```\nclass Solution:\n def orderOfLargestPlusSign(self, n, mines):\n dp, a...
1
You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`. Return _the order of the largest **axis-aligned** plus sign of_ ...
null
Python (Simple DP)
largest-plus-sign
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n^2)\n\n- Space complexity: O(n^2)\n\n# Code\n```\nclass Solution:\n def orderOfLargestPlusSign(self, n, mines):\n dp, a...
1
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number...
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
[Python] Two concise loops. TC: O(n^2), SC: O(n^2)
largest-plus-sign
0
1
\n```\nclass Solution:\n def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:\n mine_set = set([(x, y) for x, y in mines])\n row = lambda: [defaultdict(int) for _ in range(n)]\n dp = [row() for _ in range(n)]\n t, b, l, rt = \'t\', \'b\', \'l\', \'r\'\n res = 0\...
0
You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`. Return _the order of the largest **axis-aligned** plus sign of_ ...
null
[Python] Two concise loops. TC: O(n^2), SC: O(n^2)
largest-plus-sign
0
1
\n```\nclass Solution:\n def orderOfLargestPlusSign(self, n: int, mines: List[List[int]]) -> int:\n mine_set = set([(x, y) for x, y in mines])\n row = lambda: [defaultdict(int) for _ in range(n)]\n dp = [row() for _ in range(n)]\n t, b, l, rt = \'t\', \'b\', \'l\', \'r\'\n res = 0\...
0
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number...
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
Minimum Distance DP Explained! [Python3]
largest-plus-sign
0
1
# Intuition\n\nIf we know the minimum distance to either an edge or mine in the x direction for each cell and also the minimum distance to either an edge or mine in the y direction for each cell, we can solve the problem!\n\nWe can find these values using DP!\n\nSee the commented code below.\n\n# Complexity\n- Time com...
0
You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`. Return _the order of the largest **axis-aligned** plus sign of_ ...
null
Minimum Distance DP Explained! [Python3]
largest-plus-sign
0
1
# Intuition\n\nIf we know the minimum distance to either an edge or mine in the x direction for each cell and also the minimum distance to either an edge or mine in the y direction for each cell, we can solve the problem!\n\nWe can find these values using DP!\n\nSee the commented code below.\n\n# Complexity\n- Time com...
0
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number...
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
DP with space optim. in single pass using nested loops with in-place matrix updates. (Explained)
largest-plus-sign
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity ...
0
You are given an integer `n`. You have an `n x n` binary grid `grid` with all values initially `1`'s except for some indices given in the array `mines`. The `ith` element of the array `mines` is defined as `mines[i] = [xi, yi]` where `grid[xi][yi] == 0`. Return _the order of the largest **axis-aligned** plus sign of_ ...
null
DP with space optim. in single pass using nested loops with in-place matrix updates. (Explained)
largest-plus-sign
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n^2)$$\n<!-- Add your space complexity ...
0
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number...
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
Solution
couples-holding-hands
1
1
```C++ []\nclass UnionFind {\n public:\n UnionFind(int n) : count(n), id(n) {\n iota(begin(id), end(id), 0);\n }\n void union_(int u, int v) {\n const int i = find(u);\n const int j = find(v);\n if (i == j)\n return;\n id[i] = j;\n --count;\n }\n int getCount() const {\n return count;\n ...
1
There are `n` couples sitting in `2n` seats arranged in a row and want to hold hands. The people and seats are represented by an integer array `row` where `row[i]` is the ID of the person sitting in the `ith` seat. The couples are numbered in order, the first couple being `(0, 1)`, the second couple being `(2, 3)`, an...
null
765: Solution with step by step explanation
couples-holding-hands
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThe solution uses the union-find data structure. Union-find helps in understanding the component or group to which an element belongs.\n\n```\ndef minSwapsCouples(self, row: List[int]) -> int:\n ...\n n = len(row) // 2...
2
There are `n` couples sitting in `2n` seats arranged in a row and want to hold hands. The people and seats are represented by an integer array `row` where `row[i]` is the ID of the person sitting in the `ith` seat. The couples are numbered in order, the first couple being `(0, 1)`, the second couple being `(2, 3)`, an...
null
Simple Solution with proper comments | TC - O(n) | Without using Union, cyclic swapping
couples-holding-hands
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...
1
There are `n` couples sitting in `2n` seats arranged in a row and want to hold hands. The people and seats are represented by an integer array `row` where `row[i]` is the ID of the person sitting in the `ith` seat. The couples are numbered in order, the first couple being `(0, 1)`, the second couple being `(2, 3)`, an...
null
Number of connected components
couples-holding-hands
0
1
\n\n# Code\n```\nclass Solution:\n def minSwapsCouples(self, row: List[int]) -> int:\n n = len(row) \n """\n 1 node = 1 couple\n edge between two nodes mean that 1 swap should take place to make one of the node correct - that node will have correct pair .\n so the degree of a node...
1
There are `n` couples sitting in `2n` seats arranged in a row and want to hold hands. The people and seats are represented by an integer array `row` where `row[i]` is the ID of the person sitting in the `ith` seat. The couples are numbered in order, the first couple being `(0, 1)`, the second couple being `(2, 3)`, an...
null
🐍 python, approach using cycle sort; O(N) time complexity
couples-holding-hands
0
1
# Approach\nlet\'s look at the following example:\n[[1,0],[2,5],[4,6],[3,7]]\nwhich after 2 swaps we have\n[[1,0],[2,3],[4,5],[6,7]]\nWe can easily notice that if the first element on the sublist is odd, the partner should be one value less and if it is even the partner should be one value more.\n\nNow, let\'s go back ...
1
There are `n` couples sitting in `2n` seats arranged in a row and want to hold hands. The people and seats are represented by an integer array `row` where `row[i]` is the ID of the person sitting in the `ith` seat. The couples are numbered in order, the first couple being `(0, 1)`, the second couple being `(2, 3)`, an...
null
766: Beats 91.88%, Solution with step by step explanation
toeplitz-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n```\nfor i in range(1, len(matrix)):\n for j in range(1, len(matrix[0])):\n```\nWe use two nested loops to iterate over the matrix. We start from 1 because the topmost row and leftmost column don\'t have a top-left neighb...
1
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._ A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements. **Example 1:** **Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\] **Output:** true **Explanation:** In the above gr...
null
Python Solution || Simple Approach
toeplitz-matrix
0
1
class Solution:\n def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:\n \n for i in range(0, len(matrix)-1):\n \n for j in range(0, len(matrix[i])-1):\n \n if matrix[i][j] != matrix[i+1][j+1]:\n return False\n ...
1
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._ A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements. **Example 1:** **Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\] **Output:** true **Explanation:** In the above gr...
null
Simplest Python Solution || O(n^2)
toeplitz-matrix
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(n^2)\n\n- Space complexity:\n(1)\n\n# Code\n```\nclass Solution:\n def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool...
1
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._ A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements. **Example 1:** **Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\] **Output:** true **Explanation:** In the above gr...
null
SIMPLE SOLUTION
toeplitz-matrix
0
1
```\nclass Solution:\n def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:\n m=len(matrix)\n n=len(matrix[0])\n for i in range(m-2,-1,-1):\n curr=matrix[i][0]\n row=i\n col=0\n while row<m and col<n:\n if curr!=matrix[row][col]:...
1
Given an `m x n` `matrix`, return _`true` if the matrix is Toeplitz. Otherwise, return `false`._ A matrix is **Toeplitz** if every diagonal from top-left to bottom-right has the same elements. **Example 1:** **Input:** matrix = \[\[1,2,3,4\],\[5,1,2,3\],\[9,5,1,2\]\] **Output:** true **Explanation:** In the above gr...
null
Python 3 || Runtime 26ms
reorganize-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * ...
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
Python 3 || Runtime 26ms
reorganize-string
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ --...
2
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`. The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both square...
Alternate placing the most common letters.
easy solution
reorganize-string
0
1
\n \n\n# Code\n```\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n count = Counter(s)\n maxHeap = [[-cnt,char] for char,cnt in count.items()]\n heapq.heapify(maxHeap)\n\n\n prev,res = None,""\n res = ""\n while prev or maxHeap:\n if prev and not ma...
1
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * ...
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
easy solution
reorganize-string
0
1
\n \n\n# Code\n```\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n count = Counter(s)\n maxHeap = [[-cnt,char] for char,cnt in count.items()]\n heapq.heapify(maxHeap)\n\n\n prev,res = None,""\n res = ""\n while prev or maxHeap:\n if prev and not ma...
1
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`. The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both square...
Alternate placing the most common letters.
Python Solution Best Approach Reorganize String
reorganize-string
0
1
```\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n dic = {}\n for i in s:\n dic[i] = dic.get(i,0)+1 \n max_key = None\n max_value = None\n\n for key, value in dic.items():\n if max_value is None or value > max_value:\n max_v...
1
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * ...
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
Python Solution Best Approach Reorganize String
reorganize-string
0
1
```\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n dic = {}\n for i in s:\n dic[i] = dic.get(i,0)+1 \n max_key = None\n max_value = None\n\n for key, value in dic.items():\n if max_value is None or value > max_value:\n max_v...
1
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`. The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both square...
Alternate placing the most common letters.
✅ 100% 2-Approaches Priority Queue & Sort
reorganize-string
1
1
# Problem Understanding\n\nIn the "767. Reorganize String" problem, we are given a string `s` consisting of lowercase English letters. The task is to rearrange the string such that no two adjacent characters are the same. If it\'s not possible to do so, we return an empty string.\n\nFor instance, given the input "aab...
106
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * ...
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
✅ 100% 2-Approaches Priority Queue & Sort
reorganize-string
1
1
# Problem Understanding\n\nIn the "767. Reorganize String" problem, we are given a string `s` consisting of lowercase English letters. The task is to rearrange the string such that no two adjacent characters are the same. If it\'s not possible to do so, we return an empty string.\n\nFor instance, given the input "aab...
106
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`. The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both square...
Alternate placing the most common letters.
✅Easy Solution🔥Python3/C#/C++/Java/Python🔥With 🗺️Image🗺️
reorganize-string
1
1
\n![Screenshot 2023-08-20 065922.png](https://assets.leetcode.com/users/images/62945814-a6d0-4e8c-89c9-6f7a605695a0_1692760772.3556774.png)\n\n```Python3 []\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n count = Counter(s)\n maxHeap = [[-cnt, char] for char, cnt in count.items()]\n ...
42
Given a string `s`, rearrange the characters of `s` so that any two adjacent characters are not the same. Return _any possible rearrangement of_ `s` _or return_ `" "` _if not possible_. **Example 1:** **Input:** s = "aab" **Output:** "aba" **Example 2:** **Input:** s = "aaab" **Output:** "" **Constraints:** * ...
Write a helper function to count the number of set bits in a number, then check whether the number of set bits is 2, 3, 5, 7, 11, 13, 17 or 19.
✅Easy Solution🔥Python3/C#/C++/Java/Python🔥With 🗺️Image🗺️
reorganize-string
1
1
\n![Screenshot 2023-08-20 065922.png](https://assets.leetcode.com/users/images/62945814-a6d0-4e8c-89c9-6f7a605695a0_1692760772.3556774.png)\n\n```Python3 []\nclass Solution:\n def reorganizeString(self, s: str) -> str:\n count = Counter(s)\n maxHeap = [[-cnt, char] for char, cnt in count.items()]\n ...
42
You are given an `n x n` integer matrix `grid` where each value `grid[i][j]` represents the elevation at that point `(i, j)`. The rain starts to fall. At time `t`, the depth of the water everywhere is `t`. You can swim from a square to another 4-directionally adjacent square if and only if the elevation of both square...
Alternate placing the most common letters.
Python || Sorting+Hashmap || O(n logn)
max-chunks-to-make-sorted-ii
0
1
We have 2 arrays. One sorted and one unsorted.Now traverse over both.For one array increment by one for every value and for other decrement.We delete an element from map when its count is reached 0, it means when one element who was in excess in one array has been compensated by the same value in other array.(basically...
1
You are given an integer array `arr`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[5,4,3,2...
Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
Python || Sorting+Hashmap || O(n logn)
max-chunks-to-make-sorted-ii
0
1
We have 2 arrays. One sorted and one unsorted.Now traverse over both.For one array increment by one for every value and for other decrement.We delete an element from map when its count is reached 0, it means when one element who was in excess in one array has been compensated by the same value in other array.(basically...
1
We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`. * For example, for `n = 3`, the `1st` row is `0`, the `2nd` row is `01`, and the `3rd` r...
Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.
📌📌 Easy-to-Understand || 98% faster || Well-Explained 🐍
max-chunks-to-make-sorted-ii
0
1
## IDEA:\n**Take this [ 2, 1, 7, 6, 3, 5, 4, 9, 8 ] as an example and once try yourself to split it into maximum chunks using stack.**\n\nYou will come to following conclusions : \n* The max number in the left chunk must always be <= the max number in the right chunk. \n\n* We only need to maintain the max number of ea...
16
You are given an integer array `arr`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number of chunks we can make to sort the array_. **Example 1:** **Input:** arr = \[5,4,3,2...
Try to greedily choose the smallest partition that includes the first letter. If you have something like "abaccbdeffed", then you might need to add b. You can use an map like "last['b'] = 5" to help you expand the width of your partition.
📌📌 Easy-to-Understand || 98% faster || Well-Explained 🐍
max-chunks-to-make-sorted-ii
0
1
## IDEA:\n**Take this [ 2, 1, 7, 6, 3, 5, 4, 9, 8 ] as an example and once try yourself to split it into maximum chunks using stack.**\n\nYou will come to following conclusions : \n* The max number in the left chunk must always be <= the max number in the right chunk. \n\n* We only need to maintain the max number of ea...
16
We build a table of `n` rows (**1-indexed**). We start by writing `0` in the `1st` row. Now in every subsequent row, we look at the previous row and replace each occurrence of `0` with `01`, and each occurrence of `1` with `10`. * For example, for `n = 3`, the `1st` row is `0`, the `2nd` row is `01`, and the `3rd` r...
Each k for which some permutation of arr[:k] is equal to sorted(arr)[:k] is where we should cut each chunk.
Python Easy Sol(28ms) with Detailed Explanation
max-chunks-to-make-sorted
0
1
\n\n \n So the idea is that we initally set a max_so_far which is initally taken as the first ele of arr\n \n secondly we are checking two things first if max_so_far < arr[i] if so then update max_so_far\n \n and then we are checking that once the max_so_far has reached the ind...
28
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number...
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
Python Easy Sol(28ms) with Detailed Explanation
max-chunks-to-make-sorted
0
1
\n\n \n So the idea is that we initally set a max_so_far which is initally taken as the first ele of arr\n \n secondly we are checking two things first if max_so_far < arr[i] if so then update max_so_far\n \n and then we are checking that once the max_so_far has reached the ind...
28
Given four integers `sx`, `sy`, `tx`, and `ty`, return `true` _if it is possible to convert the point_ `(sx, sy)` _to the point_ `(tx, ty)` _through some operations__, or_ `false` _otherwise_. The allowed operation on some point `(x, y)` is to convert it to either `(x, x + y)` or `(x + y, y)`. **Example 1:** **Input...
The first chunk can be found as the smallest k for which A[:k+1] == [0, 1, 2, ...k]; then we repeat this process.
Solution
max-chunks-to-make-sorted
1
1
```C++ []\nclass Solution {\npublic:\n int maxChunksToSorted(vector<int>& arr) {\n int ch=0;\n int right = arr[0];\n for(int i=0;i<arr.size();i++){\n right = max(right, arr[i]);\n if(right == i)ch++;\n }\n return ch;\n }\n};\n```\n\n```Python3 []\nclass Sol...
2
You are given an integer array `arr` of length `n` that represents a permutation of the integers in the range `[0, n - 1]`. We split `arr` into some number of **chunks** (i.e., partitions), and individually sort each chunk. After concatenating them, the result should equal the sorted array. Return _the largest number...
For each direction such as "left", find left[r][c] = the number of 1s you will see before a zero starting at r, c and walking left. You can find this in N^2 time with a dp. The largest plus sign at r, c is just the minimum of left[r][c], up[r][c] etc.
Solution
max-chunks-to-make-sorted
1
1
```C++ []\nclass Solution {\npublic:\n int maxChunksToSorted(vector<int>& arr) {\n int ch=0;\n int right = arr[0];\n for(int i=0;i<arr.size();i++){\n right = max(right, arr[i]);\n if(right == i)ch++;\n }\n return ch;\n }\n};\n```\n\n```Python3 []\nclass Sol...
2
Given four integers `sx`, `sy`, `tx`, and `ty`, return `true` _if it is possible to convert the point_ `(sx, sy)` _to the point_ `(tx, ty)` _through some operations__, or_ `false` _otherwise_. The allowed operation on some point `(x, y)` is to convert it to either `(x, x + y)` or `(x + y, y)`. **Example 1:** **Input...
The first chunk can be found as the smallest k for which A[:k+1] == [0, 1, 2, ...k]; then we repeat this process.
Solution
basic-calculator-iv
1
1
```C++ []\nclass Solution {\npublic:\n vector<string> basicCalculatorIV(string expression, vector<string>& evalvars, vector<int>& evalints) {\n unordered_map<string, int> mp;\n int n = evalvars.size();\n for (int i = 0; i < n; ++i) mp[evalvars[i]] = evalints[i];\n int pos = 0;\n un...
1
Given an expression such as `expression = "e + 8 - a + 5 "` and an evaluation map such as `{ "e ": 1}` (given in terms of `evalvars = [ "e "]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `[ "-1*a ", "14 "]` * An expression alternates chunks and symbols, with a space...
Say there are N two-seat couches. For each couple, draw an edge from the couch of one partner to the couch of the other partner.
Solution
basic-calculator-iv
1
1
```C++ []\nclass Solution {\npublic:\n vector<string> basicCalculatorIV(string expression, vector<string>& evalvars, vector<int>& evalints) {\n unordered_map<string, int> mp;\n int n = evalvars.size();\n for (int i = 0; i < n; ++i) mp[evalvars[i]] = evalints[i];\n int pos = 0;\n un...
1
There is a forest with an unknown number of rabbits. We asked n rabbits **"How many rabbits have the same color as you? "** and collected the answers in an integer array `answers` where `answers[i]` is the answer of the `ith` rabbit. Given the array `answers`, return _the minimum number of rabbits that could be in the...
One way is with a Polynomial class. For example, * `Poly:add(this, that)` returns the result of `this + that`. * `Poly:sub(this, that)` returns the result of `this - that`. * `Poly:mul(this, that)` returns the result of `this * that`. * `Poly:evaluate(this, evalmap)` returns the polynomial after replacing all free va...
Standard Parser
basic-calculator-iv
0
1
```python\nclass Atom:\n def __init__(self, h={}):\n self.h = defaultdict(int)\n for k, v in h.items(): self.h[k] += v\n\n def __add__(self, other):\n h = defaultdict(int)\n for k in self.h: h[k] += self.h[k]\n for k in other.h: h[k] += other.h[k]\n return Atom({k: v for ...
0
Given an expression such as `expression = "e + 8 - a + 5 "` and an evaluation map such as `{ "e ": 1}` (given in terms of `evalvars = [ "e "]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `[ "-1*a ", "14 "]` * An expression alternates chunks and symbols, with a space...
Say there are N two-seat couches. For each couple, draw an edge from the couch of one partner to the couch of the other partner.
Standard Parser
basic-calculator-iv
0
1
```python\nclass Atom:\n def __init__(self, h={}):\n self.h = defaultdict(int)\n for k, v in h.items(): self.h[k] += v\n\n def __add__(self, other):\n h = defaultdict(int)\n for k in self.h: h[k] += self.h[k]\n for k in other.h: h[k] += other.h[k]\n return Atom({k: v for ...
0
There is a forest with an unknown number of rabbits. We asked n rabbits **"How many rabbits have the same color as you? "** and collected the answers in an integer array `answers` where `answers[i]` is the answer of the `ith` rabbit. Given the array `answers`, return _the minimum number of rabbits that could be in the...
One way is with a Polynomial class. For example, * `Poly:add(this, that)` returns the result of `this + that`. * `Poly:sub(this, that)` returns the result of `this - that`. * `Poly:mul(this, that)` returns the result of `this * that`. * `Poly:evaluate(this, evalmap)` returns the polynomial after replacing all free va...
770: Solution with step by step explanation
basic-calculator-iv
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n__init__: Initializes the term with given expression or term.\n__add__, __sub__, __mul__: Arithmetic operations to add, subtract, and multiply two terms.\nget: Returns the term as a list of strings.\n_exp: Splits the variabl...
0
Given an expression such as `expression = "e + 8 - a + 5 "` and an evaluation map such as `{ "e ": 1}` (given in terms of `evalvars = [ "e "]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `[ "-1*a ", "14 "]` * An expression alternates chunks and symbols, with a space...
Say there are N two-seat couches. For each couple, draw an edge from the couch of one partner to the couch of the other partner.
770: Solution with step by step explanation
basic-calculator-iv
0
1
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n__init__: Initializes the term with given expression or term.\n__add__, __sub__, __mul__: Arithmetic operations to add, subtract, and multiply two terms.\nget: Returns the term as a list of strings.\n_exp: Splits the variabl...
0
There is a forest with an unknown number of rabbits. We asked n rabbits **"How many rabbits have the same color as you? "** and collected the answers in an integer array `answers` where `answers[i]` is the answer of the `ith` rabbit. Given the array `answers`, return _the minimum number of rabbits that could be in the...
One way is with a Polynomial class. For example, * `Poly:add(this, that)` returns the result of `this + that`. * `Poly:sub(this, that)` returns the result of `this - that`. * `Poly:mul(this, that)` returns the result of `this * that`. * `Poly:evaluate(this, evalmap)` returns the polynomial after replacing all free va...
[Python] Cheating with eval(), thoughts?
basic-calculator-iv
0
1
### Explanation\n\nI basically built a class that automatically handles the addition, subtraction and multiplication of two expressions (called \'terms\'), overriding the `__add__()`, `__sub__()`, and `__mul__()` dunder methods respectively. All that\'s left to do is to parse each variable as a \'term\', and let Python...
1
Given an expression such as `expression = "e + 8 - a + 5 "` and an evaluation map such as `{ "e ": 1}` (given in terms of `evalvars = [ "e "]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `[ "-1*a ", "14 "]` * An expression alternates chunks and symbols, with a space...
Say there are N two-seat couches. For each couple, draw an edge from the couch of one partner to the couch of the other partner.
[Python] Cheating with eval(), thoughts?
basic-calculator-iv
0
1
### Explanation\n\nI basically built a class that automatically handles the addition, subtraction and multiplication of two expressions (called \'terms\'), overriding the `__add__()`, `__sub__()`, and `__mul__()` dunder methods respectively. All that\'s left to do is to parse each variable as a \'term\', and let Python...
1
There is a forest with an unknown number of rabbits. We asked n rabbits **"How many rabbits have the same color as you? "** and collected the answers in an integer array `answers` where `answers[i]` is the answer of the `ith` rabbit. Given the array `answers`, return _the minimum number of rabbits that could be in the...
One way is with a Polynomial class. For example, * `Poly:add(this, that)` returns the result of `this + that`. * `Poly:sub(this, that)` returns the result of `this - that`. * `Poly:mul(this, that)` returns the result of `this * that`. * `Poly:evaluate(this, evalmap)` returns the polynomial after replacing all free va...
[C++] [Python] Brute Force Approach || Too Easy || Fully Explained
jewels-and-stones
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nSuppose we have the following inputs:\n```\nstring jw = "aA";\nstring st = "aAAbbbb";\n```\n\nNow, let\'s go through the function step by step:\n\n1. Initialize `count` to 0.\n2. Start a loop to iterate through the `jw` string using an index-based loo...
1
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type o...
null
[C++] [Python] Brute Force Approach || Too Easy || Fully Explained
jewels-and-stones
0
1
# Approach\n<!-- Describe your approach to solving the problem. -->\nSuppose we have the following inputs:\n```\nstring jw = "aA";\nstring st = "aAAbbbb";\n```\n\nNow, let\'s go through the function step by step:\n\n1. Initialize `count` to 0.\n2. Start a loop to iterate through the `jw` string using an index-based loo...
1
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other. Return _the minimum number of moves to transform the board into a **chessboard board**_. If the task is impossible, return `-1`. A **chessboard board** is a board where no `0`'s a...
For each stone, check if it is a jewel.
Solution
jewels-and-stones
1
1
```C++ []\nclass Solution {\npublic:\n int numJewelsInStones(string jewels, string stones) {\n int res=0;\n for (char c:stones) if (jewels.find(c)<jewels.length()) res++;\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) ->...
1
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type o...
null
Solution
jewels-and-stones
1
1
```C++ []\nclass Solution {\npublic:\n int numJewelsInStones(string jewels, string stones) {\n int res=0;\n for (char c:stones) if (jewels.find(c)<jewels.length()) res++;\n return res;\n }\n};\n```\n\n```Python3 []\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) ->...
1
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other. Return _the minimum number of moves to transform the board into a **chessboard board**_. If the task is impossible, return `-1`. A **chessboard board** is a board where no `0`'s a...
For each stone, check if it is a jewel.
Python3 Hash Map Beats 98.25% Runtime | 65.81% Memory
jewels-and-stones
0
1
# Intuition\nJust count the number of occurrences of each jewel in stones via a hash map.\n\n# Approach\nCreate a hash map with each character in jewels as key and their frequency in stones as value. Initially all jewel counts are set to 0. Iterate over the stones string checking on each iteration whether it is a jewel...
3
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type o...
null
Python3 Hash Map Beats 98.25% Runtime | 65.81% Memory
jewels-and-stones
0
1
# Intuition\nJust count the number of occurrences of each jewel in stones via a hash map.\n\n# Approach\nCreate a hash map with each character in jewels as key and their frequency in stones as value. Initially all jewel counts are set to 0. Iterate over the stones string checking on each iteration whether it is a jewel...
3
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other. Return _the minimum number of moves to transform the board into a **chessboard board**_. If the task is impossible, return `-1`. A **chessboard board** is a board where no `0`'s a...
For each stone, check if it is a jewel.
Solution of jewels and stones problem
jewels-and-stones
0
1
# Approach\n- Step one: create list of all jewels\n- Step two: check if the stone is on the list\n- Step three: return answer\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$ - as algorithm takes linear time and\n.count() function takes linear time --> O(n*n) == O(n^2).\n\n- Space complexity:\n$$O(n)$$ - as we use extra...
3
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type o...
null
Solution of jewels and stones problem
jewels-and-stones
0
1
# Approach\n- Step one: create list of all jewels\n- Step two: check if the stone is on the list\n- Step three: return answer\n\n# Complexity\n- Time complexity:\n$$O(n^2)$$ - as algorithm takes linear time and\n.count() function takes linear time --> O(n*n) == O(n^2).\n\n- Space complexity:\n$$O(n)$$ - as we use extra...
3
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other. Return _the minimum number of moves to transform the board into a **chessboard board**_. If the task is impossible, return `-1`. A **chessboard board** is a board where no `0`'s a...
For each stone, check if it is a jewel.
Simple 1 liner, with line by line explanation
jewels-and-stones
0
1
\n# Code\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n return sum(x in jewels for x in stones)\n```\n# Line by Line\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n result = 0\n for x in list(stones):\n ...
4
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type o...
null
Simple 1 liner, with line by line explanation
jewels-and-stones
0
1
\n# Code\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n return sum(x in jewels for x in stones)\n```\n# Line by Line\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n result = 0\n for x in list(stones):\n ...
4
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other. Return _the minimum number of moves to transform the board into a **chessboard board**_. If the task is impossible, return `-1`. A **chessboard board** is a board where no `0`'s a...
For each stone, check if it is a jewel.
Easy to understand Python code
jewels-and-stones
0
1
# Complexity\n- Time complexity\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n m = {}\n for i in stones:\n if i in m:\n m[i] += 1\n else:\n m[i] = 1\n ans = 0...
1
You're given strings `jewels` representing the types of stones that are jewels, and `stones` representing the stones you have. Each character in `stones` is a type of stone you have. You want to know how many of the stones you have are also jewels. Letters are case sensitive, so `"a "` is considered a different type o...
null
Easy to understand Python code
jewels-and-stones
0
1
# Complexity\n- Time complexity\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution:\n def numJewelsInStones(self, jewels: str, stones: str) -> int:\n m = {}\n for i in stones:\n if i in m:\n m[i] += 1\n else:\n m[i] = 1\n ans = 0...
1
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other. Return _the minimum number of moves to transform the board into a **chessboard board**_. If the task is impossible, return `-1`. A **chessboard board** is a board where no `0`'s a...
For each stone, check if it is a jewel.
Python 3 || 17 lines, BFS || T/M: 99% / 91%
sliding-puzzle
0
1
```\nmoves = ((1,3), (0,2,4), (1,5),\n (0,4), (1,3,5), (2,4))\n\nclass Solution:\n def slidingPuzzle(self, board: List[List[int]]) -> int:\n\n state = (*board[0], *board[1])\n queue, seen, cnt = deque([state]), set(), 0\n\n while queue:\n\n for _ in range(len(queue)):\n ...
3
On an `2 x 3` board, there are five tiles labeled from `1` to `5`, and an empty square represented by `0`. A **move** consists of choosing `0` and a 4-directionally adjacent number and swapping it. The state of the board is solved if and only if the board is `[[1,2,3],[4,5,0]]`. Given the puzzle board `board`, return...
null
Python 3 || 17 lines, BFS || T/M: 99% / 91%
sliding-puzzle
0
1
```\nmoves = ((1,3), (0,2,4), (1,5),\n (0,4), (1,3,5), (2,4))\n\nclass Solution:\n def slidingPuzzle(self, board: List[List[int]]) -> int:\n\n state = (*board[0], *board[1])\n queue, seen, cnt = deque([state]), set(), 0\n\n while queue:\n\n for _ in range(len(queue)):\n ...
3
There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`. You are also given three integers `src`, `dst`, and `k`, return _**the cheapest price** from_ `src` _...
Perform a breadth-first-search, where the nodes are the puzzle boards and edges are if two puzzle boards can be transformed into one another with one move.