Leetcodeleetcode.ca
https://leetcode.ca/
2416 - Sum of Prefix Scores of Strings
Formatted question description: https://leetcode.ca/all/2416.html 2416. Sum of Prefix Scores of Strings Difficulty: Hard. Related Topics: . Similar Questions: Design Add and Search Words Data Structure, Maximum XOR of Two Numbers in an Array, Map Sum Pairs. Problem You are given an array words of size n consisting of non-empty strings. We define the score of a string word as the number of strings words[i] such that word is a prefix of words[i]. For example, if words = ["a", "ab", "abc", "cab"], then the score of "ab" is 2, since "ab" is a prefix of both "ab" and "abc". Return an array **answer of size n where answer[i] is the sum of scores of every non-empty prefix of **words[i]. Note that a string is considered as a prefix of itself. Example 1: Input: words = ["abc","ab","bc","b"] Output: [5,4,3,2] Explanation: The answer for each string is the following: - "abc" has 3 prefixes: "a", "ab", and "abc". - There are 2 strings with the prefix "a", 2 strings with the prefix "ab", and 1 string with the prefix "abc". The total is answer[0] = 2 + 2 + 1 = 5. - "ab" has 2 prefixes: "a" and "ab". - There are 2 strings with the prefix "a", and 2 strings with the prefix "ab". The total is answer[1] = 2 + 2 = 4. - "bc" has 2 prefixes: "b" and "bc". - There are 2 strings with the prefix "b", and 1 string with the prefix "bc". The total is answer[2] = 2 + 1 = 3. - "b" has 1 prefix: "b". - There are 2 strings with the prefix "b". The total is answer[3] = 2. Example 2: Input: words = ["abcd"] Output: [4] Explanation: "abcd" has 4 prefixes: "a", "ab", "abc", and "abcd". Each prefix has a score of one, so the total is answer[0] = 1 + 1 + 1 + 1 = 4. Constraints: 1 <= words.length <= 1000 1 <= words[i].length <= 1000 words[i] consists of lowercase English letters. Solution (Java, C++, Python) Java C++ Python class Trie { Trie[] ch = new Trie[26]; int visited = 0; } class Solution { public int[] sumPrefixScores(String[] words) { Trie trie = new Trie(); int[] ans = new int[words.length]; int k = 0; for (String x: words) { Trie t = trie; for (int i = 0; i < x.length(); i++) { int c = x.charAt(i) - 'a'; if (t.ch[c] == null) t.ch[c] = new Trie(); t.ch[c].visited++; t = t.ch[c]; } } for (String x: words) { Trie t = trie; int curr = 0; for (int i = 0; i < x.length(); i++) { int c = x.charAt(i) - 'a'; curr += t.ch[c].visited; t = t.ch[c]; } ans[k++] = curr; } return ans; } } Todo # 2416. Sum of Prefix Scores of Strings # https://leetcode.com/problems/sum-of-prefix-scores-of-strings class Solution: def sumPrefixScores(self, words: List[str]) -> List[int]: N = len(words) res = [0] * N mp = defaultdict(int) for word in words: prefix = "" for...
Fri, 04 Nov 2022 11:21:01 -0700
https://leetcode.ca/2022-11-04-2416-Sum-of-Prefix-Scores-of-Strings/
https://leetcode.ca/2022-11-04-2416-Sum-of-Prefix-Scores-of-Strings/2415 - Reverse Odd Levels of Binary Tree
Formatted question description: https://leetcode.ca/all/2415.html 2415. Reverse Odd Levels of Binary Tree Difficulty: Medium. Related Topics: . Similar Questions: Invert Binary Tree. Problem Given the root of a perfect binary tree, reverse the node values at each odd level of the tree. For example, suppose the node values at level 3 are [2,1,3,4,7,11,29,18], then it should become [18,29,11,7,4,3,1,2]. Return the root of the reversed tree. A binary tree is perfect if all parent nodes have two children and all leaves are on the same level. The level of a node is the number of edges along the path between it and the root node. Example 1: Input: root = [2,3,5,8,13,21,34] Output: [2,5,3,8,13,21,34] Explanation: The tree has only one odd level. The nodes at level 1 are 3, 5 respectively, which are reversed and become 5, 3. Example 2: Input: root = [7,13,11] Output: [7,11,13] Explanation: The nodes at level 1 are 13, 11, which are reversed and become 11, 13. Example 3: Input: root = [0,1,2,0,0,0,0,1,1,1,1,2,2,2,2] Output: [0,2,1,0,0,0,0,2,2,2,2,1,1,1,1] Explanation: The odd levels have non-zero values. The nodes at level 1 were 1, 2, and are 2, 1 after the reversal. The nodes at level 3 were 1, 1, 1, 1, 2, 2, 2, 2, and are 2, 2, 2, 2, 1, 1, 1, 1 after the reversal. Constraints: The number of nodes in the tree is in the range [1, 214]. 0 <= Node.val <= 105 root is a perfect binary tree. Solution (Java, C++, Python) Java C++ Python /** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode() {} * TreeNode(int val) { this.val = val; } * TreeNode(int val, TreeNode left, TreeNode right) { * this.val = val; * this.left = left; * this.right = right; * } * } */ class Solution { public TreeNode reverseOddLevels(TreeNode root) { if(root == null) return root; Queue<TreeNode> queue = new LinkedList<>(); int level = 0; queue.add(root); while (!queue.isEmpty()) { int size = queue.size(); level++; TreeNode[] arr = new TreeNode[size]; for (int i = 0; i < size; i++) { TreeNode cur = queue.poll(); arr[i] = cur; if(cur.left != null){ queue.add(cur.left); queue.add(cur.right); } } if (level % 2 == 0) { int left = 0; int right = size - 1; while (left < right) { int leftVal = arr[left].val; arr[left].val = arr[right].val; arr[right].val = leftVal; left++; right--; } } } return root; } } Todo # 2415. Reverse Odd Levels of Binary Tree # https://leetcode.com/problems/reverse-odd-levels-of-binary-tree/ # Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def reverseOddLevels(self, root: Optional[TreeNode]) -> Optional[TreeNode]: res = [] dq = deque([root]) level = 0 while dq: n = len(dq) curr = [] for _ in range(n): node = dq.popleft() curr.append(node.val) for child in filter(None, (node.left, node.right)): dq.append(child) if level % 2 == 1: curr.reverse() res += curr level +=...
Thu, 03 Nov 2022 11:21:01 -0700
https://leetcode.ca/2022-11-03-2415-Reverse-Odd-Levels-of-Binary-Tree/
https://leetcode.ca/2022-11-03-2415-Reverse-Odd-Levels-of-Binary-Tree/2414 - Length of the Longest Alphabetical Continuous Substring
Formatted question description: https://leetcode.ca/all/2414.html
2414. Length of the Longest Alphabetical Continuous Substring
Difficulty: Medium.
Related Topics: .
Similar Questions: Longest Consecutive Sequence, Arithmetic Slices, Max Consecutive Ones, Maximum Number of Vowels in a Substring of Given Length, Number of Zero-Filled Subarrays.
Problem
An alphabetical continuous string is a string consisting of consecutive letters in the alphabet. In other words, it is any substring of the string "abcdefghijklmnopqrstuvwxyz".
For example, "abc" is an alphabetical continuous string, while "acb" and "za" are not.
Given a string s consisting of lowercase letters only, return the length of the **longest alphabetical continuous substring.**
Example 1:
Input: s = "abacaba"
Output: 2
Explanation: There are 4 distinct continuous substrings: "a", "b", "c" and "ab".
"ab" is the longest continuous substring.
Example 2:
Input: s = "abcde"
Output: 5
Explanation: "abcde" is the longest continuous substring.
Constraints:
1 <= s.length <= 105
s consists of only English lowercase letters.
Solution (Java, C++, Python)
Java
C++
Python
class Solution {
public int longestContinuousSubstring(String s) {
int x = 0, len = 0, res = 0;
for(char ch : s.toCharArray()) {
len = ch-'a'-x==1 ? len+1 : 1; // add to len or restart
res = Math.max(res, len);
x = ch-'a';
}
return res;
}
}
Todo
# 2414. Length of the Longest Alphabetical Continuous Substring
# https://leetcode.com/problems/length-of-the-longest-alphabetical-continuous-substring/
class Solution:
def longestContinuousSubstring(self, s: str) -> int:
N = len(s)
res = length = 1
def f(x):
return ord(x) - ord("a")
prev = f(s[0])
for i in range(1, N):
curr = f(s[i])
if prev + 1 == curr:
length += 1
res = max(res, length)
else:
length = 1
prev = curr
return res
Explain:
nope.
Complexity:
Time complexity : O(n).
Space complexity : O(n).
All Problems
All Solutions
Wed, 02 Nov 2022 11:21:01 -0700
https://leetcode.ca/2022-11-02-2414-Length-of-the-Longest-Alphabetical-Continuous-Substring/
https://leetcode.ca/2022-11-02-2414-Length-of-the-Longest-Alphabetical-Continuous-Substring/2413 - Smallest Even Multiple
Formatted question description: https://leetcode.ca/all/2413.html
2413. Smallest Even Multiple
Difficulty: Easy.
Related Topics: .
Similar Questions: Greatest Common Divisor of Strings, Three Divisors, Find Greatest Common Divisor of Array.
Problem
Given a positive integer n, return the smallest positive integer that is a multiple of **both 2 and n.
**Example 1:
Input: n = 5
Output: 10
Explanation: The smallest multiple of both 5 and 2 is 10.
Example 2:
Input: n = 6
Output: 6
Explanation: The smallest multiple of both 6 and 2 is 6. Note that a number is a multiple of itself.
Constraints:
1 <= n <= 150
Solution (Java, C++, Python)
Java
C++
Python
class Solution {
public int smallestEvenMultiple(int n) {
int k=2*n;
for(int i=2*n;i>=n;i--)
{
if(i%n==0&&i%2==0)
k=i;
}
return k;
}
}
Todo
# 2413. Smallest Even Multiple
# https://leetcode.com/problems/smallest-even-multiple/
class Solution:
def smallestEvenMultiple(self, n: int) -> int:
for x in range(1, n * 2 + 1):
if x % 2 == 0 and x % n == 0:
return x
return -1
Explain:
nope.
Complexity:
Time complexity : O(n).
Space complexity : O(n).
All Problems
All Solutions
Tue, 01 Nov 2022 11:21:01 -0700
https://leetcode.ca/2022-11-01-2413-Smallest-Even-Multiple/
https://leetcode.ca/2022-11-01-2413-Smallest-Even-Multiple/2412 - Minimum Money Required Before Transactions
Formatted question description: https://leetcode.ca/all/2412.html
2412. Minimum Money Required Before Transactions
Difficulty: Hard.
Related Topics: .
Similar Questions: .
Problem
You are given a 0-indexed 2D integer array transactions, where transactions[i] = [costi, cashbacki].
The array describes transactions, where each transaction must be completed exactly once in some order. At any given moment, you have a certain amount of money. In order to complete transaction i, money >= costi must hold true. After performing a transaction, money becomes money - costi + cashbacki.
Return** the minimum amount of money required before any transaction so that all of the transactions can be completed regardless of the order of the transactions.**
Example 1:
Input: transactions = [[2,1],[5,0],[4,2]]
Output: 10
Explanation:
Starting with money = 10, the transactions can be performed in any order.
It can be shown that starting with money < 10 will fail to complete all transactions in some order.
Example 2:
Input: transactions = [[3,0],[0,3]]
Output: 3
Explanation:
- If transactions are in the order [[3,0],[0,3]], the minimum money required to complete the transactions is 3.
- If transactions are in the order [[0,3],[3,0]], the minimum money required to complete the transactions is 0.
Thus, starting with money = 3, the transactions can be performed in any order.
Constraints:
1 <= transactions.length <= 105
transactions[i].length == 2
0 <= costi, cashbacki <= 109
Solution (Java, C++, Python)
Java
C++
Python
class Solution {
public long minimumMoney(int[][] transactions) {
Arrays.sort(transactions,(int a[],int b[])->(a[1]-b[1]));
long max=0,ans=0,ab=0;
for(int a[]:transactions){
if(a[0]>a[1]){
max+=a[0];
ans=Math.max(ans,max);
max-=a[1];
}
else ab=Math.max(ab,a[0]);
}
ans=Math.max(ans,max+ab);
return ans;
}
}
Todo
# 2412. Minimum Money Required Before Transactions
# https://leetcode.com/problems/minimum-money-required-before-transactions
class Solution:
def minimumMoney(self, A: List[List[int]]) -> int:
return sum(max(0, i - j) for i, j in A) + max(map(min, A))
Explain:
nope.
Complexity:
Time complexity : O(n).
Space complexity : O(n).
All Problems
All Solutions
Mon, 31 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-31-2412-Minimum-Money-Required-Before-Transactions/
https://leetcode.ca/2022-10-31-2412-Minimum-Money-Required-Before-Transactions/2411 - Smallest Subarrays With Maximum Bitwise OR
Formatted question description: https://leetcode.ca/all/2411.html 2411. Smallest Subarrays With Maximum Bitwise OR Difficulty: Medium. Related Topics: . Similar Questions: Merge k Sorted Lists, Bitwise ORs of Subarrays. Problem You are given a 0-indexed array nums of length n, consisting of non-negative integers. For each index i from 0 to n - 1, you must determine the size of the minimum sized non-empty subarray of nums starting at i (inclusive) that has the maximum possible bitwise OR. In other words, let Bij be the bitwise OR of the subarray nums[i...j]. You need to find the smallest subarray starting at i, such that bitwise OR of this subarray is equal to max(Bik) where i <= k <= n - 1. The bitwise OR of an array is the bitwise OR of all the numbers in it. Return an integer array **answer of size n where answer[i] is the length of the minimum sized subarray starting at i with maximum bitwise OR.** A subarray is a contiguous non-empty sequence of elements within an array. Example 1: Input: nums = [1,0,2,1,3] Output: [3,3,2,2,1] Explanation: The maximum possible bitwise OR starting at any index is 3. - Starting at index 0, the shortest subarray that yields it is [1,0,2]. - Starting at index 1, the shortest subarray that yields the maximum bitwise OR is [0,2,1]. - Starting at index 2, the shortest subarray that yields the maximum bitwise OR is [2,1]. - Starting at index 3, the shortest subarray that yields the maximum bitwise OR is [1,3]. - Starting at index 4, the shortest subarray that yields the maximum bitwise OR is [3]. Therefore, we return [3,3,2,2,1]. Example 2: Input: nums = [1,2] Output: [2,1] Explanation: Starting at index 0, the shortest subarray that yields the maximum bitwise OR is of length 2. Starting at index 1, the shortest subarray that yields the maximum bitwise OR is of length 1. Therefore, we return [2,1]. Constraints: n == nums.length 1 <= n <= 105 0 <= nums[i] <= 109 Solution (Java, C++, Python) Java C++ Python class Solution { public int[] smallestSubarrays(int[] nums) { TreeSet<Integer>[] ar = new TreeSet[32]; for (int i = 0; i < 32; i++) ar[i] = new TreeSet<>(); for (int i = 0; i < nums.length; i++) { for (int j = 0; j < 32; j++) { if ((nums[i] >> j & 1) == 1) ar[j].add(i); } } int ans[] = new int[nums.length]; for (int i = 0; i < nums.length; i++) { int max = i; for (TreeSet<Integer> set : ar) { if (!set.isEmpty()) { max = Math.max(max, set.first()); set.remove(i); } } ans[i] = (max - i + 1); } return ans; } } Todo # 2411. Smallest Subarrays With Maximum Bitwise OR # https://leetcode.com/problems/smallest-subarrays-with-maximum-bitwise-or/ class Solution: def smallestSubarrays(self, nums: List[int]) -> List[int]: N = len(nums) res = [0] * N last = [0] * 32 for i in range(N - 1, -1, -1): for k in range(32, -1, -1): if (nums[i] >> k) & 1 > 0: last[k]...
Sun, 30 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-30-2411-Smallest-Subarrays-With-Maximum-Bitwise-OR/
https://leetcode.ca/2022-10-30-2411-Smallest-Subarrays-With-Maximum-Bitwise-OR/2410 - Maximum Matching of Players With Trainers
Formatted question description: https://leetcode.ca/all/2410.html
2410. Maximum Matching of Players With Trainers
Difficulty: Medium.
Related Topics: .
Similar Questions: Most Profit Assigning Work, Long Pressed Name, Interval List Intersections, Largest Merge Of Two Strings, Maximum Number of Tasks You Can Assign, Successful Pairs of Spells and Potions, The Latest Time to Catch a Bus.
Problem
You are given a 0-indexed integer array players, where players[i] represents the ability of the ith player. You are also given a 0-indexed integer array trainers, where trainers[j] represents the **training capacity **of the jth trainer.
The ith player can match with the jth trainer if the player’s ability is less than or equal to the trainer’s training capacity. Additionally, the ith player can be matched with at most one trainer, and the jth trainer can be matched with at most one player.
Return the **maximum number of matchings between players and trainers that satisfy these conditions.**
Example 1:
Input: players = [4,7,9], trainers = [8,2,5,8]
Output: 2
Explanation:
One of the ways we can form two matchings is as follows:
- players[0] can be matched with trainers[0] since 4 <= 8.
- players[1] can be matched with trainers[3] since 7 <= 8.
It can be proven that 2 is the maximum number of matchings that can be formed.
Example 2:
Input: players = [1,1,1], trainers = [10]
Output: 1
Explanation:
The trainer can be matched with any of the 3 players.
Each player can only be matched with one trainer, so the maximum answer is 1.
Constraints:
1 <= players.length, trainers.length <= 105
1 <= players[i], trainers[j] <= 109
Solution (Java, C++, Python)
Java
C++
Python
class Solution {
public int matchPlayersAndTrainers(int[] player, int[] train) {
Arrays.sort(player);
Arrays.sort(train);
int i = 0, j = 0, res = 0;
while(j<train.length && i<player.length) {
if(player[i]>train[j])
while(j<train.length && train[j]<player[i]) // find trainer
j++;
else { res++; i++; j++; } // can train.
}
return res;
}
}
Todo
# 2410. Maximum Matching of Players With Trainers
# https://leetcode.com/problems/maximum-matching-of-players-with-trainers/
class Solution:
def matchPlayersAndTrainers(self, players: List[int], trainers: List[int]) -> int:
N, M = len(players), len(trainers)
players.sort()
trainers.sort()
res = 0
firstPlayer = players[0]
j = bisect_left(trainers, firstPlayer)
if j == M: return 0
for player in players:
while j < M and player > trainers[j]:
j += 1
if j == M: break
if player <= trainers[j]:
res += 1
j += 1
return res
Explain:
nope.
Complexity:
Time complexity : O(n).
Space complexity : O(n).
All Problems
All Solutions
Sat, 29 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-29-2410-Maximum-Matching-of-Players-With-Trainers/
https://leetcode.ca/2022-10-29-2410-Maximum-Matching-of-Players-With-Trainers/2409 - Count Days Spent Together
Formatted question description: https://leetcode.ca/all/2409.html 2409. Count Days Spent Together Difficulty: Easy. Related Topics: . Similar Questions: Number of Days Between Two Dates, Minimum Number of Operations to Convert Time. Problem Alice and Bob are traveling to Rome for separate business meetings. You are given 4 strings arriveAlice, leaveAlice, arriveBob, and leaveBob. Alice will be in the city from the dates arriveAlice to leaveAlice (inclusive), while Bob will be in the city from the dates arriveBob to leaveBob (inclusive). Each will be a 5-character string in the format "MM-DD", corresponding to the month and day of the date. Return** the total number of days that Alice and Bob are in Rome together.** You can assume that all dates occur in the same calendar year, which is not a leap year. Note that the number of days per month can be represented as: [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]. Example 1: Input: arriveAlice = "08-15", leaveAlice = "08-18", arriveBob = "08-16", leaveBob = "08-19" Output: 3 Explanation: Alice will be in Rome from August 15 to August 18. Bob will be in Rome from August 16 to August 19. They are both in Rome together on August 16th, 17th, and 18th, so the answer is 3. Example 2: Input: arriveAlice = "10-01", leaveAlice = "10-31", arriveBob = "11-01", leaveBob = "12-31" Output: 0 Explanation: There is no day when Alice and Bob are in Rome together, so we return 0. Constraints: All dates are provided in the format "MM-DD". Alice and Bob’s arrival dates are earlier than or equal to their leaving dates. The given dates are valid dates of a non-leap year. Solution (Java, C++, Python) Java C++ Python class Solution { int[] months = new int[]{31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; public int countDaysTogether(String s1, String e1, String s2, String e2) { int[] a = new int[]{ getVal(s1), getVal(e1) }; int[] b = new int[]{ getVal(s2), getVal(e2) }; if(b[0]>a[1] || a[0]>b[1]) return 0; // no overlap int start = Math.max(a[0], b[0]); int last = Math.min(a[1], b[1]); return last-start+1; } // convert date to nth day of year, (1st-365th day) int getVal(String str){ int idx = 0; int mon = (str.charAt(0)-'0')*10+(str.charAt(1)-'0'); int day = (str.charAt(3)-'0')*10+(str.charAt(4)-'0'); for(int i=1; i<mon; i++) idx += months[i-1]; // or use prefix sum return idx+day; } } Todo # 2409. Count Days Spent Together # https://leetcode.com/problems/count-days-spent-together/ class Solution: def countDaysTogether(self, a: str, b: str, c: str, d: str) -> int: months = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] days = [[0] * (month + 1) for month in months] def go(A, B): a, b = map(int, A.split('-')) c, d = map(int, B.split('-')) if a != c: for month in range(a, c): if month == a: for day in range(b, months[month] + 1): days[month][day] += 1 else: for day in range(months[month] + 1): days[month][day] += 1 for day in range(1, d + 1): days[c][day] += 1 return...
Fri, 28 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-28-2409-Count-Days-Spent-Together/
https://leetcode.ca/2022-10-28-2409-Count-Days-Spent-Together/2408 - Design SQL
Formatted question description: https://leetcode.ca/all/2408.html
Todo
All Problems
All Solutions
Thu, 27 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-27-2408-Design-SQL/
https://leetcode.ca/2022-10-27-2408-Design-SQL/2407 - Longest Increasing Subsequence II
Formatted question description: https://leetcode.ca/all/2407.html 2407. Longest Increasing Subsequence II Difficulty: Hard. Related Topics: . Similar Questions: Longest Increasing Subsequence, Number of Longest Increasing Subsequence, Longest Continuous Increasing Subsequence, Longest Substring of One Repeating Character, Booking Concert Tickets in Groups. Problem You are given an integer array nums and an integer k. Find the longest subsequence of nums that meets the following requirements: The subsequence is strictly increasing and The difference between adjacent elements in the subsequence is at most k. Return** the length of the longest subsequence that meets the requirements.** A subsequence is an array that can be derived from another array by deleting some or no elements without changing the order of the remaining elements. Example 1: Input: nums = [4,2,1,4,3,4,5,8,15], k = 3 Output: 5 Explanation: The longest subsequence that meets the requirements is [1,3,4,5,8]. The subsequence has a length of 5, so we return 5. Note that the subsequence [1,3,4,5,8,15] does not meet the requirements because 15 - 8 = 7 is larger than 3. Example 2: Input: nums = [7,4,5,1,8,12,4,7], k = 5 Output: 4 Explanation: The longest subsequence that meets the requirements is [4,5,8,12]. The subsequence has a length of 4, so we return 4. Example 3: Input: nums = [1,5], k = 1 Output: 1 Explanation: The longest subsequence that meets the requirements is [1]. The subsequence has a length of 1, so we return 1. Constraints: 1 <= nums.length <= 105 1 <= nums[i], k <= 105 Solution (Java, C++, Python) Java C++ Python class Solution { public int lengthOfLIS(int[] nums, int k) { SegmentTree root = new SegmentTree(1, 100000); int res = 0; for (int num : nums) { int preMax = root.rangeMaxQuery(root, num - k, num - 1); root.update(root, num, preMax + 1); res = Math.max(res, preMax + 1); } return res; } } class SegmentTree { SegmentTree left, right; int start, end, val; public SegmentTree(int start, int end) { this.start = start; this.end = end; setup(this, start, end); } public void setup(SegmentTree node, int start, int end) { if (start == end) return; int mid = start + (end - start) / 2; if (node.left == null) { node.left = new SegmentTree(start, mid); node.right = new SegmentTree(mid + 1, end); } setup(node.left, start, mid); setup(node.right, mid + 1, end); node.val = Math.max(node.left.val, node.right.val); } public void update(SegmentTree node, int index, int val) { if (index < node.start || index > node.end) return; if (node.start == node.end && node.start == index) { node.val = val; return; } update(node.left, index, val); update(node.right, index, val); node.val = Math.max(node.left.val, node.right.val); } public int rangeMaxQuery(SegmentTree node, int start, int end) { if (node.start > end || node.end < start) return 0; if (node.start >= start && node.end <= end) return node.val; return Math.max(rangeMaxQuery(node.left, start, end), rangeMaxQuery(node.right, start, end)); } } Todo # 2407. Longest Increasing Subsequence II # https://leetcode.com/problems/longest-increasing-subsequence-ii class SegmentTree: # https://github.com/cheran-senthil/PyRival/blob/master/pyrival/data_structures/SegmentTree.py def __init__(self, data, default=0, func=max): """initialize the segment tree with data""" self._default = default self._func = func self._len =...
Wed, 26 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-26-2407-Longest-Increasing-Subsequence-II/
https://leetcode.ca/2022-10-26-2407-Longest-Increasing-Subsequence-II/2406 - Divide Intervals Into Minimum Number of Groups
Formatted question description: https://leetcode.ca/all/2406.html
2406. Divide Intervals Into Minimum Number of Groups
Difficulty: Medium.
Related Topics: .
Similar Questions: Merge Intervals, Minimum Number of Frogs Croaking, Average Height of Buildings in Each Segment.
Problem
You are given a 2D integer array intervals where intervals[i] = [lefti, righti] represents the inclusive interval [lefti, righti].
You have to divide the intervals into one or more groups such that each interval is in exactly one group, and no two intervals that are in the same group intersect each other.
Return the **minimum number of groups you need to make**.
Two intervals intersect if there is at least one common number between them. For example, the intervals [1, 5] and [5, 8] intersect.
Example 1:
Input: intervals = [[5,10],[6,8],[1,5],[2,3],[1,10]]
Output: 3
Explanation: We can divide the intervals into the following groups:
- Group 1: [1, 5], [6, 8].
- Group 2: [2, 3], [5, 10].
- Group 3: [1, 10].
It can be proven that it is not possible to divide the intervals into fewer than 3 groups.
Example 2:
Input: intervals = [[1,3],[5,6],[8,10],[11,13]]
Output: 1
Explanation: None of the intervals overlap, so we can put all of them in one group.
Constraints:
1 <= intervals.length <= 105
intervals[i].length == 2
1 <= lefti <= righti <= 106
Solution (Java, C++, Python)
Java
C++
Python
class Solution {
public int minGroups(int[][] intervals) {
int m = 0;
for(int i[] : intervals){
m = Math.max(m,i[0]);
m = Math.max(m,i[1]);
}
long arr[] = new long[m+2];
for(int a[] : intervals){
arr[a[0]] += 1;
arr[a[1]+1] -= 1;
}
long max = 0l;
for(int i = 1; i <= m +1; i++){
arr[i] += arr[i-1];
max = Math.max(max,arr[i]);
}
return (int)max;
}
}
Todo
# 2406. Divide Intervals Into Minimum Number of Groups
# https://leetcode.com/problems/divide-intervals-into-minimum-number-of-groups/
from sortedcontainers import SortedList
class Solution:
def minGroups(self, intervals: List[List[int]]) -> int:
n = len(intervals)
intervals.sort()
sl = SortedList(intervals)
res = 0
while len(sl) > 0:
s, e = sl[0]
nextStart = e + 1
index = sl.bisect_left([nextStart, ])
while index < len(sl):
ns, ne = sl[index]
nextStart = ne + 1
sl.remove([ns, ne])
index = sl.bisect_left([nextStart, ])
sl.remove([s, e])
res += 1
return res
Explain:
nope.
Complexity:
Time complexity : O(n).
Space complexity : O(n).
All Problems
All Solutions
Tue, 25 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-25-2406-Divide-Intervals-Into-Minimum-Number-of-Groups/
https://leetcode.ca/2022-10-25-2406-Divide-Intervals-Into-Minimum-Number-of-Groups/2405 - Optimal Partition of String
Formatted question description: https://leetcode.ca/all/2405.html
2405. Optimal Partition of String
Difficulty: Medium.
Related Topics: .
Similar Questions: Longest Substring Without Repeating Characters, Longest Substring with At Least K Repeating Characters, Partition Labels, Partition Array into Disjoint Intervals.
Problem
Given a string s, partition the string into one or more substrings such that the characters in each substring are unique. That is, no letter appears in a single substring more than once.
Return the **minimum number of substrings in such a partition.**
Note that each character should belong to exactly one substring in a partition.
Example 1:
Input: s = "abacaba"
Output: 4
Explanation:
Two possible partitions are ("a","ba","cab","a") and ("ab","a","ca","ba").
It can be shown that 4 is the minimum number of substrings needed.
Example 2:
Input: s = "ssssss"
Output: 6
Explanation:
The only valid partition is ("s","s","s","s","s","s").
Constraints:
1 <= s.length <= 105
s consists of only English lowercase letters.
Solution (Java, C++, Python)
Java
C++
Python
class Solution {
public int partitionString(String s) {
int count = (s.isEmpty()) ? 0 : 1;
HashSet<Character> letters = new HashSet<Character>(); // creating a set to find unique letters in substring
for (int i = 0; i < s.length(); i++) {
if (letters.contains(s.charAt(i))) { // if we encounter a duplicate
letters.clear(); // remove all letters in set
count++; // increment count
}
letters.add(s.charAt(i));
}
return count;
}
}
Todo
# 2405. Optimal Partition of String
# https://leetcode.com/problems/optimal-partition-of-string/
class Solution:
def partitionString(self, s: str) -> int:
n = len(s)
res = 1
seen = set()
for j, x in enumerate(s):
if x in seen:
seen.clear()
res += 1
seen.add(x)
return res
Explain:
nope.
Complexity:
Time complexity : O(n).
Space complexity : O(n).
All Problems
All Solutions
Mon, 24 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-24-2405-Optimal-Partition-of-String/
https://leetcode.ca/2022-10-24-2405-Optimal-Partition-of-String/2404 - Most Frequent Even Element
Formatted question description: https://leetcode.ca/all/2404.html
2404. Most Frequent Even Element
Difficulty: Easy.
Related Topics: .
Similar Questions: Majority Element, Majority Element II, Top K Frequent Elements, Sort Characters By Frequency.
Problem
Given an integer array nums, return the most frequent even element.
If there is a tie, return the smallest one. If there is no such element, return -1.
Example 1:
Input: nums = [0,1,2,2,4,4,1]
Output: 2
Explanation:
The even elements are 0, 2, and 4. Of these, 2 and 4 appear the most.
We return the smallest one, which is 2.
Example 2:
Input: nums = [4,4,4,9,2,4]
Output: 4
Explanation: 4 is the even element appears the most.
Example 3:
Input: nums = [29,47,21,41,13,37,25,7]
Output: -1
Explanation: There is no even element.
Constraints:
1 <= nums.length <= 2000
0 <= nums[i] <= 105
Solution (Java, C++, Python)
Java
C++
Python
class Solution {
public int mostFrequentEven(int[] A) {
HashMap<Integer,Integer> mp= new HashMap<>();
int val=1000000,freq=0;
for(var i:A){
//if even element
if(i%2==0){
//increase frequency in map
int curr= mp.getOrDefault(i,0)+1;
mp.put(i,curr);
//Update smallest with greatest frequency
if(curr>freq || curr==freq && i<val){
val=i;
freq=curr;
}
}
}
return freq==0? -1 : val;
}
}
Todo
# 2404. Most Frequent Even Element
# https://leetcode.com/problems/most-frequent-even-element/
class Solution:
def mostFrequentEven(self, nums: List[int]) -> int:
counter = Counter()
have = False
for x in nums:
if x % 2 == 0:
counter[x] += 1
have = True
if not have: return -1
mmax = max(counter.values())
for x in sorted(counter.keys()):
if counter[x] == mmax:
return x
return -1
Explain:
nope.
Complexity:
Time complexity : O(n).
Space complexity : O(n).
All Problems
All Solutions
Sun, 23 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-23-2404-Most-Frequent-Even-Element/
https://leetcode.ca/2022-10-23-2404-Most-Frequent-Even-Element/2403 - Minimum Time to Kill All Monsters
Formatted question description: https://leetcode.ca/all/2403.html
Todo
All Problems
All Solutions
Sat, 22 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-22-2403-Minimum-Time-to-Kill-All-Monsters/
https://leetcode.ca/2022-10-22-2403-Minimum-Time-to-Kill-All-Monsters/2402 - Meeting Rooms III
Formatted question description: https://leetcode.ca/all/2402.html 2402. Meeting Rooms III Difficulty: Hard. Related Topics: Array, Sorting, Heap (Priority Queue). Similar Questions: Meeting Rooms, Meeting Rooms II, Maximum Number of Events That Can Be Attended, Find Servers That Handled Most Number of Requests, Maximum Number of Events That Can Be Attended II. Problem You are given an integer n. There are n rooms numbered from 0 to n - 1. You are given a 2D integer array meetings where meetings[i] = [starti, endi] means that a meeting will be held during the half-closed time interval [starti, endi). All the values of starti are unique. Meetings are allocated to rooms in the following manner: Each meeting will take place in the unused room with the lowest number. If there are no available rooms, the meeting will be delayed until a room becomes free. The delayed meeting should have the same duration as the original meeting. When a room becomes unused, meetings that have an earlier original start time should be given the room. Return** the number of the room that held the most meetings. If there are multiple rooms, return the room with the lowest number.** A half-closed interval [a, b) is the interval between a and b including a and not including b. Example 1: Input: n = 2, meetings = [[0,10],[1,5],[2,7],[3,4]] Output: 0 Explanation: - At time 0, both rooms are not being used. The first meeting starts in room 0. - At time 1, only room 1 is not being used. The second meeting starts in room 1. - At time 2, both rooms are being used. The third meeting is delayed. - At time 3, both rooms are being used. The fourth meeting is delayed. - At time 5, the meeting in room 1 finishes. The third meeting starts in room 1 for the time period [5,10). - At time 10, the meetings in both rooms finish. The fourth meeting starts in room 0 for the time period [10,11). Both rooms 0 and 1 held 2 meetings, so we return 0. Example 2: Input: n = 3, meetings = [[1,20],[2,10],[3,5],[4,9],[6,8]] Output: 1 Explanation: - At time 1, all three rooms are not being used. The first meeting starts in room 0. - At time 2, rooms 1 and 2 are not being used. The second meeting starts in room 1. - At time 3, only room 2 is not being used. The third meeting starts in room 2. - At time 4, all three rooms are being used. The fourth meeting is delayed. - At time 5, the meeting in room 2 finishes. The fourth meeting starts in room 2 for the time period [5,10). - At time 6, all three rooms are being used. The fifth meeting is delayed. - At time 10, the meetings in rooms 1 and 2 finish. The fifth meeting starts in room 1 for the time period [10,12). Room 0 held 1 meeting while rooms 1 and 2 each held 2 meetings, so...
Fri, 21 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-21-2402-Meeting-Rooms-III/
https://leetcode.ca/2022-10-21-2402-Meeting-Rooms-III/2401 - Longest Nice Subarray
Formatted question description: https://leetcode.ca/all/2401.html
2401. Longest Nice Subarray
Difficulty: Medium.
Related Topics: Array, Bit Manipulation, Sliding Window.
Similar Questions: Longest Substring Without Repeating Characters, Bitwise AND of Numbers Range, Bitwise ORs of Subarrays, Fruit Into Baskets, Max Consecutive Ones III, Get Equal Substrings Within Budget, Frequency of the Most Frequent Element, Longest Substring Of All Vowels in Order, Maximize the Confusion of an Exam.
Problem
You are given an array nums consisting of positive integers.
We call a subarray of nums nice if the bitwise AND of every pair of elements that are in different positions in the subarray is equal to 0.
Return the length of the **longest nice subarray**.
A subarray is a contiguous part of an array.
Note that subarrays of length 1 are always considered nice.
Example 1:
Input: nums = [1,3,8,48,10]
Output: 3
Explanation: The longest nice subarray is [3,8,48]. This subarray satisfies the conditions:
- 3 AND 8 = 0.
- 3 AND 48 = 0.
- 8 AND 48 = 0.
It can be proven that no longer nice subarray can be obtained, so we return 3.
Example 2:
Input: nums = [3,1,5,11,13]
Output: 1
Explanation: The length of the longest nice subarray is 1. Any subarray of length 1 can be chosen.
Constraints:
1 <= nums.length <= 105
1 <= nums[i] <= 109
Solution (Java, C++, Python)
Java
C++
Python
class Solution {
public int longestNiceSubarray(int[] nums) {
int maxCount = 1;
int count = 1;
List<Integer> list = new ArrayList<>();
for (int i = 0; i < nums.length - 1; i++) {
list.clear();
list.add(nums[i]);
count = 1;
for (int j = i + 1; j < nums.length; j++) {
if ((nums[i] & nums[j]) == 0) {
list.add(nums[j]);
} else
break;
}
boolean bool = true;
if (list.size() != 1) {
for (int i1 = 1; i1 < list.size(); i1++) {
for (int j = 0; j < i1; j++) {
if (i1!=j&&(list.get(i1) & list.get(j)) != 0) {
bool = false;
break;
}
}
if (bool)
count++;
else
break;
}
if (maxCount<count)
maxCount = count;
}
}
return maxCount;
}
}
Todo
# 2401. Longest Nice Subarray
# https://leetcode.com/problems/longest-nice-subarray/
class Solution:
def longestNiceSubarray(self, nums: List[int]) -> int:
n = len(nums)
res = 1
i = mask = 0
for j, x in enumerate(nums):
while mask & x != 0:
mask ^= (nums[i])
i += 1
mask |= x
res = max(res, j - i + 1)
return res
Explain:
nope.
Complexity:
Time complexity : O(n).
Space complexity : O(n).
All Problems
All Solutions
Thu, 20 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-20-2401-Longest-Nice-Subarray/
https://leetcode.ca/2022-10-20-2401-Longest-Nice-Subarray/2400 - Number of Ways to Reach a Position After Exactly k Steps
Formatted question description: https://leetcode.ca/all/2400.html
2400. Number of Ways to Reach a Position After Exactly k Steps
Difficulty: Medium.
Related Topics: Math, Dynamic Programming, Combinatorics.
Similar Questions: Unique Paths, Climbing Stairs, Reach a Number, Reaching Points, Number of Ways to Stay in the Same Place After Some Steps.
Problem
You are given two positive integers startPos and endPos. Initially, you are standing at position startPos on an infinite number line. With one step, you can move either one position to the left, or one position to the right.
Given a positive integer k, return the number of **different ways to reach the position endPos starting from startPos, such that you perform exactly k steps. Since the answer may be very large, return it **modulo 109 + 7.
Two ways are considered different if the order of the steps made is not exactly the same.
Note that the number line includes negative integers.
Example 1:
Input: startPos = 1, endPos = 2, k = 3
Output: 3
Explanation: We can reach position 2 from 1 in exactly 3 steps in three ways:
- 1 -> 2 -> 3 -> 2.
- 1 -> 2 -> 1 -> 2.
- 1 -> 0 -> 1 -> 2.
It can be proven that no other way is possible, so we return 3.
Example 2:
Input: startPos = 2, endPos = 5, k = 10
Output: 0
Explanation: It is impossible to reach position 5 from position 2 in exactly 10 steps.
Constraints:
1 <= startPos, endPos, k <= 1000
Solution (Java, C++, Python)
Java
C++
Python
class Solution {
int p = 1000000007;
public int numberOfWays(int a, int b, int k) {
if ((a - b - k) % 2 != 0) return 0;
if (Math.abs(a - b) > k) return 0;
long res = 1L;
for (int i = 0; i < (b - a + k) / 2; ++i) {
res = res * (k - i) % p;
res = res * inv(i + 1) % p;
}
return (int)res;
}
private long inv(long a) {
if (a == 1) return 1;
return (p - p / a) * inv(p % a) % p;
}
}
Todo
# 2400. Number of Ways to Reach a Position After Exactly k Steps
# https://leetcode.com/problems/number-of-ways-to-reach-a-position-after-exactly-k-steps/
class Solution:
def numberOfWays(self, startPos: int, endPos: int, k: int) -> int:
M = 10 ** 9 + 7
@cache
def dfs(pos, steps):
if steps == k:
return 1 if pos == endPos else 0
remainingSteps = k - steps
if abs(pos - endPos) > remainingSteps:
return 0
return (dfs(pos + 1, steps + 1) + dfs(pos - 1, steps + 1)) % M
return dfs(startPos, 0)
Explain:
nope.
Complexity:
Time complexity : O(n).
Space complexity : O(n).
All Problems
All Solutions
Wed, 19 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-19-2400-Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/
https://leetcode.ca/2022-10-19-2400-Number-of-Ways-to-Reach-a-Position-After-Exactly-k-Steps/2399 - Check Distances Between Same Letters
Formatted question description: https://leetcode.ca/all/2399.html
2399. Check Distances Between Same Letters
Difficulty: Easy.
Related Topics: Array, Hash Table, String.
Similar Questions: Two Sum, Shortest Distance to a Character.
Problem
You are given a 0-indexed string s consisting of only lowercase English letters, where each letter in s appears exactly twice. You are also given a 0-indexed integer array distance of length 26.
Each letter in the alphabet is numbered from 0 to 25 (i.e. 'a' -> 0, 'b' -> 1, 'c' -> 2, … , 'z' -> 25).
In a well-spaced string, the number of letters between the two occurrences of the ith letter is distance[i]. If the ith letter does not appear in s, then distance[i] can be ignored.
Return true** if s is a well-spaced string, otherwise return **false.
Example 1:
Input: s = "abaccb", distance = [1,3,0,5,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: true
Explanation:
- 'a' appears at indices 0 and 2 so it satisfies distance[0] = 1.
- 'b' appears at indices 1 and 5 so it satisfies distance[1] = 3.
- 'c' appears at indices 3 and 4 so it satisfies distance[2] = 0.
Note that distance[3] = 5, but since 'd' does not appear in s, it can be ignored.
Return true because s is a well-spaced string.
Example 2:
Input: s = "aa", distance = [1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]
Output: false
Explanation:
- 'a' appears at indices 0 and 1 so there are zero letters between them.
Because distance[0] = 1, s is not a well-spaced string.
Constraints:
2 <= s.length <= 52
s consists only of lowercase English letters.
Each letter appears in s exactly twice.
distance.length == 26
0 <= distance[i] <= 50
Solution (Java, C++, Python)
Java
C++
Python
class Solution {
public boolean checkDistances(String s, int[] distance) {
boolean valid = true;
HashMap<Character,Integer> map = new HashMap<>();
int n = s.length();
// System.out.println('c'-'a');
for(int i = 0 ; i < n ; i++){
char c = s.charAt(i);
if(map.containsKey(c)){
int value = i - map.get(c) - 1;
if(value != distance[c-'a'])return false;
}else{
map.put(c,i);
}
}
return valid;
}
}
Todo
# 2399. Check Distances Between Same Letters
# https://leetcode.com/problems/check-distances-between-same-letters/
class Solution:
def checkDistances(self, s: str, distance: List[int]) -> bool:
dist = {}
for i, x in enumerate(s):
if x not in dist:
dist[x] = i
else:
k = ord(x) - ord("a")
if distance[k] != i - dist[x] - 1:
return False
return True
Explain:
nope.
Complexity:
Time complexity : O(n).
Space complexity : O(n).
All Problems
All Solutions
Tue, 18 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-18-2399-Check-Distances-Between-Same-Letters/
https://leetcode.ca/2022-10-18-2399-Check-Distances-Between-Same-Letters/2398 - Maximum Number of Robots Within Budget
Formatted question description: https://leetcode.ca/all/2398.html 2398. Maximum Number of Robots Within Budget Difficulty: Hard. Related Topics: Array, Binary Search, Queue, Sliding Window, Heap (Priority Queue), Prefix Sum. Similar Questions: Sliding Window Maximum, Kth Smallest Product of Two Sorted Arrays, Maximum Number of Tasks You Can Assign, Minimized Maximum of Products Distributed to Any Store, Minimum Time to Complete Trips. Problem You have n robots. You are given two 0-indexed integer arrays, chargeTimes and runningCosts, both of length n. The ith robot costs chargeTimes[i] units to charge and costs runningCosts[i] units to run. You are also given an integer budget. The total cost of running k chosen robots is equal to max(chargeTimes) + k * sum(runningCosts), where max(chargeTimes) is the largest charge cost among the k robots and sum(runningCosts) is the sum of running costs among the k robots. Return** the maximum number of consecutive robots you can run such that the total cost does not exceed **budget. Example 1: Input: chargeTimes = [3,6,1,3,4], runningCosts = [2,1,3,4,5], budget = 25 Output: 3 Explanation: It is possible to run all individual and consecutive pairs of robots within budget. To obtain answer 3, consider the first 3 robots. The total cost will be max(3,6,1) + 3 * sum(2,1,3) = 6 + 3 * 6 = 24 which is less than 25. It can be shown that it is not possible to run more than 3 consecutive robots within budget, so we return 3. Example 2: Input: chargeTimes = [11,12,19], runningCosts = [10,8,7], budget = 19 Output: 0 Explanation: No robot can be run that does not exceed the budget, so we return 0. Constraints: chargeTimes.length == runningCosts.length == n 1 <= n <= 5 * 104 1 <= chargeTimes[i], runningCosts[i] <= 105 1 <= budget <= 1015 Solution (Java, C++, Python) Java C++ Python class Solution { public int maximumRobots(int[] times, int[] costs, long budget) { long sum = 0; int i = 0, n = times.length; Deque<Integer> d = new LinkedList<Integer>(); for (int j = 0; j < n; ++j) { sum += costs[j]; while (!d.isEmpty() && times[d.peekLast()] <= times[j]) d.pollLast(); d.addLast(j); if (times[d.getFirst()] + (j - i + 1) * sum > budget) { if (d.getFirst() == i) d.pollFirst(); sum -= costs[i++]; } } return n - i; } } Todo # 2398. Maximum Number of Robots Within Budget # https://leetcode.com/problems/maximum-number-of-robots-within-budget/ from sortedcontainers import SortedList class Solution: def maximumRobots(self, chargeTimes: List[int], runningCosts: List[int], budget: int) -> int: n = len(chargeTimes) largest = SortedList() res = i = costs = 0 for j in range(n): largest.add(-chargeTimes[j]) costs += runningCosts[j] total = -largest[0] + (j - i + 1) * costs while total > budget: ...
Mon, 17 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-17-2398-Maximum-Number-of-Robots-Within-Budget/
https://leetcode.ca/2022-10-17-2398-Maximum-Number-of-Robots-Within-Budget/2397 - Maximum Rows Covered by Columns
Formatted question description: https://leetcode.ca/all/2397.html 2397. Maximum Rows Covered by Columns Difficulty: Medium. Related Topics: Array, Backtracking, Bit Manipulation, Matrix, Enumeration. Similar Questions: Matchsticks to Square, Partition to K Equal Sum Subsets, Find the Shortest Superstring, Smallest Sufficient Team, Fair Distribution of Cookies. Problem You are given a 0-indexed m x n binary matrix matrix and an integer numSelect, which denotes the number of distinct columns you must select from matrix. Let us consider s = {c1, c2, ...., cnumSelect} as the set of columns selected by you. A row row is covered by s if: For each cell matrix[row][col] (0 <= col <= n - 1) where matrix[row][col] == 1, col is present in s or, No cell in row has a value of 1. You need to choose numSelect columns such that the number of rows that are covered is maximized. Return the **maximum number of rows that can be covered by a set of numSelect columns.** Example 1: Input: matrix = [[0,0,0],[1,0,1],[0,1,1],[0,0,1]], numSelect = 2 Output: 3 Explanation: One possible way to cover 3 rows is shown in the diagram above. We choose s = {0, 2}. - Row 0 is covered because it has no occurrences of 1. - Row 1 is covered because the columns with value 1, i.e. 0 and 2 are present in s. - Row 2 is not covered because matrix[2][1] == 1 but 1 is not present in s. - Row 3 is covered because matrix[2][2] == 1 and 2 is present in s. Thus, we can cover three rows. Note that s = {1, 2} will also cover 3 rows, but it can be shown that no more than three rows can be covered. Example 2: Input: matrix = [[1],[0]], numSelect = 1 Output: 2 Explanation: Selecting the only column will result in both rows being covered since the entire matrix is selected. Therefore, we return 2. Constraints: m == matrix.length n == matrix[i].length 1 <= m, n <= 12 matrix[i][j] is either 0 or 1. 1 <= numSelect <= n Solution (Java, C++, Python) Java C++ Python class Solution { public int maximumRows(int[][] mat, int cols) { int m=mat.length; int n=mat[0].length; int[] s=new int[n]; return f(0,m,n,cols,mat,s); } public int f(int ind,int m,int n,int cols,int[][] mat,int[] s){ if(cols==0){ int count=0; for(int i=0; i<m; i++){ //supposing that this row is valid boolean selected=true; for(int j=0; j<n; j++){ //if any cell of this row violates the given two conditions, then the row is discarded if(mat[i][j]==1 && s[j]!=1) selected=false; } if(selected) count+=1; } return count; } int ans=-1; for(int i=ind; i<n; i++){ s[i]=1; //do ans=Math.max(ans,f(i+1,m,n,cols-1,mat,s)); s[i]=0; //undo / backtrack } return ans; } } Todo # 2397. Maximum Rows Covered by Columns # https://leetcode.com/problems/maximum-rows-covered-by-columns/ class Solution: def maximumRows(self, mat: List[List[int]], k: int) -> int: rows, cols = len(mat), len(mat[0]) res = 0 A = list(range(cols)) for comb in combinations(A, k): ...
Sun, 16 Oct 2022 11:21:01 -0700
https://leetcode.ca/2022-10-16-2397-Maximum-Rows-Covered-by-Columns/
https://leetcode.ca/2022-10-16-2397-Maximum-Rows-Covered-by-Columns/