task_num
int64
4
3.12k
task_title
stringlengths
4
75
difficulty
int64
1
3
func_name
stringlengths
5
34
description
stringlengths
81
2.11k
python_solution
stringlengths
510
3.55k
java_solution
stringlengths
443
5.52k
cpp_solution
stringlengths
390
5.48k
1,655
Distribute Repeating Integers
3
canDistribute
You are given an array of `n` integers, `nums`, where there are at most `50` unique values in the array. You are also given an array of `m` customer order quantities, `quantity`, where `quantity[i]` is the amount of integers the `ith` customer ordered. Determine if it is possible to distribute `nums` such that: * The `ith` customer gets exactly `quantity[i]` integers, * The integers the `ith` customer gets are all equal, and * Every customer is satisfied. Return `true` if it is possible to distribute `nums` according to the above conditions.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def canDistribute(self, nums: List[int], quantity: List[int]) -> bool: freqs = list(collections.Counter(nums).values()) validDistribution = self._getValidDistribution(freqs, quantity) n = len(freqs) m = len(quantity) maxMask = 1 << m dp = [[False] * maxMask for _ in range(n + 1)] dp[n][maxMask - 1] = True for i in range(n - 1, -1, -1): for mask in range(maxMask): dp[i][mask] = dp[i + 1][mask] availableMask = ~mask & (maxMask - 1) submask = availableMask while submask > 0: if validDistribution[i][submask]: dp[i][mask] = dp[i][mask] or dp[i + 1][mask | submask] submask = (submask - 1) & availableMask return dp[0][0] def _getValidDistribution(self, freqs: List[int], quantity: List[int]) -> List[List[bool]]: maxMask = 1 << len(quantity) validDistribution = [[False] * maxMask for _ in range(len(freqs))] for i, freq in enumerate(freqs): for mask in range(maxMask): if freq >= self._getQuantitySum(quantity, mask): validDistribution[i][mask] = True return validDistribution def _getQuantitySum(self, quantity: List[int], mask: int) -> int: res=[] for i, q in enumerate(quantity): if mask >> i & 1: res.append(q) return sum(res)
class Solution { public boolean canDistribute(int[] nums, int[] quantity) { List<Integer> freqs = getFreqs(nums); // validDistribution[i][j] := true if it's possible to distribute the i-th // freq into a subset of quantity represented by the bitmask j boolean[][] validDistribution = getValidDistribution(freqs, quantity); final int n = freqs.size(); final int m = quantity.length; final int maxMask = 1 << m; // dp[i][j] := true if it's possible to distribute freqs[i..n), where j is // the bitmask of the selected quantity boolean[][] dp = new boolean[n + 1][maxMask]; dp[n][maxMask - 1] = true; for (int i = n - 1; i >= 0; --i) for (int mask = 0; mask < maxMask; ++mask) { dp[i][mask] = dp[i + 1][mask]; final int availableMask = ~mask & (maxMask - 1); for (int submask = availableMask; submask > 0; submask = (submask - 1) & availableMask) if (validDistribution[i][submask]) dp[i][mask] = dp[i][mask] || dp[i + 1][mask | submask]; } return dp[0][0]; } private List<Integer> getFreqs(int[] nums) { List<Integer> freqs = new ArrayList<>(); Map<Integer, Integer> count = new HashMap<>(); for (final int num : nums) count.merge(num, 1, Integer::sum); return new ArrayList<>(count.values()); } boolean[][] getValidDistribution(List<Integer> freqs, int[] quantity) { final int maxMask = 1 << quantity.length; boolean[][] validDistribution = new boolean[freqs.size()][maxMask]; for (int i = 0; i < freqs.size(); ++i) for (int mask = 0; mask < maxMask; ++mask) if (freqs.get(i) >= getQuantitySum(quantity, mask)) validDistribution[i][mask] = true; return validDistribution; } // Returns the sum of the selected quantity represented by `mask`. int getQuantitySum(int[] quantity, int mask) { int sum = 0; for (int i = 0; i < quantity.length; ++i) if ((mask >> i & 1) == 1) sum += quantity[i]; return sum; } }
class Solution { public: bool canDistribute(vector<int>& nums, vector<int>& quantity) { // validDistribution[i][j] := true if it's possible to distribute the i-th // freq into a subset of quantity represented by the bitmask j const vector<int> freqs = getFreqs(nums); const vector<vector<bool>> validDistribution = getValidDistribuition(freqs, quantity); const int n = freqs.size(); const int m = quantity.size(); const int maxMask = 1 << m; // dp[i][j] := true if it's possible to distribute freqs[i..n), where j is // the bitmask of the selected quantity vector<vector<bool>> dp(n + 1, vector<bool>(maxMask)); dp[n][maxMask - 1] = true; for (int i = n - 1; i >= 0; --i) for (int mask = 0; mask < maxMask; ++mask) { dp[i][mask] = dp[i + 1][mask]; const int availableMask = ~mask & (maxMask - 1); for (int submask = availableMask; submask > 0; submask = (submask - 1) & availableMask) if (validDistribution[i][submask]) dp[i][mask] = dp[i][mask] || dp[i + 1][mask | submask]; } return dp[0][0]; } private: vector<int> getFreqs(const vector<int>& nums) { vector<int> freqs; unordered_map<int, int> count; for (const int num : nums) ++count[num]; for (const auto& [_, freq] : count) freqs.push_back(freq); return freqs; } vector<vector<bool>> getValidDistribuition(const vector<int>& freqs, const vector<int>& quantity) { const int maxMask = 1 << quantity.size(); vector<vector<bool>> validDistribution(freqs.size(), vector<bool>(maxMask)); for (int i = 0; i < freqs.size(); ++i) for (int mask = 0; mask < maxMask; ++mask) if (freqs[i] >= getQuantitySum(quantity, mask)) validDistribution[i][mask] = true; return validDistribution; } // Returns the sum of the selected quantity represented by `mask`. int getQuantitySum(const vector<int>& quantity, int mask) { int sum = 0; for (int i = 0; i < quantity.size(); ++i) if (mask >> i & 1) sum += quantity[i]; return sum; } };
1,681
Minimum Incompatibility
3
minimumIncompatibility
You are given an integer array `nums`​​​ and an integer `k`. You are asked to distribute this array into `k` subsets of equal size such that there are no two equal elements in the same subset. A subset's incompatibility is the difference between the maximum and minimum elements in that array. Return the minimum possible sum of incompatibilities of the `k` subsets after distributing the array optimally, or return `-1` if it is not possible. A subset is a group integers that appear in the array with no particular order.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def __init__(self): self.kMaxNum = 16 def minimumIncompatibility(self, nums: List[int], k: int) -> int: kMaxCompatibility = (16 - 1) * (16 // 2) n = len(nums) subsetSize = n // k maxMask = 1 << n incompatibilities = self._getIncompatibilities(nums, subsetSize) dp = [kMaxCompatibility] * maxMask dp[0] = 0 for mask in range(1, maxMask): if mask.bit_count() % subsetSize != 0: continue submask = mask while submask > 0: if incompatibilities[submask] != -1: dp[mask] = min(dp[mask], dp[mask - submask] + incompatibilities[submask]) submask = (submask - 1) & mask if dp[-1] != kMaxCompatibility: return dp[-1] else: return -1 def _getIncompatibilities(self, nums: List[int], subsetSize: int) -> List[int]: maxMask = 1 << len(nums) incompatibilities = [-1] * maxMask for mask in range(maxMask): if mask.bit_count() == subsetSize and self._isUnique(nums, mask, subsetSize): incompatibilities[mask] = self._getIncompatibility(nums, mask) return incompatibilities def _isUnique(self, nums: List[int], mask: int, subsetSize: int) -> bool: used = 0 for i, num in enumerate(nums): if mask >> i & 1: used |= 1 << num return used.bit_count() == subsetSize def _getIncompatibility(self, nums: List[int], mask: int) -> int: mini = self.kMaxNum maxi = 0 for i, num in enumerate(nums): if mask >> i & 1: maxi = max(maxi, num) mini = min(mini, num) return maxi - mini
class Solution { public int minimumIncompatibility(int[] nums, int k) { final int MAX_COMPATIBILITY = (16 - 1) * (16 / 2); final int n = nums.length; final int subsetSize = n / k; final int maxMask = 1 << n; final int[] incompatibilities = getIncompatibilities(nums, subsetSize); // dp[i] := the minimum possible sum of incompatibilities of the subset // of numbers represented by the bitmask i int[] dp = new int[maxMask]; Arrays.fill(dp, MAX_COMPATIBILITY); dp[0] = 0; for (int mask = 1; mask < maxMask; ++mask) { // The number of 1s in `mask` isn't a multiple of `subsetSize`. if (Integer.bitCount(mask) % subsetSize != 0) continue; // https://cp-algorithms.com/algebra/all-submasks.html for (int submask = mask; submask > 0; submask = (submask - 1) & mask) if (incompatibilities[submask] != -1) // valid submask dp[mask] = Math.min(dp[mask], dp[mask - submask] + incompatibilities[submask]); } return dp[maxMask - 1] == MAX_COMPATIBILITY ? -1 : dp[maxMask - 1]; } private static final int MAX_NUM = 16; // Returns an incompatibilities array where // * incompatibilities[i] := the incompatibility of the subset of numbers // represented by the bitmask i // * incompatibilities[i] := -1 if the number of 1s in the bitmask i is not // `subsetSize` private int[] getIncompatibilities(int[] nums, int subsetSize) { final int maxMask = 1 << nums.length; int[] incompatibilities = new int[maxMask]; Arrays.fill(incompatibilities, -1); for (int mask = 0; mask < maxMask; ++mask) if (Integer.bitCount(mask) == subsetSize && isUnique(nums, mask, subsetSize)) incompatibilities[mask] = getIncompatibility(nums, mask); return incompatibilities; } // Returns true if the numbers selected by `mask` are unique. // // e.g. If we call isUnique(0b1010, 2, [1, 2, 1, 4]), `used` variable // will be 0b1, which only has one 1 (less than `subsetSize`). In this case, // we should return false. private boolean isUnique(int[] nums, int mask, int subsetSize) { int used = 0; for (int i = 0; i < nums.length; ++i) if ((mask >> i & 1) == 1) used |= 1 << nums[i]; return Integer.bitCount(used) == subsetSize; } // Returns the incompatibility of the selected numbers represented by the // `mask`. private int getIncompatibility(int[] nums, int mask) { int mn = MAX_NUM; int mx = 0; for (int i = 0; i < nums.length; ++i) if ((mask >> i & 1) == 1) { mx = Math.max(mx, nums[i]); mn = Math.min(mn, nums[i]); } return mx - mn; } }
class Solution { public: int minimumIncompatibility(vector<int>& nums, int k) { constexpr int kMaxCompatibility = (16 - 1) * (16 / 2); const int n = nums.size(); const int subsetSize = n / k; const int maxMask = 1 << n; const vector<int> incompatibilities = getIncompatibilities(nums, subsetSize); // dp[i] := the minimum possible sum of incompatibilities of the subset // of numbers represented by the bitmask i vector<int> dp(maxMask, kMaxCompatibility); dp[0] = 0; for (unsigned mask = 1; mask < maxMask; ++mask) { // The number of 1s in `mask` isn't a multiple of `subsetSize`. if (popcount(mask) % subsetSize != 0) continue; // https://cp-algorithms.com/algebra/all-submasks.html for (int submask = mask; submask > 0; submask = (submask - 1) & mask) if (incompatibilities[submask] != -1) // valid subset dp[mask] = min(dp[mask], dp[mask - submask] + incompatibilities[submask]); } return dp.back() == kMaxCompatibility ? -1 : dp.back(); } private: static constexpr int kMaxNum = 16; // Returns an incompatibilities array where // * incompatibilities[i] := the incompatibility of the subset of numbers // represented by the bitmask i // * incompatibilities[i] := -1 if the number of 1s in the bitmask i is not // `subsetSize` vector<int> getIncompatibilities(const vector<int>& nums, int subsetSize) { const int maxMask = 1 << nums.size(); vector<int> incompatibilities(maxMask, -1); for (unsigned mask = 0; mask < maxMask; ++mask) if (popcount(mask) == subsetSize && isUnique(nums, mask, subsetSize)) incompatibilities[mask] = getIncompatibility(nums, mask); return incompatibilities; } // Returns true if the numbers selected by `mask` are unique. // // e.g. If we call isUnique(0b1010, 2, [1, 2, 1, 4]), `used` variable // will be 0b1, which only has one 1 (less than `subsetSize`). In this case, // we should return false. bool isUnique(const vector<int>& nums, int mask, int subsetSize) { unsigned used = 0; for (int i = 0; i < nums.size(); ++i) if (mask >> i & 1) used |= 1 << nums[i]; return popcount(used) == subsetSize; } // Returns the incompatibility of the selected numbers represented by the // `mask`. int getIncompatibility(const vector<int>& nums, int mask) { int mn = kMaxNum; int mx = 0; for (int i = 0; i < nums.size(); ++i) if (mask >> i & 1) { mx = max(mx, nums[i]); mn = min(mn, nums[i]); } return mx - mn; } };
1,687
Delivering Boxes from Storage to Ports
3
boxDelivering
You have the task of delivering some boxes from storage to their ports using only one ship. However, this ship has a limit on the number of boxes and the total weight that it can carry. You are given an array `boxes`, where `boxes[i] = [ports​​i​, weighti]`, and three integers `portsCount`, `maxBoxes`, and `maxWeight`. * `ports​​i` is the port where you need to deliver the `ith` box and `weightsi` is the weight of the `ith` box. * `portsCount` is the number of ports. * `maxBoxes` and `maxWeight` are the respective box and weight limits of the ship. The boxes need to be delivered in the order they are given. The ship will follow these steps: * The ship will take some number of boxes from the `boxes` queue, not violating the `maxBoxes` and `maxWeight` constraints. * For each loaded box in order, the ship will make a trip to the port the box needs to be delivered to and deliver it. If the ship is already at the correct port, no trip is needed, and the box can immediately be delivered. * The ship then makes a return trip to storage to take more boxes from the queue. The ship must end at storage after all the boxes have been delivered. Return the minimum number of trips the ship needs to make to deliver all boxes to their respective ports.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def boxDelivering(self, boxes: List[List[int]], portsCount: int, maxBoxes: int, maxWeight: int) -> int: n = len(boxes) dp = [0] * (n + 1) trips = 2 weight = 0 l = 0 for r in range(n): weight += boxes[r][1] if r > 0 and boxes[r][0] != boxes[r - 1][0]: trips += 1 while r - l + 1 > maxBoxes or weight > maxWeight or (l < r and dp[l + 1] == dp[l]): weight -= boxes[l][1] if boxes[l][0] != boxes[l + 1][0]: trips -= 1 l += 1 dp[r + 1] = dp[l] + trips return dp[n]
class Solution { public int boxDelivering(int[][] boxes, int portsCount, int maxBoxes, int maxWeight) { final int n = boxes.length; // dp[i] := the minimum trips to deliver boxes[0..i) and return to the // storage int[] dp = new int[n + 1]; int trips = 2; int weight = 0; for (int l = 0, r = 0; r < n; ++r) { weight += boxes[r][1]; // The current box is different from the previous one, need to make one // more trip. if (r > 0 && boxes[r][0] != boxes[r - 1][0]) ++trips; while (r - l + 1 > maxBoxes || weight > maxWeight || // Loading boxes[l] in the previous turn is always no bad than // loading it in this turn. (l < r && dp[l + 1] == dp[l])) { weight -= boxes[l][1]; if (boxes[l][0] != boxes[l + 1][0]) --trips; ++l; } // the minimum trips to deliver boxes[0..r] // = the minimum trips to deliver boxes[0..l) + // trips to deliver boxes[l..r] dp[r + 1] = dp[l] + trips; } return dp[n]; } }
class Solution { public: int boxDelivering(vector<vector<int>>& boxes, int portsCount, int maxBoxes, int maxWeight) { const int n = boxes.size(); // dp[i] := the minimum trips to deliver boxes[0..i) and return to the // storage vector<int> dp(n + 1); int trips = 2; int weight = 0; for (int l = 0, r = 0; r < n; ++r) { weight += boxes[r][1]; // The current box is different from the previous one, need to make one // more trip. if (r > 0 && boxes[r][0] != boxes[r - 1][0]) ++trips; while (r - l + 1 > maxBoxes || weight > maxWeight || // Loading boxes[l] in the previous turn is always no bad than // loading it in this turn. (l < r && dp[l + 1] == dp[l])) { weight -= boxes[l][1]; if (boxes[l][0] != boxes[l + 1][0]) --trips; ++l; } // min trips to deliver boxes[0..r] // = min trips to deliver boxes[0..l) + trips to deliver boxes[l..r] dp[r + 1] = dp[l] + trips; } return dp[n]; } };
1,705
Maximum Number of Eaten Apples
2
eatenApples
There is a special kind of apple tree that grows apples every day for `n` days. On the `ith` day, the tree grows `apples[i]` apples that will rot after `days[i]` days, that is on day `i + days[i]` the apples will be rotten and cannot be eaten. On some days, the apple tree does not grow any apples, which are denoted by `apples[i] == 0` and `days[i] == 0`. You decided to eat at most one apple a day (to keep the doctors away). Note that you can keep eating after the first `n` days. Given two integer arrays `days` and `apples` of length `n`, return the maximum number of apples you can eat.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def eatenApples(self, apples: List[int], days: List[int]) -> int: n = len(apples) ans = 0 minHeap = [] i = 0 while i < n or minHeap: while minHeap and minHeap[0][0] <= i: heapq.heappop(minHeap) if i < n and apples[i] > 0: heapq.heappush(minHeap, (i + days[i], apples[i])) if minHeap: rottenDay, numApples = heapq.heappop(minHeap) if numApples > 1: heapq.heappush(minHeap, (rottenDay, numApples - 1)) ans += 1 i += 1 return ans
class Solution { public int eatenApples(int[] apples, int[] days) { final int n = apples.length; int ans = 0; // (the rotten day, the number of apples) Queue<Pair<Integer, Integer>> minHeap = new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)); for (int i = 0; i < n || !minHeap.isEmpty(); ++i) { // Remove the rotten apples. while (!minHeap.isEmpty() && minHeap.peek().getKey() <= i) minHeap.poll(); // Add today's apples. if (i < n && apples[i] > 0) minHeap.offer(new Pair<>(i + days[i], apples[i])); // Eat one apple today. if (!minHeap.isEmpty()) { final int rottenDay = minHeap.peek().getKey(); final int numApples = minHeap.poll().getValue(); if (numApples > 1) minHeap.offer(new Pair<>(rottenDay, numApples - 1)); ++ans; } } return ans; } }
class Solution { public: int eatenApples(vector<int>& apples, vector<int>& days) { const int n = apples.size(); int ans = 0; using P = pair<int, int>; // (the rotten day, the number of apples) priority_queue<P, vector<P>, greater<>> minHeap; for (int i = 0; i < n || !minHeap.empty(); ++i) { // i := day // Remove the rotten apples. while (!minHeap.empty() && minHeap.top().first <= i) minHeap.pop(); // Add today's apples. if (i < n && apples[i] > 0) minHeap.emplace(i + days[i], apples[i]); // Eat one apple today. if (!minHeap.empty()) { const auto [rottenDay, numApples] = minHeap.top(); minHeap.pop(); if (numApples > 1) minHeap.emplace(rottenDay, numApples - 1); ++ans; } } return ans; } };
1,706
Where Will the Ball Fall
2
findBall
You have a 2-D `grid` of size `m x n` representing a box, and you have `n` balls. The box is open on the top and bottom sides. Each cell in the box has a diagonal board spanning two corners of the cell that can redirect a ball to the right or to the left. * A board that redirects the ball to the right spans the top-left corner to the bottom-right corner and is represented in the grid as `1`. * A board that redirects the ball to the left spans the top-right corner to the bottom-left corner and is represented in the grid as `-1`. We drop one ball at the top of each column of the box. Each ball can get stuck in the box or fall out of the bottom. A ball gets stuck if it hits a "V" shaped pattern between two boards or if a board redirects the ball into either wall of the box. Return an array `answer` of size `n` where `answer[i]` is the column that the ball falls out of at the bottom after dropping the ball from the `ith` column at the top, or `-1` if the ball gets stuck in the box.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def findBall(self, grid: List[List[int]]) -> List[int]: m = len(grid) n = len(grid[0]) dp = [i for i in range(n)] ans = [-1] * n for i in range(m): newDp = [-1] * n for j in range(n): if j + grid[i][j] < 0 or j + grid[i][j] == n: continue if grid[i][j] == 1 and grid[i][j + 1] == -1 or grid[i][j] == -1 and grid[i][j - 1] == 1: continue newDp[j + grid[i][j]] = dp[j] dp = newDp for i, ball in enumerate(dp): if ball != -1: ans[ball] = i return ans
class Solution { public int[] findBall(int[][] grid) { final int m = grid.length; final int n = grid[0].length; // dp[i] := status of the i-th column // -1 := empty, 0 := b0, 1 := b1, ... int[] dp = new int[n]; // ans[i] := the i-th ball's final position int[] ans = new int[n]; Arrays.fill(ans, -1); for (int i = 0; i < n; ++i) dp[i] = i; for (int i = 0; i < m; ++i) { int[] newDp = new int[n]; Arrays.fill(newDp, -1); for (int j = 0; j < n; ++j) { // out-of-bounds if (j + grid[i][j] < 0 || j + grid[i][j] == n) continue; // Stuck if (grid[i][j] == 1 && grid[i][j + 1] == -1 || grid[i][j] == -1 && grid[i][j - 1] == 1) continue; newDp[j + grid[i][j]] = dp[j]; } dp = newDp; } for (int i = 0; i < n; ++i) if (dp[i] != -1) ans[dp[i]] = i; return ans; } }
class Solution { public: vector<int> findBall(vector<vector<int>>& grid) { const int m = grid.size(); const int n = grid[0].size(); // dp[i] := status of the i-th column // -1 := empty, 0 := b0, 1 := b1, ... vector<int> dp(n); // ans[i] := the i-th ball's final position vector<int> ans(n, -1); iota(dp.begin(), dp.end(), 0); for (int i = 0; i < m; ++i) { vector<int> newDp(n, -1); for (int j = 0; j < n; ++j) { // out-of-bounds if (j + grid[i][j] < 0 || j + grid[i][j] == n) continue; // Stuck if (grid[i][j] == 1 && grid[i][j + 1] == -1 || grid[i][j] == -1 && grid[i][j - 1] == 1) continue; newDp[j + grid[i][j]] = dp[j]; } dp = std::move(newDp); } for (int i = 0; i < n; ++i) if (dp[i] != -1) ans[dp[i]] = i; return ans; } };
1,707
Maximum XOR With an Element From Array
3
maximizeXor
You are given an array `nums` consisting of non-negative integers. You are also given a `queries` array, where `queries[i] = [xi, mi]`. The answer to the `ith` query is the maximum bitwise `XOR` value of `xi` and any element of `nums` that does not exceed `mi`. In other words, the answer is `max(nums[j] XOR xi)` for all `j` such that `nums[j] <= mi`. If all elements in `nums` are larger than `mi`, then the answer is `-1`. Return an integer array `answer` where `answer.length == queries.length` and `answer[i]` is the answer to the `ith` query.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator, Optional class TrieNode: def __init__(self): self.children: List[Optional[TrieNode]] = [None] * 2 class BitTrie: def __init__(self, maxBit: int): self.maxBit = maxBit self.root = TrieNode() def insert(self, num: int) -> None: node = self.root for i in range(self.maxBit, -1, -1): bit = num >> i & 1 if not node.children[bit]: node.children[bit] = TrieNode() node = node.children[bit] def getMaxXor(self, num: int) -> int: maxXor = 0 node = self.root for i in range(self.maxBit, -1, -1): bit = num >> i & 1 toggleBit = bit ^ 1 if node.children[toggleBit]: maxXor = maxXor | 1 << i node = node.children[toggleBit] elif node.children[bit]: node = node.children[bit] else: return 0 return maxXor class IndexedQuery: def __init__(self, queryIndex: int, x: int, m: int): self.queryIndex = queryIndex self.x = x self.m = m def __iter__(self): yield self.queryIndex yield self.x yield self.m class Solution: def maximizeXor(self, nums: List[int], queries: List[List[int]]) -> List[int]: ans = [-1] * len(queries) maxBit = int(math.log2(max(max(nums), max(x for x, _ in queries)))) bitTrie = BitTrie(maxBit) nums.sort() i = 0 for queryIndex, x, m in sorted([IndexedQuery(i, x, m) for i, (x, m) in enumerate(queries)], key=lambda iq: iq.m): while i < len(nums) and nums[i] <= m: bitTrie.insert(nums[i]) i += 1 if i > 0 and nums[i - 1] <= m: ans[queryIndex] = bitTrie.getMaxXor(x) return ans
class TrieNode { public TrieNode[] children = new TrieNode[2]; } class BitTrie { public BitTrie(int maxBit) { this.maxBit = maxBit; } public void insert(int num) { TrieNode node = root; for (int i = maxBit; i >= 0; --i) { final int bit = (int) (num >> i & 1); if (node.children[bit] == null) node.children[bit] = new TrieNode(); node = node.children[bit]; } } public int getMaxXor(int num) { int maxXor = 0; TrieNode node = root; for (int i = maxBit; i >= 0; --i) { final int bit = (int) (num >> i & 1); final int toggleBit = bit ^ 1; if (node.children[toggleBit] != null) { maxXor = maxXor | 1 << i; node = node.children[toggleBit]; } else if (node.children[bit] != null) { node = node.children[bit]; } else { // There's nothing in the Bit Trie. return 0; } } return maxXor; } private int maxBit; private TrieNode root = new TrieNode(); } class Solution { public int[] maximizeXor(int[] nums, int[][] queries) { int[] ans = new int[queries.length]; Arrays.fill(ans, -1); final int maxNumInNums = Arrays.stream(nums).max().getAsInt(); final int maxNumInQuery = Arrays.stream(queries).mapToInt(query -> query[0]).max().getAsInt(); final int maxBit = (int) (Math.log(Math.max(maxNumInNums, maxNumInQuery)) / Math.log(2)); BitTrie bitTrie = new BitTrie(maxBit); Arrays.sort(nums); int i = 0; // nums' index for (IndexedQuery indexedQuery : getIndexedQueries(queries)) { final int queryIndex = indexedQuery.queryIndex; final int x = indexedQuery.x; final int m = indexedQuery.m; while (i < nums.length && nums[i] <= m) bitTrie.insert(nums[i++]); if (i > 0 && nums[i - 1] <= m) ans[queryIndex] = bitTrie.getMaxXor(x); } return ans; } private record IndexedQuery(int queryIndex, int x, int m){}; private IndexedQuery[] getIndexedQueries(int[][] queries) { IndexedQuery[] indexedQueries = new IndexedQuery[queries.length]; for (int i = 0; i < queries.length; ++i) indexedQueries[i] = new IndexedQuery(i, queries[i][0], queries[i][1]); Arrays.sort(indexedQueries, Comparator.comparingInt(IndexedQuery::m)); return indexedQueries; } }
struct TrieNode { vector<shared_ptr<TrieNode>> children; TrieNode() : children(2) {} }; class BitTrie { public: BitTrie(int maxBit) : maxBit(maxBit) {} void insert(int num) { shared_ptr<TrieNode> node = root; for (int i = maxBit; i >= 0; --i) { const int bit = num >> i & 1; if (node->children[bit] == nullptr) node->children[bit] = make_shared<TrieNode>(); node = node->children[bit]; } } int getMaxXor(int num) { int maxXor = 0; shared_ptr<TrieNode> node = root; for (int i = maxBit; i >= 0; --i) { const int bit = num >> i & 1; const int toggleBit = bit ^ 1; if (node->children[toggleBit] != nullptr) { maxXor = maxXor | 1 << i; node = node->children[toggleBit]; } else if (node->children[bit] != nullptr) { node = node->children[bit]; } else { // There's nothing in the Bit Trie. return 0; } } return maxXor; } private: const int maxBit; shared_ptr<TrieNode> root = make_shared<TrieNode>(); }; struct IndexedQuery { int queryIndex; int x; int m; }; class Solution { public: vector<int> maximizeXor(vector<int>& nums, vector<vector<int>>& queries) { vector<int> ans(queries.size(), -1); const int maxNumInNums = ranges::max(nums); const int maxNumInQuery = ranges::max_element(queries, ranges::less{}, [](const vector<int>& query) { return query[0]; })->at(0); const int maxBit = static_cast<int>(log2(max(maxNumInNums, maxNumInQuery))); BitTrie bitTrie(maxBit); ranges::sort(nums); int i = 0; // nums' index for (const auto& [queryIndex, x, m] : getIndexedQueries(queries)) { while (i < nums.size() && nums[i] <= m) bitTrie.insert(nums[i++]); if (i > 0 && nums[i - 1] <= m) ans[queryIndex] = bitTrie.getMaxXor(x); } return ans; } private: vector<IndexedQuery> getIndexedQueries(const vector<vector<int>>& queries) { vector<IndexedQuery> indexedQueries; for (int i = 0; i < queries.size(); ++i) indexedQueries.emplace_back(i, queries[i][0], queries[i][1]); ranges::sort( indexedQueries, ranges::less{}, [](const IndexedQuery& indexedQuery) { return indexedQuery.m; }); return indexedQueries; } };
1,717
Maximum Score From Removing Substrings
2
maximumGain
You are given a string `s` and two integers `x` and `y`. You can perform two types of operations any number of times. * Remove substring `"ab"` and gain `x` points. * For example, when removing `"ab"` from `"cabxbae"` it becomes `"cxbae"`. * Remove substring `"ba"` and gain `y` points. * For example, when removing `"ba"` from `"cabxbae"` it becomes `"cabxe"`. Return the maximum points you can gain after applying the above operations on `s`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def maximumGain(self, s: str, x: int, y: int) -> int: if x > y: return self._gain(s, 'ab', x, 'ba', y) else: return self._gain(s, 'ba', y, 'ab', x) def _gain(self, s: str, sub1: str, point1: int, sub2: str, point2: int) -> int: points = 0 stack1 = [] stack2 = [] for c in s: if stack1 and stack1[-1] == sub1[0] and c == sub1[1]: stack1.pop() points += point1 else: stack1.append(c) for c in stack1: if stack2 and stack2[-1] == sub2[0] and c == sub2[1]: stack2.pop() points += point2 else: stack2.append(c) return points
class Solution { public int maximumGain(String s, int x, int y) { // The assumption that gain("ab") > gain("ba") while removing "ba" first is // optimal is contradicted. Only "b(ab)a" satisfies the condition of // preventing two "ba" removals, but after removing "ab", we can still // remove one "ba", resulting in a higher gain. Thus, removing "ba" first is // not optimal. return x > y ? gain(s, "ab", x, "ba", y) : gain(s, "ba", y, "ab", x); } // Returns the points gained by first removing sub1 ("ab" | "ba") from s with // point1, then removing sub2 ("ab" | "ba") from s with point2. private int gain(final String s, final String sub1, int point1, final String sub2, int point2) { int points = 0; Stack<Character> stack1 = new Stack<>(); Stack<Character> stack2 = new Stack<>(); // Remove "sub1" from s with point1 gain. for (final char c : s.toCharArray()) if (!stack1.isEmpty() && stack1.peek() == sub1.charAt(0) && c == sub1.charAt(1)) { stack1.pop(); points += point1; } else { stack1.push(c); } // Remove "sub2" from s with point2 gain. for (final char c : stack1) if (!stack2.isEmpty() && stack2.peek() == sub2.charAt(0) && c == sub2.charAt(1)) { stack2.pop(); points += point2; } else { stack2.push(c); } return points; } }
class Solution { public: int maximumGain(string s, int x, int y) { // The assumption that gain("ab") > gain("ba") while removing "ba" first is // optimal is contradicted. Only "b(ab)a" satisfies the condition of // preventing two "ba" removals, but after removing "ab", we can still // remove one "ba", resulting in a higher gain. Thus, removing "ba" first is // not optimal. return x > y ? gain(s, "ab", x, "ba", y) : gain(s, "ba", y, "ab", x); } private: // Returns the points gained by first removing sub1 ("ab" | "ba") from s with // point1, then removing sub2 ("ab" | "ba") from s with point2. int gain(const string& s, const string& sub1, int point1, const string& sub2, int point2) { int points = 0; vector<char> stack1; vector<char> stack2; // Remove "sub1" from s with point1 gain. for (const char c : s) if (!stack1.empty() && stack1.back() == sub1[0] && c == sub1[1]) { stack1.pop_back(); points += point1; } else { stack1.push_back(c); } // Remove "sub2" from s with point2 gain. for (const char c : stack1) if (!stack2.empty() && stack2.back() == sub2[0] && c == sub2[1]) { stack2.pop_back(); points += point2; } else { stack2.push_back(c); } return points; } };
1,719
Number Of Ways To Reconstruct A Tree
3
checkWays
You are given an array `pairs`, where `pairs[i] = [xi, yi]`, and: * There are no duplicates. * `xi < yi` Let `ways` be the number of rooted trees that satisfy the following conditions: * The tree consists of nodes whose values appeared in `pairs`. * A pair `[xi, yi]` exists in `pairs` if and only if `xi` is an ancestor of `yi` or `yi` is an ancestor of `xi`. * Note: the tree does not have to be a binary tree. Two ways are considered to be different if there is at least one node that has different parents in both ways. Return: * `0` if `ways == 0` * `1` if `ways == 1` * `2` if `ways > 1` A rooted tree is a tree that has a single root node, and all edges are oriented to be outgoing from the root. An ancestor of a node is any node on the path from the root to that node (excluding the node itself). The root has no ancestors.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def checkWays(self, pairs: List[List[int]]) -> int: kMax = 501 graph = collections.defaultdict(list) degrees = [0] * kMax connected = [[False] * kMax for _ in range(kMax)] for u, v in pairs: graph[u].append(v) graph[v].append(u) degrees[u] += 1 degrees[v] += 1 connected[u][v] = True connected[v][u] = True for _, children in graph.items(): children.sort(key=lambda a: degrees[a], reverse=True) root = next((i for i, d in enumerate(degrees) if d == len(graph) - 1), -1) if root == -1: return 0 hasMoreThanOneWay = False def dfs(u: int, ancestors: List[int], seen: List[bool]) -> bool: nonlocal hasMoreThanOneWay seen[u] = True for ancestor in ancestors: if not connected[u][ancestor]: return False ancestors.append(u) for v in graph[u]: if seen[v]: continue if degrees[v] == degrees[u]: hasMoreThanOneWay = True if not dfs(v, ancestors, seen): return False ancestors.pop() return True if not dfs(root, [], [False] * kMax): return 0 if hasMoreThanOneWay: return 2 else: return 1
class Solution { public int checkWays(int[][] pairs) { final int MAX = 501; Map<Integer, List<Integer>> graph = new HashMap<>(); int[] degrees = new int[MAX]; boolean[][] connected = new boolean[MAX][MAX]; for (int[] pair : pairs) { final int u = pair[0]; final int v = pair[1]; graph.putIfAbsent(u, new ArrayList<>()); graph.putIfAbsent(v, new ArrayList<>()); graph.get(u).add(v); graph.get(v).add(u); ++degrees[u]; ++degrees[v]; connected[u][v] = true; connected[v][u] = true; } // For each node, sort its children by degrees in descending order. for (final int u : graph.keySet()) graph.get(u).sort(Comparator.comparingInt(a -> - degrees[a])); final int root = getRoot(degrees, graph.keySet().size()); if (root == -1) return 0; if (!dfs(graph, root, degrees, connected, new ArrayList<>(), new boolean[MAX])) return 0; return hasMoreThanOneWay ? 2 : 1; } private boolean hasMoreThanOneWay = false; // Returns the root by finding the node with a degree that equals to n - 1. private int getRoot(int[] degrees, int n) { for (int i = 1; i < degrees.length; ++i) if (degrees[i] == n - 1) return i; return -1; } // Returns true if each node rooted at u is connected to all of its ancestors. private boolean dfs(Map<Integer, List<Integer>> graph, int u, int[] degrees, boolean[][] connected, List<Integer> ancestors, boolean[] seen) { seen[u] = true; for (final int ancestor : ancestors) if (!connected[u][ancestor]) return false; ancestors.add(u); for (final int v : graph.get(u)) { if (seen[v]) continue; // We can swap u with v, so there are more than one way. if (degrees[v] == degrees[u]) hasMoreThanOneWay = true; if (!dfs(graph, v, degrees, connected, ancestors, seen)) return false; } ancestors.remove(ancestors.size() - 1); return true; } }
class Solution { public: int checkWays(vector<vector<int>>& pairs) { constexpr int kMax = 501; unordered_map<int, vector<int>> graph; vector<int> degrees(kMax); vector<vector<bool>> connected(kMax, vector<bool>(kMax)); for (const vector<int>& pair : pairs) { const int u = pair[0]; const int v = pair[1]; graph[u].push_back(v); graph[v].push_back(u); ++degrees[u]; ++degrees[v]; connected[u][v] = true; connected[v][u] = true; } // For each node, sort its children by degrees in descending order. for (auto& [_, children] : graph) ranges::sort(children, ranges::greater{}, [&degrees](int child) { return degrees[child]; }); const int root = getRoot(degrees, graph.size()); if (root == -1) return 0; if (!dfs(graph, root, degrees, connected, {}, vector<bool>(kMax))) return 0; return hasMoreThanOneWay ? 2 : 1; } private: bool hasMoreThanOneWay = false; // Returns the root by finding the node with a degree that equals to n - 1. int getRoot(const vector<int>& degrees, int n) { for (int i = 1; i < degrees.size(); ++i) if (degrees[i] == n - 1) return i; return -1; } // Returns true if each node rooted at u is connected to all of its ancestors. bool dfs(const unordered_map<int, vector<int>>& graph, int u, vector<int>& degrees, vector<vector<bool>>& connected, vector<int>&& ancestors, vector<bool>&& seen) { seen[u] = true; for (const int ancestor : ancestors) if (!connected[u][ancestor]) return false; ancestors.push_back(u); for (const int v : graph.at(u)) { if (seen[v]) continue; // We can swap u with v, so there are more than one way. if (degrees[v] == degrees[u]) hasMoreThanOneWay = true; if (!dfs(graph, v, degrees, connected, std::move(ancestors), std::move(seen))) return false; } ancestors.pop_back(); return true; } };
1,722
Minimize Hamming Distance After Swap Operations
2
minimumHammingDistance
You are given two integer arrays, `source` and `target`, both of length `n`. You are also given an array `allowedSwaps` where each `allowedSwaps[i] = [ai, bi]` indicates that you are allowed to swap the elements at index `ai` and index `bi` (0-indexed) of array `source`. Note that you can swap elements at a specific pair of indices multiple times and in any order. The Hamming distance of two arrays of the same length, `source` and `target`, is the number of positions where the elements are different. Formally, it is the number of indices `i` for `0 <= i <= n-1` where `source[i] != target[i]` (0-indexed). Return the minimum Hamming distance of `source` and `target` after performing any amount of swap operations on array `source`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class UnionFind: def __init__(self, n: int): self.id = list(range(n)) self.rank = [0] * n def unionByRank(self, u: int, v: int) -> None: i = self.find(u) j = self.find(v) if i == j: return if self.rank[i] < self.rank[j]: self.id[i] = j elif self.rank[i] > self.rank[j]: self.id[j] = i else: self.id[i] = j self.rank[j] += 1 def find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self.find(self.id[u]) return self.id[u] class Solution: def minimumHammingDistance(self, source: List[int], target: List[int], allowedSwaps: List[List[int]]) -> int: n = len(source) ans = 0 uf = UnionFind(n) groupIdToCount = [collections.Counter() for _ in range(n)] for a, b in allowedSwaps: uf.unionByRank(a, b) for i in range(n): groupIdToCount[uf.find(i)][source[i]] += 1 for i in range(n): groupId = uf.find(i) count = groupIdToCount[groupId] if target[i] not in count: ans += 1 else: count[target[i]] -= 1 if count[target[i]] == 0: del count[target[i]] return ans
class UnionFind { public UnionFind(int n) { id = new int[n]; rank = new int[n]; for (int i = 0; i < n; ++i) id[i] = i; } public void unionByRank(int u, int v) { final int i = find(u); final int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } public int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } private int[] id; private int[] rank; } class Solution { public int minimumHammingDistance(int[] source, int[] target, int[][] allowedSwaps) { final int n = source.length; int ans = 0; UnionFind uf = new UnionFind(n); Map<Integer, Integer>[] groupIdToCount = new Map[n]; for (int i = 0; i < n; ++i) groupIdToCount[i] = new HashMap<>(); for (int[] allowedSwap : allowedSwaps) { final int a = allowedSwap[0]; final int b = allowedSwap[1]; uf.unionByRank(a, b); } for (int i = 0; i < n; ++i) groupIdToCount[uf.find(i)].merge(source[i], 1, Integer::sum); for (int i = 0; i < n; ++i) { final int groupId = uf.find(i); Map<Integer, Integer> count = groupIdToCount[groupId]; if (!count.containsKey(target[i])) ++ans; else if (count.merge(target[i], -1, Integer::sum) == 0) count.remove(target[i]); } return ans; } }
class UnionFind { public: UnionFind(int n) : id(n), rank(n) { iota(id.begin(), id.end(), 0); } void unionByRank(int u, int v) { const int i = find(u); const int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } private: vector<int> id; vector<int> rank; }; class Solution { public: int minimumHammingDistance(vector<int>& source, vector<int>& target, vector<vector<int>>& allowedSwaps) { const int n = source.size(); int ans = 0; UnionFind uf(n); vector<unordered_map<int, int>> groupIdToCount(n); for (const vector<int>& allowedSwap : allowedSwaps) { const int a = allowedSwap[0]; const int b = allowedSwap[1]; uf.unionByRank(a, b); } for (int i = 0; i < n; ++i) ++groupIdToCount[uf.find(i)][source[i]]; for (int i = 0; i < n; ++i) { const int groupId = uf.find(i); unordered_map<int, int>& count = groupIdToCount[groupId]; if (!count.contains(target[i])) ++ans; else if (--count[target[i]] == 0) count.erase(target[i]); } return ans; } };
1,735
Count Ways to Make Array With Product
3
waysToFillArray
You are given a 2D integer array, `queries`. For each `queries[i]`, where `queries[i] = [ni, ki]`, find the number of different ways you can place positive integers into an array of size `ni` such that the product of the integers is `ki`. As the number of ways may be too large, the answer to the `ith` query is the number of ways modulo `109 + 7`. Return an integer array `answer` where `answer.length == queries.length`, and `answer[i]` is the answer to the `ith` query.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def waysToFillArray(self, queries: List[List[int]]) -> List[int]: kMod = 1_000_000_007 kMax = 10_000 minPrimeFactors = self._sieveEratosthenes(kMax + 1) @functools.lru_cache(None) def fact(i: int) -> int: return 1 if i <= 1 else i * fact(i - 1) % kMod @functools.lru_cache(None) def inv(i: int) -> int: return pow(i, kMod - 2, kMod) @functools.lru_cache(None) def nCk(n: int, k: int) -> int: return fact(n) * inv(fact(k)) * inv(fact(n - k)) % kMod ans = [] for n, k in queries: res = 1 for freq in self._getPrimeFactorsCount(k, minPrimeFactors).values(): res = res * nCk(n - 1 + freq, freq) % kMod ans.append(res) return ans def _sieveEratosthenes(self, n: int) -> List[int]: minPrimeFactors = [i for i in range(n + 1)] for i in range(2, int(n**0.5) + 1): if minPrimeFactors[i] == i: for j in range(i * i, n, i): minPrimeFactors[j] = min(minPrimeFactors[j], i) return minPrimeFactors def _getPrimeFactorsCount(self, num: int, minPrimeFactors: List[int]) -> Dict[int, int]: count = collections.Counter() while num > 1: divisor = minPrimeFactors[num] while num % divisor == 0: num //= divisor count[divisor] += 1 return count
class Solution { public int[] waysToFillArray(int[][] queries) { final int MAX = 10_000; final int MAX_FREQ = 13; // 2^13 = 8192 < MAX final int[] minPrimeFactors = sieveEratosthenes(MAX + 1); final long[][] factAndInvFact = getFactAndInvFact(MAX + MAX_FREQ - 1); final long[] fact = factAndInvFact[0]; final long[] invFact = factAndInvFact[1]; int[] ans = new int[queries.length]; for (int i = 0; i < queries.length; ++i) { final int n = queries[i][0]; final int k = queries[i][1]; int res = 1; for (final int freq : getPrimeFactorsCount(k, minPrimeFactors).values()) res = (int) ((long) res * nCk(n - 1 + freq, freq, fact, invFact) % MOD); ans[i] = res; } return ans; } private static final int MOD = 1_000_000_007; // Gets the minimum prime factor of i, where 1 < i <= n. private int[] sieveEratosthenes(int n) { int[] minPrimeFactors = new int[n + 1]; for (int i = 2; i <= n; ++i) minPrimeFactors[i] = i; for (int i = 2; i * i < n; ++i) if (minPrimeFactors[i] == i) // `i` is prime. for (int j = i * i; j < n; j += i) minPrimeFactors[j] = Math.min(minPrimeFactors[j], i); return minPrimeFactors; } private Map<Integer, Integer> getPrimeFactorsCount(int num, int[] minPrimeFactors) { Map<Integer, Integer> count = new HashMap<>(); while (num > 1) { final int divisor = minPrimeFactors[num]; while (num % divisor == 0) { num /= divisor; count.put(divisor, count.merge(divisor, 1, Integer::sum)); } } return count; } private long[][] getFactAndInvFact(int n) { long[] fact = new long[n + 1]; long[] invFact = new long[n + 1]; long[] inv = new long[n + 1]; fact[0] = invFact[0] = 1; inv[0] = inv[1] = 1; for (int i = 1; i <= n; ++i) { if (i >= 2) inv[i] = MOD - MOD / i * inv[MOD % i] % MOD; fact[i] = fact[i - 1] * i % MOD; invFact[i] = invFact[i - 1] * inv[i] % MOD; } return new long[][] {fact, invFact}; } private int nCk(int n, int k, long[] fact, long[] invFact) { return (int) (fact[n] * invFact[k] % MOD * invFact[n - k] % MOD); } }
class Solution { public: vector<int> waysToFillArray(vector<vector<int>>& queries) { constexpr int kMax = 10000; constexpr int kMaxFreq = 13; // 2^13 = 8192 < kMax const vector<int> minPrimeFactors = sieveEratosthenes(kMax + 1); const auto [fact, invFact] = getFactAndInvFact(kMax + kMaxFreq - 1); vector<int> ans; for (const vector<int>& query : queries) { const int n = query[0]; const int k = query[1]; int res = 1; for (const auto& [_, freq] : getPrimeFactorsCount(k, minPrimeFactors)) res = static_cast<long>(res) * nCk(n - 1 + freq, freq, fact, invFact) % kMod; ans.push_back(res); } return ans; } private: static constexpr int kMod = 1'000'000'007; // Gets the minimum prime factor of i, where 1 < i <= n. vector<int> sieveEratosthenes(int n) { vector<int> minPrimeFactors(n + 1); iota(minPrimeFactors.begin() + 2, minPrimeFactors.end(), 2); for (int i = 2; i * i < n; ++i) if (minPrimeFactors[i] == i) // `i` is prime. for (int j = i * i; j < n; j += i) minPrimeFactors[j] = min(minPrimeFactors[j], i); return minPrimeFactors; } unordered_map<int, int> getPrimeFactorsCount( int num, const vector<int>& minPrimeFactors) { unordered_map<int, int> count; while (num > 1) { const int divisor = minPrimeFactors[num]; while (num % divisor == 0) { num /= divisor; ++count[divisor]; } } return count; } pair<vector<long>, vector<long>> getFactAndInvFact(int n) { vector<long> fact(n + 1); vector<long> invFact(n + 1); vector<long> inv(n + 1); fact[0] = invFact[0] = 1; inv[0] = inv[1] = 1; for (int i = 1; i <= n; ++i) { if (i >= 2) inv[i] = kMod - kMod / i * inv[kMod % i] % kMod; fact[i] = fact[i - 1] * i % kMod; invFact[i] = invFact[i - 1] * inv[i] % kMod; } return {fact, invFact}; } int nCk(int n, int k, const vector<long>& fact, const vector<long>& invFact) { return fact[n] * invFact[k] % kMod * invFact[n - k] % kMod; } };
1,765
Map of Highest Peak
2
highestPeak
You are given an integer matrix `isWater` of size `m x n` that represents a map of land and water cells. * If `isWater[i][j] == 0`, cell `(i, j)` is a land cell. * If `isWater[i][j] == 1`, cell `(i, j)` is a water cell. You must assign each cell a height in a way that follows these rules: * The height of each cell must be non-negative. * If the cell is a water cell, its height must be `0`. * Any two adjacent cells must have an absolute height difference of at most `1`. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching). Find an assignment of heights such that the maximum height in the matrix is maximized. Return an integer matrix `height` of size `m x n` where `height[i][j]` is cell `(i, j)`'s height. If there are multiple solutions, return any of them.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def highestPeak(self, isWater: List[List[int]]) -> List[List[int]]: dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) m = len(isWater) n = len(isWater[0]) ans = [[-1] * n for _ in range(m)] q = collections.deque() for i in range(m): for j in range(n): if isWater[i][j] == 1: q.append((i, j)) ans[i][j] = 0 while q: i, j = q.popleft() for dx, dy in dirs: x = i + dx y = j + dy if x < 0 or x == m or y < 0 or y == n: continue if ans[x][y] != -1: continue ans[x][y] = ans[i][j] + 1 q.append((x, y)) return ans
class Solution { public int[][] highestPeak(int[][] isWater) { final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; final int m = isWater.length; final int n = isWater[0].length; int[][] ans = new int[m][n]; Arrays.stream(ans).forEach(A -> Arrays.fill(A, -1)); Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (isWater[i][j] == 1) { q.offer(new Pair<>(i, j)); ans[i][j] = 0; } while (!q.isEmpty()) { final int i = q.peek().getKey(); final int j = q.poll().getValue(); for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == m || y < 0 || y == n) continue; if (ans[x][y] != -1) continue; ans[x][y] = ans[i][j] + 1; q.offer(new Pair<>(x, y)); } } return ans; } }
class Solution { public: vector<vector<int>> highestPeak(vector<vector<int>>& isWater) { constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; const int m = isWater.size(); const int n = isWater[0].size(); vector<vector<int>> ans(m, vector<int>(n, -1)); queue<pair<int, int>> q; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (isWater[i][j] == 1) { q.emplace(i, j); ans[i][j] = 0; } while (!q.empty()) { const auto [i, j] = q.front(); q.pop(); for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == m || y < 0 || y == n) continue; if (ans[x][y] != -1) continue; ans[x][y] = ans[i][j] + 1; q.emplace(x, y); } } return ans; } };
1,782
Count Pairs Of Nodes
3
countPairs
You are given an undirected graph defined by an integer `n`, the number of nodes, and a 2D integer array `edges`, the edges in the graph, where `edges[i] = [ui, vi]` indicates that there is an undirected edge between `ui` and `vi`. You are also given an integer array `queries`. Let `incident(a, b)` be defined as the number of edges that are connected to either node `a` or `b`. The answer to the `jth` query is the number of pairs of nodes `(a, b)` that satisfy both of the following conditions: * `a < b` * `incident(a, b) > queries[j]` Return an array `answers` such that `answers.length == queries.length` and `answers[j]` is the answer of the `jth` query. Note that there can be multiple edges between the same two nodes.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def countPairs(self, n: int, edges: List[List[int]], queries: List[int]) -> List[int]: ans = [0] * len(queries) count = [0] * (n + 1) shared = [collections.Counter() for _ in range(n + 1)] for u, v in edges: count[u] += 1 count[v] += 1 shared[min(u, v)][max(u, v)] += 1 sortedCount = sorted(count) for k, query in enumerate(queries): i = 1 j = n while i < j: if sortedCount[i] + sortedCount[j] > query: ans[k] += j - i j -= 1 else: i += 1 for i in range(1, n + 1): for j, sh in shared[i].items(): if count[i] + count[j] > query and count[i] + count[j] - sh <= query: ans[k] -= 1 return ans
class Solution { public int[] countPairs(int n, int[][] edges, int[] queries) { int[] ans = new int[queries.length]; // count[i] := the number of edges of node i int[] count = new int[n + 1]; // shared[i][j] := the number of edges incident to i or j, where i < j Map<Integer, Integer>[] shared = new Map[n + 1]; for (int i = 1; i <= n; ++i) shared[i] = new HashMap<>(); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; ++count[u]; ++count[v]; shared[Math.min(u, v)].merge(Math.max(u, v), 1, Integer::sum); } int[] sortedCount = count.clone(); Arrays.sort(sortedCount); int k = 0; for (final int query : queries) { for (int i = 1, j = n; i < j;) if (sortedCount[i] + sortedCount[j] > query) // sortedCount[i] + sortedCount[j] > query // sortedCount[i + 1] + sortedCount[j] > query // ... // sortedCount[j - 1] + sortedCount[j] > query // So, there are (j - 1) - i + 1 = j - i pairs > query ans[k] += (j--) - i; else ++i; for (int i = 1; i <= n; ++i) for (Map.Entry<Integer, Integer> p : shared[i].entrySet()) { final int j = p.getKey(); final int sh = p.getValue(); if (count[i] + count[j] > query && count[i] + count[j] - sh <= query) --ans[k]; } ++k; } return ans; } }
class Solution { public: vector<int> countPairs(int n, vector<vector<int>>& edges, vector<int>& queries) { vector<int> ans(queries.size()); // count[i] := the number of edges of node i vector<int> count(n + 1); // shared[i][j] := the number of edges incident to i or j, where i < j vector<unordered_map<int, int>> shared(n + 1); for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; ++count[u]; ++count[v]; ++shared[min(u, v)][max(u, v)]; } vector<int> sortedCount(count); ranges::sort(sortedCount); int k = 0; for (const int query : queries) { for (int i = 1, j = n; i < j;) if (sortedCount[i] + sortedCount[j] > query) // sortedCount[i] + sortedCount[j] > query // sortedCount[i + 1] + sortedCount[j] > query // ... // sortedCount[j - 1] + sortedCount[j] > query // So, there are (j - 1) - i + 1 = j - i pairs > query ans[k] += (j--) - i; else ++i; for (int i = 1; i <= n; ++i) for (const auto& [j, sh] : shared[i]) if (count[i] + count[j] > query && count[i] + count[j] - sh <= query) --ans[k]; ++k; } return ans; } };
1,786
Number of Restricted Paths From First to Last Node
2
countRestrictedPaths
There is an undirected weighted connected graph. You are given a positive integer `n` which denotes that the graph has `n` nodes labeled from `1` to `n`, and an array `edges` where each `edges[i] = [ui, vi, weighti]` denotes that there is an edge between nodes `ui` and `vi` with weight equal to `weighti`. A path from node `start` to node `end` is a sequence of nodes `[z0, z1, z2, ..., zk]` such that `z0 = start` and `zk = end` and there is an edge between `zi` and `zi+1` where `0 <= i <= k-1`. The distance of a path is the sum of the weights on the edges of the path. Let `distanceToLastNode(x)` denote the shortest distance of a path between node `n` and node `x`. A restricted path is a path that also satisfies that `distanceToLastNode(zi) > distanceToLastNode(zi+1)` where `0 <= i <= k-1`. Return the number of restricted paths from node `1` to node `n`. Since that number may be too large, return it modulo `109 + 7`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int: graph = [[] for _ in range(n)] for u, v, w in edges: graph[u - 1].append((v - 1, w)) graph[v - 1].append((u - 1, w)) return self._dijkstra(graph, 0, n - 1) def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, dst: int) -> int: kMod = 10**9 + 7 ways = [0] * len(graph) dist = [math.inf] * len(graph) ways[dst] = 1 dist[dst] = 0 minHeap = [(dist[dst], dst)] while minHeap: d, u = heapq.heappop(minHeap) if d > dist[u]: continue for v, w in graph[u]: if d + w < dist[v]: dist[v] = d + w heapq.heappush(minHeap, (dist[v], v)) if dist[v] < dist[u]: ways[u] += ways[v] ways[u] %= kMod return ways[src]
class Solution { public int countRestrictedPaths(int n, int[][] edges) { List<Pair<Integer, Integer>>[] graph = new List[n]; Arrays.setAll(graph, i -> new ArrayList<>()); for (int[] edge : edges) { final int u = edge[0] - 1; final int v = edge[1] - 1; final int w = edge[2]; graph[u].add(new Pair<>(v, w)); graph[v].add(new Pair<>(u, w)); } return dijkstra(graph, 0, n - 1); } private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst) { final int MOD = 1_000_000_007; // ways[i] := the number of restricted path from i to n long[] ways = new long[graph.length]; // dist[i] := the distance to the last node of i long[] dist = new long[graph.length]; Arrays.fill(dist, Long.MAX_VALUE); ways[dst] = 1; dist[dst] = 0; // (d, u) Queue<Pair<Long, Integer>> minHeap = new PriorityQueue<>(Comparator.comparingLong(Pair::getKey)); minHeap.offer(new Pair<>(dist[dst], dst)); while (!minHeap.isEmpty()) { final long d = minHeap.peek().getKey(); final int u = minHeap.poll().getValue(); if (d > dist[u]) continue; for (Pair<Integer, Integer> pair : graph[u]) { final int v = pair.getKey(); final int w = pair.getValue(); if (d + w < dist[v]) { dist[v] = d + w; minHeap.offer(new Pair<>(dist[v], v)); } if (dist[v] < dist[u]) { ways[u] += ways[v]; ways[u] %= MOD; } } } return (int) ways[src]; } }
class Solution { public: int countRestrictedPaths(int n, vector<vector<int>>& edges) { vector<vector<pair<int, int>>> graph(n); for (const vector<int>& edge : edges) { const int u = edge[0] - 1; const int v = edge[1] - 1; const int w = edge[2]; graph[u].emplace_back(v, w); graph[v].emplace_back(u, w); } return dijkstra(graph, 0, n - 1); } private: int dijkstra(const vector<vector<pair<int, int>>>& graph, int src, int dst) { constexpr int kMod = 1'000'000'007; // ways[i] := the number of restricted path from i to n vector<long> ways(graph.size()); // dist[i] := the distance to the last node of i vector<long> dist(graph.size(), LONG_MAX); ways[dst] = 1; dist[dst] = 0; using P = pair<long, int>; // (d, u) priority_queue<P, vector<P>, greater<>> minHeap; minHeap.emplace(dist[dst], dst); while (!minHeap.empty()) { const auto [d, u] = minHeap.top(); minHeap.pop(); if (d > dist[u]) continue; for (const auto& [v, w] : graph[u]) { if (d + w < dist[v]) { dist[v] = d + w; minHeap.emplace(dist[v], v); } if (dist[v] < dist[u]) { ways[u] += ways[v]; ways[u] %= kMod; } } } return ways[src]; } };
1,793
Maximum Score of a Good Subarray
3
maximumScore
You are given an array of integers `nums` (0-indexed) and an integer `k`. The score of a subarray `(i, j)` is defined as `min(nums[i], nums[i+1], ..., nums[j]) * (j - i + 1)`. A good subarray is a subarray where `i <= k <= j`. Return the maximum possible score of a good subarray.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def maximumScore(self, nums: List[int], k: int) -> int: ans = 0 stack = [] for i in range(len(nums) + 1): while stack and (i == len(nums) or nums[stack[-1]] > nums[i]): h = nums[stack.pop()] w = i - stack[-1] - 1 if stack else i if (not stack or stack[-1] + 1 <= k) and i - 1 >= k: ans = max(ans, h * w) stack.append(i) return ans
class Solution { // Similar to 84. Largest Rectangle in Histogram public int maximumScore(int[] nums, int k) { int ans = 0; Deque<Integer> stack = new ArrayDeque<>(); for (int i = 0; i <= nums.length; ++i) { while (!stack.isEmpty() && (i == nums.length || nums[stack.peek()] > nums[i])) { final int h = nums[stack.pop()]; final int w = stack.isEmpty() ? i : i - stack.peek() - 1; if ((stack.isEmpty() || stack.peek() + 1 <= k) && i - 1 >= k) ans = Math.max(ans, h * w); } stack.push(i); } return ans; } }
class Solution { public: // Similar to 84. Largest Rectangle in Histogram int maximumScore(vector<int>& nums, int k) { int ans = 0; stack<int> stack; for (int i = 0; i <= nums.size(); ++i) { while (!stack.empty() && (i == nums.size() || nums[stack.top()] > nums[i])) { const int h = nums[stack.top()]; stack.pop(); const int w = stack.empty() ? i : i - stack.top() - 1; if ((stack.empty() || stack.top() + 1 <= k) && i - 1 >= k) ans = max(ans, h * w); } stack.push(i); } return ans; } };
1,805
Number of Different Integers in a String
1
numDifferentIntegers
You are given a string `word` that consists of digits and lowercase English letters. You will replace every non-digit character with a space. For example, `"a123bc34d8ef34"` will become `" 123 34 8 34"`. Notice that you are left with some integers that are separated by at least one space: `"123"`, `"34"`, `"8"`, and `"34"`. Return the number of different integers after performing the replacement operations on `word`. Two integers are considered different if their decimal representations without any leading zeros are different.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def numDifferentIntegers(self, word: str) -> int: nums = set() curr = [] for c in word: if c.isdigit(): curr.append(c) elif curr: nums.add(''.join(self._removeLeadingZeros(curr))) curr = [] if curr: nums.add(''.join(self._removeLeadingZeros(curr))) return len(nums) def _removeLeadingZeros(self, s: str) -> str: index = next((i for i, c in enumerate(s) if c != '0'), -1) if index == -1: return ['0'] else: return s[index:]
class Solution { public int numDifferentIntegers(String word) { HashSet<String> nums = new HashSet<>(); StringBuilder sb = new StringBuilder(); for (final char c : word.toCharArray()) if (Character.isDigit(c)) { sb.append(c); } else if (sb.length() > 0) { nums.add(removeLeadingZeros(sb.toString())); sb = new StringBuilder(); } if (sb.length() > 0) nums.add(removeLeadingZeros(sb.toString())); return nums.size(); } private String removeLeadingZeros(final String s) { int index = 0; while (index < s.length() && s.charAt(index) == '0') ++index; return index == s.length() ? "0" : s.substring(index); } }
class Solution { public: int numDifferentIntegers(string word) { unordered_set<string> nums; string curr; for (const char c : word) if (isdigit(c)) { curr += c; } else if (curr.length() > 0) { nums.insert(removeLeadingZeros(curr)); curr = ""; } if (curr.length() > 0) nums.insert(removeLeadingZeros(curr)); return nums.size(); } private: string removeLeadingZeros(const string& s) { const int index = s.find_first_not_of('0'); return index == string::npos ? "0" : s.substr(index); } };
1,857
Largest Color Value in a Directed Graph
3
largestPathValue
There is a directed graph of `n` colored nodes and `m` edges. The nodes are numbered from `0` to `n - 1`. You are given a string `colors` where `colors[i]` is a lowercase English letter representing the color of the `ith` node in this graph (0-indexed). You are also given a 2D array `edges` where `edges[j] = [aj, bj]` indicates that there is a directed edge from node `aj` to node `bj`. A valid path in the graph is a sequence of nodes `x1 -> x2 -> x3 -> ... -> xk` such that there is a directed edge from `xi` to `xi+1` for every `1 <= i < k`. The color value of the path is the number of nodes that are colored the most frequently occurring color along that path. Return the largest color value of any valid path in the given graph, or `-1` if the graph contains a cycle.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def largestPathValue(self, colors: str, edges: List[List[int]]) -> int: n = len(colors) ans = 0 processed = 0 graph = [[] for _ in range(n)] inDegrees = [0] * n q = collections.deque() count = [[0] * 26 for _ in range(n)] for u, v in edges: graph[u].append(v) inDegrees[v] += 1 for i, degree in enumerate(inDegrees): if degree == 0: q.append(i) while q: u = q.popleft() processed += 1 count[u][ord(colors[u]) - ord('a')] += 1 ans = max(ans, count[u][ord(colors[u]) - ord('a')]) for v in graph[u]: for i in range(26): count[v][i] = max(count[v][i], count[u][i]) inDegrees[v] -= 1 if inDegrees[v] == 0: q.append(v) if processed == n: return ans else: return -1
class Solution { public int largestPathValue(String colors, int[][] edges) { final int n = colors.length(); int ans = 0; int processed = 0; List<Integer>[] graph = new List[n]; int[] inDegrees = new int[n]; int[][] count = new int[n][26]; Arrays.setAll(graph, i -> new ArrayList<>()); // Build the graph. for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; graph[u].add(v); ++inDegrees[v]; } // Perform topological sorting. Queue<Integer> q = IntStream.range(0, n) .filter(i -> inDegrees[i] == 0) .boxed() .collect(Collectors.toCollection(ArrayDeque::new)); while (!q.isEmpty()) { final int out = q.poll(); ++processed; ans = Math.max(ans, ++count[out][colors.charAt(out) - 'a']); for (final int in : graph[out]) { for (int i = 0; i < 26; ++i) count[in][i] = Math.max(count[in][i], count[out][i]); if (--inDegrees[in] == 0) q.offer(in); } } return processed == n ? ans : -1; } }
class Solution { public: int largestPathValue(string colors, vector<vector<int>>& edges) { const int n = colors.length(); int ans = 0; int processed = 0; vector<vector<int>> graph(n); vector<int> inDegrees(n); queue<int> q; vector<vector<int>> count(n, vector<int>(26)); // Build the graph. for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; graph[u].push_back(v); ++inDegrees[v]; } // Perform topological sorting. for (int i = 0; i < n; ++i) if (inDegrees[i] == 0) q.push(i); while (!q.empty()) { const int out = q.front(); q.pop(); ++processed; ans = max(ans, ++count[out][colors[out] - 'a']); for (const int in : graph[out]) { for (int i = 0; i < 26; ++i) count[in][i] = max(count[in][i], count[out][i]); if (--inDegrees[in] == 0) q.push(in); } } return processed == n ? ans : -1; } };
1,878
Get Biggest Three Rhombus Sums in a Grid
2
getBiggestThree
You are given an `m x n` integer matrix `grid`​​​. A rhombus sum is the sum of the elements that form the border of a regular rhombus shape in `grid`​​​. The rhombus must have the shape of a square rotated 45 degrees with each of the corners centered in a grid cell. Below is an image of four valid rhombus shapes with the corresponding colored cells that should be included in each rhombus sum: Note that the rhombus can have an area of 0, which is depicted by the purple rhombus in the bottom right corner. Return the biggest three distinct rhombus sums in the `grid` in descending order. If there are less than three distinct values, return all of them.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator from sortedcontainers import SortedSet class Solution: def getBiggestThree(self, grid: List[List[int]]) -> List[int]: m = len(grid) n = len(grid[0]) sums = SortedSet() for i in range(m): for j in range(n): sz = 0 while i + sz < m and i - sz >= 0 and j + 2 * sz < n: summ = grid[i][j] if sz == 0 else self._getSum(grid, i, j, sz) sums.add(summ) if len(sums) > 3: sums.pop(0) sz += 1 return reversed(sums) def _getSum(self, grid: List[List[int]], i: int, j: int, sz: int) -> int: x = i y = j summ = 0 for _ in range(sz): x -= 1 y += 1 summ += grid[x][y] for _ in range(sz): x += 1 y += 1 summ += grid[x][y] for _ in range(sz): x += 1 y -= 1 summ += grid[x][y] for _ in range(sz): x -= 1 y -= 1 summ += grid[x][y] return summ
class Solution { public int[] getBiggestThree(int[][] grid) { final int m = grid.length; final int n = grid[0].length; TreeSet<Integer> sums = new TreeSet<>(); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) for (int sz = 0; i + sz < m && i - sz >= 0 && j + 2 * sz < n; ++sz) { final int sum = sz == 0 ? grid[i][j] : getSum(grid, i, j, sz); sums.add(sum); if (sums.size() > 3) sums.pollFirst(); } return sums.descendingSet().stream().mapToInt(Integer::intValue).toArray(); } // Returns the sum of the rhombus, where the top grid is (i, j) and the edge // size is `sz`. private int getSum(int[][] grid, int i, int j, int sz) { int x = i; int y = j; int sum = 0; // Go left down. for (int k = 0; k < sz; ++k) sum += grid[--x][++y]; // Go right down. for (int k = 0; k < sz; ++k) sum += grid[++x][++y]; // Go right up. for (int k = 0; k < sz; ++k) sum += grid[++x][--y]; // Go left up. for (int k = 0; k < sz; ++k) sum += grid[--x][--y]; return sum; } }
class Solution { public: vector<int> getBiggestThree(vector<vector<int>>& grid) { const int m = grid.size(); const int n = grid[0].size(); set<int> sums; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) for (int sz = 0; i + sz < m && i - sz >= 0 && j + 2 * sz < n; ++sz) { const int sum = sz == 0 ? grid[i][j] : getSum(grid, i, j, sz); sums.insert(sum); if (sums.size() > 3) sums.erase(sums.begin()); } return vector<int>(sums.rbegin(), sums.rend()); } private: // Returns the sum of the rhombus, where the top grid is (i, j) and the edge // size is `sz`. int getSum(const vector<vector<int>>& grid, int i, int j, int sz) { int x = i; int y = j; int sum = 0; // Go left down. for (int k = 0; k < sz; ++k) sum += grid[--x][++y]; // Go right down. for (int k = 0; k < sz; ++k) sum += grid[++x][++y]; // Go right up. for (int k = 0; k < sz; ++k) sum += grid[++x][--y]; // Go left up. for (int k = 0; k < sz; ++k) sum += grid[--x][--y]; return sum; } };
1,896
Minimum Cost to Change the Final Value of Expression
3
minOperationsToFlip
You are given a valid boolean expression as a string `expression` consisting of the characters `'1'`,`'0'`,`'&'` (bitwise AND operator),`'|'` (bitwise OR operator),`'('`, and `')'`. * For example, `"()1|1"` and `"(1)&()"` are not valid while `"1"`, `"(((1))|(0))"`, and `"1|(0&(1))"` are valid expressions. Return the minimum cost to change the final value of the expression. * For example, if `expression = "1|1|(0&0)&1"`, its value is `1|1|(0&0)&1 = 1|1|0&1 = 1|0&1 = 1&1 = 1`. We want to apply operations so that the new expression evaluates to `0`. The cost of changing the final value of an expression is the number of operations performed on the expression. The types of operations are described as follows: * Turn a `'1'` into a `'0'`. * Turn a `'0'` into a `'1'`. * Turn a `'&'` into a `'|'`. * Turn a `'|'` into a `'&'`. Note: `'&'` does not take precedence over `'|'` in the order of calculation. Evaluate parentheses first, then in left-to-right order.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minOperationsToFlip(self, expression: str) -> int: stack = [] for e in expression: if e in '(&|': stack.append((e, 0)) continue if e == ')': lastPair = stack.pop() stack.pop() else: lastPair = (e, 1) if stack and stack[-1][0] in '&|': op = stack.pop()[0] a, costA = stack.pop() b, costB = lastPair if op == '&': if a == '0' and b == '0': lastPair = ('0', 1 + min(costA, costB)) elif a == '0' and b == '1': lastPair = ('0', 1) elif a == '1' and b == '0': lastPair = ('0', 1) else: lastPair = ('1', min(costA, costB)) else: if a == '0' and b == '0': lastPair = ('0', min(costA, costB)) elif a == '0' and b == '1': lastPair = ('1', 1) elif a == '1' and b == '0': lastPair = ('1', 1) else: lastPair = ('1', 1 + min(costA, costB)) stack.append(lastPair) return stack[-1][1]
class Solution { public int minOperationsToFlip(String expression) { // [(the expression, the cost to toggle the expression)] Deque<Pair<Character, Integer>> stack = new ArrayDeque<>(); Pair<Character, Integer> lastPair = null; for (final char e : expression.toCharArray()) { if (e == '(' || e == '&' || e == '|') { // These aren't expressions, so the cost is meaningless. stack.push(new Pair<>(e, 0)); continue; } if (e == ')') { lastPair = stack.pop(); stack.pop(); // Pop '('. } else { // e == '0' || e == '1' // Store the '0' or '1'. The cost to change their values is just 1, // whether it's changing '0' to '1' or '1' to '0'. lastPair = new Pair<>(e, 1); } if (!stack.isEmpty() && (stack.peek().getKey() == '&' || stack.peek().getKey() == '|')) { final char op = stack.pop().getKey(); final char a = stack.peek().getKey(); final int costA = stack.pop().getValue(); final char b = lastPair.getKey(); final int costB = lastPair.getValue(); // Determine the cost to toggle op(a, b). if (op == '&') { if (a == '0' && b == '0') // Change '&' to '|' and a|b to '1'. lastPair = new Pair<>('0', 1 + Math.min(costA, costB)); else if (a == '0' && b == '1') // Change '&' to '|'. lastPair = new Pair<>('0', 1); else if (a == '1' && b == '0') // Change '&' to '|'. lastPair = new Pair<>('0', 1); else // a == '1' and b == '1' // Change a|b to '0'. lastPair = new Pair<>('1', Math.min(costA, costB)); } else { // op == '|' if (a == '0' && b == '0') // Change a|b to '1'. lastPair = new Pair<>('0', Math.min(costA, costB)); else if (a == '0' && b == '1') // Change '|' to '&'. lastPair = new Pair<>('1', 1); else if (a == '1' && b == '0') // Change '|' to '&'. lastPair = new Pair<>('1', 1); else // a == '1' and b == '1' // Change '|' to '&' and a|b to '0'. lastPair = new Pair<>('1', 1 + Math.min(costA, costB)); } } stack.push(lastPair); } return stack.peek().getValue(); } }
class Solution { public: int minOperationsToFlip(string expression) { // [(the expression, the cost to toggle the expression)] stack<pair<char, int>> stack; pair<char, int> lastPair; for (const char e : expression) { if (e == '(' || e == '&' || e == '|') { // These aren't expressions, so the cost is meaningless. stack.push({e, 0}); continue; } if (e == ')') { lastPair = stack.top(); stack.pop(); stack.pop(); // Pop '('. } else { // e == '0' || e == '1' // Store the '0' or '1'. The cost to change their values is just 1, // whether it's changing '0' to '1' or '1' to '0'. lastPair = {e, 1}; } if (!stack.empty() && (stack.top().first == '&' || stack.top().first == '|')) { const char op = stack.top().first; stack.pop(); const auto [a, costA] = stack.top(); stack.pop(); const auto [b, costB] = lastPair; // Determine the cost to toggle op(a, b). if (op == '&') { if (a == '0' && b == '0') // Change '&' to '|' and a|b to '1'. lastPair = {'0', 1 + min(costA, costB)}; else if (a == '0' && b == '1') // Change '&' to '|'. lastPair = {'0', 1}; else if (a == '1' && b == '0') // Change '&' to '|'. lastPair = {'0', 1}; else // a == '1' and b == '1' // Change a|b to '0'. lastPair = {'1', min(costA, costB)}; } else { // op == '|' if (a == '0' && b == '0') // Change a|b to '1'. lastPair = {'0', min(costA, costB)}; else if (a == '0' && b == '1') // Change '|' to '&'. lastPair = {'1', 1}; else if (a == '1' && b == '0') // Change '|' to '&'. lastPair = {'1', 1}; else // a == '1' and b == '1' // Change '|' to '&' and a|b to '0'. lastPair = {'1', 1 + min(costA, costB)}; } } stack.push(lastPair); } return stack.top().second; } };
1,906
Minimum Absolute Difference Queries
2
minDifference
The minimum absolute difference of an array `a` is defined as the minimum value of `|a[i] - a[j]|`, where `0 <= i < j < a.length` and `a[i] != a[j]`. If all elements of `a` are the same, the minimum absolute difference is `-1`. * For example, the minimum absolute difference of the array `[5,2,3,7,2]` is `|2 - 3| = 1`. Note that it is not `0` because `a[i]` and `a[j]` must be different. You are given an integer array `nums` and the array `queries` where `queries[i] = [li, ri]`. For each query `i`, compute the minimum absolute difference of the subarray `nums[li...ri]` containing the elements of `nums` between the 0-based indices `li` and `ri` (inclusive). Return an array `ans` where `ans[i]` is the answer to the `ith` query. A subarray is a contiguous sequence of elements in an array. The value of `|x|` is defined as: * `x` if `x >= 0`. * `-x` if `x < 0`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from bisect import bisect_left from typing import List, Dict, Tuple, Iterator class Solution: def minDifference(self, nums: List[int], queries: List[List[int]]) -> List[int]: numToIndices = [[] for _ in range(101)] for i, num in enumerate(nums): numToIndices[num].append(i) if len(numToIndices[nums[0]]) == len(nums): return [-1] * len(queries) ans = [] for l, r in queries: prevNum = -1 minDiff = 101 for num in range(1, 101): indices = numToIndices[num] i = bisect_left(indices, l) if i == len(indices) or indices[i] > r: continue if prevNum != -1: minDiff = min(minDiff, num - prevNum) prevNum = num ans.append(-1 if minDiff == 101 else minDiff) return ans
class Solution { public int[] minDifference(int[] nums, int[][] queries) { int[] ans = new int[queries.length]; List<Integer>[] numToIndices = new List[101]; for (int i = 1; i <= 100; ++i) numToIndices[i] = new ArrayList<>(); for (int i = 0; i < nums.length; ++i) numToIndices[nums[i]].add(i); if (numToIndices[nums[0]].size() == nums.length) { Arrays.fill(ans, -1); return ans; } for (int i = 0; i < queries.length; ++i) { final int l = queries[i][0]; final int r = queries[i][1]; int prevNum = -1; int minDiff = 101; for (int num = 1; num <= 100; ++num) { List<Integer> indices = numToIndices[num]; final int j = firstGreaterEqual(indices, l); if (j == indices.size() || indices.get(j) > r) continue; if (prevNum != -1) minDiff = Math.min(minDiff, num - prevNum); prevNum = num; } ans[i] = minDiff == 101 ? -1 : minDiff; } return ans; } private int firstGreaterEqual(List<Integer> A, int target) { final int i = Collections.binarySearch(A, target); return i < 0 ? -i - 1 : i; } }
class Solution { public: vector<int> minDifference(vector<int>& nums, vector<vector<int>>& queries) { vector<vector<int>> numToIndices(101); for (int i = 0; i < nums.size(); ++i) numToIndices[nums[i]].push_back(i); if (numToIndices[nums[0]].size() == nums.size()) return vector<int>(queries.size(), -1); vector<int> ans; for (const vector<int>& query : queries) { const int l = query[0]; const int r = query[1]; int prevNum = -1; int minDiff = 101; for (int num = 1; num <= 100; ++num) { const auto& indices = numToIndices[num]; const auto it = ranges::lower_bound(indices, l); if (it == indices.cend() || *it > r) continue; if (prevNum != -1) minDiff = min(minDiff, num - prevNum); prevNum = num; } ans.push_back(minDiff == 101 ? -1 : minDiff); } return ans; } };
1,923
Longest Common Subpath
3
longestCommonSubpath
There is a country of `n` cities numbered from `0` to `n - 1`. In this country, there is a road connecting every pair of cities. There are `m` friends numbered from `0` to `m - 1` who are traveling through the country. Each one of them will take a path consisting of some cities. Each path is represented by an integer array that contains the visited cities in order. The path may contain a city more than once, but the same city will not be listed consecutively. Given an integer `n` and a 2D integer array `paths` where `paths[i]` is an integer array representing the path of the `ith` friend, return the length of the longest common subpath that is shared by every friend's path, or `0` if there is no common subpath at all. A subpath of a path is a contiguous sequence of cities within that path.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator, Set class Solution: def __init__(self): self.kMod = 8_417_508_174_513 self.kBase = 165_131 def longestCommonSubpath(self, n: int, paths: List[List[int]]) -> int: l = 0 r = len(paths[0]) while l < r: m = l + (r - l + 1) // 2 if self._checkCommonSubpath(paths, m): l = m else: r = m - 1 return l def _checkCommonSubpath(self, paths: List[List[int]], m: int) -> bool: hashSets = [self._rabinKarp(path, m) for path in paths] for subpathHash in hashSets[0]: if all(subpathHash in hashSet for hashSet in hashSets): return True return False def _rabinKarp(self, path: List[int], m: int) -> Set[int]: hashes = set() maxPower = 1 hash = 0 for i, num in enumerate(path): hash = (hash * self.kBase + num) % self.kMod if i >= m: hash = (hash - path[i - m] * maxPower % self.kMod + self.kMod) % self.kMod else: maxPower = maxPower * self.kBase % self.kMod if i >= m - 1: hashes.add(hash) return hashes
class Solution { public int longestCommonSubpath(int n, int[][] paths) { int l = 0; int r = paths[0].length; while (l < r) { final int m = l + (r - l + 1) / 2; if (checkCommonSubpath(paths, m)) l = m; else r = m - 1; } return l; } private static final long BASE = 165_131L; private static final long HASH = 8_417_508_174_513L; // Returns true if there's a common subpath of length m for all the paths. private boolean checkCommonSubpath(int[][] paths, int m) { Set<Long>[] hashSets = new Set[paths.length]; // Calculate the hash values for subpaths of length m for every path. for (int i = 0; i < paths.length; ++i) hashSets[i] = rabinKarp(paths[i], m); // Check if there is a common subpath of length m. for (final long subpathHash : hashSets[0]) if (Arrays.stream(hashSets).allMatch(hashSet -> hashSet.contains(subpathHash))) return true; return false; } // Returns the hash values for subpaths of length m in the path. private Set<Long> rabinKarp(int[] path, int m) { Set<Long> hashes = new HashSet<>(); long maxPower = 1; long hash = 0; for (int i = 0; i < path.length; ++i) { hash = (hash * BASE + path[i]) % HASH; if (i >= m) hash = (hash - path[i - m] * maxPower % HASH + HASH) % HASH; else maxPower = maxPower * BASE % HASH; if (i >= m - 1) hashes.add(hash); } return hashes; } }
class Solution { public: int longestCommonSubpath(int n, vector<vector<int>>& paths) { int l = 0; int r = paths[0].size(); while (l < r) { const int m = l + (r - l + 1) / 2; if (checkCommonSubpath(paths, m)) l = m; else r = m - 1; } return l; } static constexpr long kBase = 165'131; static constexpr long kHash = 8'417'508'174'513; // Returns true if there's a common subpath of length m for all the paths. bool checkCommonSubpath(const vector<vector<int>>& paths, int m) { vector<unordered_set<long>> hashSets; // Calculate the hash values for subpaths of length m for every path. for (const vector<int>& path : paths) hashSets.push_back(rabinKarp(path, m)); // Check if there is a common subpath of length m. for (const long subpathHash : hashSets[0]) if (ranges::all_of(hashSets, [subpathHash](const unordered_set<long>& hashSet) { return hashSet.contains(subpathHash); })) return true; return false; } // Returns the hash values for subpaths of length m in the path. unordered_set<long> rabinKarp(const vector<int>& path, int m) { unordered_set<long> hashes; long maxPower = 1; long hash = 0; for (int i = 0; i < path.size(); ++i) { hash = (hash * kBase + path[i]) % kHash; if (i >= m) hash = (hash - path[i - m] * maxPower % kHash + kHash) % kHash; else maxPower = maxPower * kBase % kHash; if (i >= m - 1) hashes.insert(hash); } return hashes; } };
1,926
Nearest Exit from Entrance in Maze
2
nearestExit
You are given an `m x n` matrix `maze` (0-indexed) with empty cells (represented as `'.'`) and walls (represented as `'+'`). You are also given the `entrance` of the maze, where `entrance = [entrancerow, entrancecol]` denotes the row and column of the cell you are initially standing at. In one step, you can move one cell up, down, left, or right. You cannot step into a cell with a wall, and you cannot step outside the maze. Your goal is to find the nearest exit from the `entrance`. An exit is defined as an empty cell that is at the border of the `maze`. The `entrance` does not count as an exit. Return the number of steps in the shortest path from the `entrance` to the nearest exit, or `-1` if no such path exists.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) m = len(maze) n = len(maze[0]) ans = 0 q = collections.deque([(entrance[0], entrance[1])]) seen = {(entrance[0], entrance[1])} while q: ans += 1 for _ in range(len(q)): i, j = q.popleft() for dx, dy in dirs: x = i + dx y = j + dy if x < 0 or x == m or y < 0 or y == n: continue if (x, y) in seen or maze[x][y] == '+': continue if x == 0 or x == m - 1 or y == 0 or y == n - 1: return ans q.append((x, y)) seen.add((x, y)) return -1
class Solution { public int nearestExit(char[][] maze, int[] entrance) { final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; final int m = maze.length; final int n = maze[0].length; Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(entrance[0], entrance[1]))); boolean[][] seen = new boolean[m][n]; seen[entrance[0]][entrance[1]] = true; for (int step = 1; !q.isEmpty(); ++step) for (int sz = q.size(); sz > 0; --sz) { final int i = q.peek().getKey(); final int j = q.poll().getValue(); for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == m || y < 0 || y == n) continue; if (seen[x][y] || maze[x][y] == '+') continue; if (x == 0 || x == m - 1 || y == 0 || y == n - 1) return step; q.offer(new Pair<>(x, y)); seen[x][y] = true; } } return -1; } }
class Solution { public: int nearestExit(vector<vector<char>>& maze, vector<int>& entrance) { constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; const int m = maze.size(); const int n = maze[0].size(); queue<pair<int, int>> q{{{entrance[0], entrance[1]}}}; vector<vector<bool>> seen(m, vector<bool>(n)); seen[entrance[0]][entrance[1]] = true; for (int step = 1; !q.empty(); ++step) for (int sz = q.size(); sz > 0; --sz) { const auto [i, j] = q.front(); q.pop(); for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == m || y < 0 || y == n) continue; if (seen[x][y] || maze[x][y] == '+') continue; if (x == 0 || x == m - 1 || y == 0 || y == n - 1) return step; q.emplace(x, y); seen[x][y] = true; } } return -1; } };
1,928
Minimum Cost to Reach Destination in Time
3
minCost
There is a country of `n` cities numbered from `0` to `n - 1` where all the cities are connected by bi-directional roads. The roads are represented as a 2D integer array `edges` where `edges[i] = [xi, yi, timei]` denotes a road between cities `xi` and `yi` that takes `timei` minutes to travel. There may be multiple roads of differing travel times connecting the same two cities, but no road connects a city to itself. Each time you pass through a city, you must pay a passing fee. This is represented as a 0-indexed integer array `passingFees` of length `n` where `passingFees[j]` is the amount of dollars you must pay when you pass through city `j`. In the beginning, you are at city `0` and want to reach city `n - 1` in `maxTime` minutes or less. The cost of your journey is the summation of passing fees for each city that you passed through at some moment of your journey (including the source and destination cities). Given `maxTime`, `edges`, and `passingFees`, return the minimum cost to complete your journey, or `-1` if you cannot complete it within `maxTime` minutes.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minCost(self, maxTime: int, edges: List[List[int]], passingFees: List[int]) -> int: n = len(passingFees) graph = [[] for _ in range(n)] for u, v, w in edges: graph[u].append((v, w)) graph[v].append((u, w)) return self._dijkstra(graph, 0, n - 1, maxTime, passingFees) def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, dst: int, maxTime: int, passingFees: List[int]) -> int: cost = [math.inf for _ in range(len(graph))] dist = [maxTime + 1 for _ in range(len(graph))] cost[src] = passingFees[src] dist[src] = 0 minHeap = [(cost[src], dist[src], src)] while minHeap: currCost, d, u = heapq.heappop(minHeap) if u == dst: return cost[dst] if d > dist[u] and currCost > cost[u]: continue for v, w in graph[u]: if d + w > maxTime: continue if currCost + passingFees[v] < cost[v]: cost[v] = currCost + passingFees[v] dist[v] = d + w heapq.heappush(minHeap, (cost[v], dist[v], v)) elif d + w < dist[v]: dist[v] = d + w heapq.heappush(minHeap, (currCost + passingFees[v], dist[v], v)) return -1
class Solution { public int minCost(int maxTime, int[][] edges, int[] passingFees) { final int n = passingFees.length; List<Pair<Integer, Integer>>[] graph = new List[n]; Arrays.setAll(graph, i -> new ArrayList<>()); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; final int t = edge[2]; graph[u].add(new Pair<>(v, t)); graph[v].add(new Pair<>(u, t)); } return dijkstra(graph, 0, n - 1, maxTime, passingFees); } private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst, int maxTime, int[] passingFees) { int[] cost = new int[graph.length]; // cost[i] := the minimum cost to reach the i-th city int[] dist = new int[graph.length]; // dist[i] := the minimum distance to reach the i-th city Arrays.fill(cost, Integer.MAX_VALUE); Arrays.fill(dist, maxTime + 1); cost[0] = passingFees[0]; dist[0] = 0; Queue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])) { { offer(new int[] {cost[src], dist[src], src}); } // (cost[u], dist[u], u) }; while (!minHeap.isEmpty()) { final int currCost = minHeap.peek()[0]; final int d = minHeap.peek()[1]; final int u = minHeap.poll()[2]; if (u == dst) return cost[dst]; if (d > dist[u] && currCost > cost[u]) continue; for (Pair<Integer, Integer> pair : graph[u]) { final int v = pair.getKey(); final int w = pair.getValue(); if (d + w > maxTime) continue; // Go from x -> y if (currCost + passingFees[v] < cost[v]) { cost[v] = currCost + passingFees[v]; dist[v] = d + w; minHeap.offer(new int[] {cost[v], dist[v], v}); } else if (d + w < dist[v]) { dist[v] = d + w; minHeap.offer(new int[] {currCost + passingFees[v], dist[v], v}); } } } return -1; } }
class Solution { public: int minCost(int maxTime, vector<vector<int>>& edges, vector<int>& passingFees) { const int n = passingFees.size(); vector<vector<pair<int, int>>> graph(n); for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; const int w = edge[2]; graph[u].emplace_back(v, w); graph[v].emplace_back(u, w); } return dijkstra(graph, 0, n - 1, maxTime, passingFees); } private: int dijkstra(const vector<vector<pair<int, int>>>& graph, int src, int dst, int maxTime, const vector<int>& passingFees) { // cost[i] := the minimum cost to reach the i-th city vector<int> cost(graph.size(), INT_MAX); // dist[i] := the minimum time to reach the i-th city vector<int> dist(graph.size(), maxTime + 1); cost[src] = passingFees[src]; dist[src] = 0; using T = tuple<int, int, int>; // (cost[u], dist[u], u) priority_queue<T, vector<T>, greater<>> minHeap; minHeap.emplace(cost[src], dist[src], src); while (!minHeap.empty()) { const auto [currCost, d, u] = minHeap.top(); minHeap.pop(); if (u == dst) return cost[dst]; if (d > dist[u] && currCost > cost[u]) continue; for (const auto& [v, w] : graph[u]) { if (d + w > maxTime) continue; // Go from u -> v. if (currCost + passingFees[v] < cost[v]) { cost[v] = currCost + passingFees[v]; dist[v] = d + w; minHeap.emplace(cost[v], dist[v], v); } else if (d + w < dist[v]) { dist[v] = d + w; minHeap.emplace(currCost + passingFees[v], dist[v], v); } } } return -1; } };
1,938
Maximum Genetic Difference Query
3
maxGeneticDifference
There is a rooted tree consisting of `n` nodes numbered `0` to `n - 1`. Each node's number denotes its unique genetic value (i.e. the genetic value of node `x` is `x`). The genetic difference between two genetic values is defined as the bitwise-XOR of their values. You are given the integer array `parents`, where `parents[i]` is the parent for node `i`. If node `x` is the root of the tree, then `parents[x] == -1`. You are also given the array `queries` where `queries[i] = [nodei, vali]`. For each query `i`, find the maximum genetic difference between `vali` and `pi`, where `pi` is the genetic value of any node that is on the path between `nodei` and the root (including `nodei` and the root). More formally, you want to maximize `vali XOR pi`. Return an array `ans` where `ans[i]` is the answer to the `ith` query.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class TrieNode: def __init__(self): self.children = [None] * 2 self.count = 0 class Trie: def __init__(self): self.root = TrieNode() self.kHeight = 17 def update(self, num: int, val: int) -> None: node = self.root for i in range(self.kHeight, -1, -1): bit = (num >> i) & 1 if not node.children[bit]: node.children[bit] = TrieNode() node = node.children[bit] node.count += val def query(self, num: int) -> int: ans = 0 node = self.root for i in range(self.kHeight, -1, -1): bit = (num >> i) & 1 targetBit = bit ^ 1 if node.children[targetBit] and node.children[targetBit].count > 0: ans += 1 << i node = node.children[targetBit] else: node = node.children[targetBit ^ 1] return ans class Solution: def maxGeneticDifference(self, parents: List[int], queries: List[List[int]]) -> List[int]: n = len(parents) ans = [0] * len(queries) rootVal = -1 tree = [[] for _ in range(n)] nodeToQueries = collections.defaultdict(list) trie = Trie() for i, parent in enumerate(parents): if parent == -1: rootVal = i else: tree[parent].append(i) for i, (node, val) in enumerate(queries): nodeToQueries[node].append((i, val)) def dfs(node: int) -> None: trie.update(node, 1) for i, val in nodeToQueries[node]: ans[i] = trie.query(val) for child in tree[node]: dfs(child) trie.update(node, -1) dfs(rootVal) return ans
class TrieNode { public TrieNode[] children = new TrieNode[2]; public int count = 0; } class Trie { public void update(int num, int val) { TrieNode node = root; for (int i = HEIGHT; i >= 0; --i) { final int bit = (num >> i) & 1; if (node.children[bit] == null) node.children[bit] = new TrieNode(); node = node.children[bit]; node.count += val; } } public int query(int num) { int ans = 0; TrieNode node = root; for (int i = HEIGHT; i >= 0; --i) { final int bit = (num >> i) & 1; final int targetBit = bit ^ 1; if (node.children[targetBit] != null && node.children[targetBit].count > 0) { ans += 1 << i; node = node.children[targetBit]; } else { node = node.children[targetBit ^ 1]; } } return ans; } private static final int HEIGHT = 17; TrieNode root = new TrieNode(); } class Solution { public int[] maxGeneticDifference(int[] parents, int[][] queries) { final int n = parents.length; int[] ans = new int[queries.length]; int rootVal = -1; List<Integer>[] tree = new List[n]; for (int i = 0; i < n; ++i) tree[i] = new ArrayList<>(); // {node: (index, val)} Map<Integer, List<Pair<Integer, Integer>>> nodeToQueries = new HashMap<>(); Trie trie = new Trie(); for (int i = 0; i < parents.length; ++i) if (parents[i] == -1) rootVal = i; else tree[parents[i]].add(i); for (int i = 0; i < queries.length; ++i) { final int node = queries[i][0]; final int val = queries[i][1]; nodeToQueries.putIfAbsent(node, new ArrayList<>()); nodeToQueries.get(node).add(new Pair<>(i, val)); } dfs(rootVal, trie, tree, nodeToQueries, ans); return ans; } private void dfs(int node, Trie trie, List<Integer>[] tree, Map<Integer, List<Pair<Integer, Integer>>> nodeToQueries, int[] ans) { trie.update(node, 1); if (nodeToQueries.containsKey(node)) for (Pair<Integer, Integer> query : nodeToQueries.get(node)) { final int i = query.getKey(); final int val = query.getValue(); ans[i] = trie.query(val); } for (final int child : tree[node]) dfs(child, trie, tree, nodeToQueries, ans); trie.update(node, -1); } }
struct TrieNode { vector<shared_ptr<TrieNode>> children; int count = 0; TrieNode() : children(2) {} }; class Trie { public: void update(int num, int val) { shared_ptr<TrieNode> node = root; for (int i = kHeight; i >= 0; --i) { const int bit = (num >> i) & 1; if (node->children[bit] == nullptr) node->children[bit] = make_shared<TrieNode>(); node = node->children[bit]; node->count += val; } } int query(int num) { int ans = 0; shared_ptr<TrieNode> node = root; for (int i = kHeight; i >= 0; --i) { const int bit = (num >> i) & 1; const int targetBit = bit ^ 1; if (node->children[targetBit] && node->children[targetBit]->count) { ans += 1 << i; node = node->children[targetBit]; } else { node = node->children[targetBit ^ 1]; } } return ans; } private: static constexpr int kHeight = 17; shared_ptr<TrieNode> root = make_shared<TrieNode>(); }; class Solution { public: vector<int> maxGeneticDifference(vector<int>& parents, vector<vector<int>>& queries) { const int n = parents.size(); vector<int> ans(queries.size()); int rootVal = -1; vector<vector<int>> tree(n); // {node: (index, val)} unordered_map<int, vector<pair<int, int>>> nodeToQueries; Trie trie; for (int i = 0; i < parents.size(); ++i) if (parents[i] == -1) rootVal = i; else tree[parents[i]].push_back(i); for (int i = 0; i < queries.size(); ++i) { const int node = queries[i][0]; const int val = queries[i][1]; nodeToQueries[node].emplace_back(i, val); } dfs(rootVal, trie, tree, nodeToQueries, ans); return ans; } private: void dfs(int node, Trie& trie, const vector<vector<int>>& tree, const unordered_map<int, vector<pair<int, int>>>& nodeToQueries, vector<int>& ans) { trie.update(node, 1); if (const auto it = nodeToQueries.find(node); it != nodeToQueries.cend()) for (const auto& [i, val] : it->second) ans[i] = trie.query(val); for (const int child : tree[node]) dfs(child, trie, tree, nodeToQueries, ans); trie.update(node, -1); } };
1,971
Find if Path Exists in Graph
1
validPath
There is a bi-directional graph with `n` vertices, where each vertex is labeled from `0` to `n - 1` (inclusive). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. You want to determine if there is a valid path that exists from vertex `source` to vertex `destination`. Given `edges` and the integers `n`, `source`, and `destination`, return `true` if there is a valid path from `source` to `destination`, or `false` otherwise.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class UnionFind: def __init__(self, n: int): self.id = list(range(n)) self.rank = [0] * n def unionByRank(self, u: int, v: int) -> None: i = self.find(u) j = self.find(v) if i == j: return if self.rank[i] < self.rank[j]: self.id[i] = j elif self.rank[i] > self.rank[j]: self.id[j] = i else: self.id[i] = j self.rank[j] += 1 def find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self.find(self.id[u]) return self.id[u] class Solution: def validPath(self, n: int, edges: List[List[int]], source: int, destination: int) -> bool: uf = UnionFind(n) for u, v in edges: uf.unionByRank(u, v) return uf.find(source) == uf.find(destination)
class UnionFind { public UnionFind(int n) { id = new int[n]; rank = new int[n]; for (int i = 0; i < n; ++i) id[i] = i; } public void unionByRank(int u, int v) { final int i = find(u); final int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } public int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } private int[] id; private int[] rank; } class Solution { public boolean validPath(int n, int[][] edges, int source, int destination) { UnionFind uf = new UnionFind(n); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; uf.unionByRank(u, v); } return uf.find(source) == uf.find(destination); } }
class UnionFind { public: UnionFind(int n) : id(n), rank(n) { iota(id.begin(), id.end(), 0); } void unionByRank(int u, int v) { const int i = find(u); const int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } private: vector<int> id; vector<int> rank; }; class Solution { public: bool validPath(int n, vector<vector<int>>& edges, int source, int destination) { UnionFind uf(n); for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; uf.unionByRank(u, v); } return uf.find(source) == uf.find(destination); } };
1,976
Number of Ways to Arrive at Destination
2
countPaths
You are in a city that consists of `n` intersections numbered from `0` to `n - 1` with bi-directional roads between some intersections. The inputs are generated such that you can reach any intersection from any other intersection and that there is at most one road between any two intersections. You are given an integer `n` and a 2D integer array `roads` where `roads[i] = [ui, vi, timei]` means that there is a road between intersections `ui` and `vi` that takes `timei` minutes to travel. You want to know in how many ways you can travel from intersection `0` to intersection `n - 1` in the shortest amount of time. Return the number of ways you can arrive at your destination in the shortest amount of time. Since the answer may be large, return it modulo `109 + 7`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def countPaths(self, n: int, roads: List[List[int]]) -> int: graph = [[] for _ in range(n)] for u, v, w in roads: graph[u].append((v, w)) graph[v].append((u, w)) return self._dijkstra(graph, 0, n - 1) def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, dst: int) -> int: kMod = 10**9 + 7 ways = [0] * len(graph) dist = [math.inf] * len(graph) ways[src] = 1 dist[src] = 0 minHeap = [(dist[src], src)] while minHeap: d, u = heapq.heappop(minHeap) if d > dist[u]: continue for v, w in graph[u]: if d + w < dist[v]: dist[v] = d + w ways[v] = ways[u] heapq.heappush(minHeap, (dist[v], v)) elif d + w == dist[v]: ways[v] += ways[u] ways[v] %= kMod return ways[dst]
class Solution { public int countPaths(int n, int[][] roads) { List<Pair<Integer, Integer>>[] graph = new List[n]; for (int i = 0; i < n; i++) graph[i] = new ArrayList<>(); for (int[] road : roads) { final int u = road[0]; final int v = road[1]; final int w = road[2]; graph[u].add(new Pair<>(v, w)); graph[v].add(new Pair<>(u, w)); } return dijkstra(graph, 0, n - 1); } private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst) { final int MOD = 1_000_000_007; long[] ways = new long[graph.length]; Arrays.fill(ways, 0); long[] dist = new long[graph.length]; Arrays.fill(dist, Long.MAX_VALUE); ways[src] = 1; dist[src] = 0; Queue<Pair<Long, Integer>> minHeap = new PriorityQueue<>(Comparator.comparingLong(Pair::getKey)) { { offer(new Pair<>(dist[src], src)); } }; while (!minHeap.isEmpty()) { final long d = minHeap.peek().getKey(); final int u = minHeap.poll().getValue(); if (d > dist[u]) continue; for (Pair<Integer, Integer> pair : graph[u]) { final int v = pair.getKey(); final int w = pair.getValue(); if (d + w < dist[v]) { dist[v] = d + w; ways[v] = ways[u]; minHeap.offer(new Pair<>(dist[v], v)); } else if (d + w == dist[v]) { ways[v] += ways[u]; ways[v] %= MOD; } } } return (int) ways[dst]; } }
class Solution { public: int countPaths(int n, vector<vector<int>>& roads) { vector<vector<pair<int, int>>> graph(n); for (const vector<int>& road : roads) { const int u = road[0]; const int v = road[1]; const int w = road[2]; graph[u].emplace_back(v, w); graph[v].emplace_back(u, w); } return dijkstra(graph, 0, n - 1); } private: // Similar to 1786. Number of Restricted Paths From First to Last Node int dijkstra(const vector<vector<pair<int, int>>>& graph, int src, int dst) { constexpr int kMod = 1'000'000'007; vector<long> ways(graph.size()); vector<long> dist(graph.size(), LONG_MAX); ways[src] = 1; dist[src] = 0; using P = pair<long, int>; // (d, u) priority_queue<P, vector<P>, greater<>> minHeap; minHeap.emplace(dist[src], src); while (!minHeap.empty()) { const auto [d, u] = minHeap.top(); minHeap.pop(); if (d > dist[u]) continue; for (const auto& [v, w] : graph[u]) if (d + w < dist[v]) { dist[v] = d + w; ways[v] = ways[u]; minHeap.emplace(dist[v], v); } else if (d + w == dist[v]) { ways[v] += ways[u]; ways[v] %= kMod; } } return ways[dst]; } };
1,977
Number of Ways to Separate Numbers
3
numberOfCombinations
You wrote down many positive integers in a string called `num`. However, you realized that you forgot to add commas to seperate the different numbers. You remember that the list of integers was non-decreasing and that no integer had leading zeros. Return the number of possible lists of integers that you could have written down to get the string `num`. Since the answer may be large, return it modulo `109 + 7`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def numberOfCombinations(self, num: str) -> int: if num[0] == '0': return 0 kMod = 1_000_000_007 n = len(num) dp = [[0] * (n + 1) for _ in range(n)] lcs = [[0] * (n + 1) for _ in range(n + 1)] for i in range(n - 1, -1, -1): for j in range(i + 1, n): if num[i] == num[j]: lcs[i][j] = lcs[i + 1][j + 1] + 1 for i in range(n): for k in range(1, i + 2): dp[i][k] += dp[i][k - 1] dp[i][k] %= kMod s = i - k + 1 if num[s] == '0': continue if s == 0: dp[i][k] += 1 continue if s < k: dp[i][k] += dp[s - 1][s] continue l = lcs[s - k][s] if l >= k or num[s - k + l] <= num[s + l]: dp[i][k] += dp[s - 1][k] else: dp[i][k] += dp[s - 1][k - 1] return dp[n - 1][n] % kMod
class Solution { public int numberOfCombinations(String num) { if (num.charAt(0) == '0') return 0; final int MOD = 1_000_000_007; final int n = num.length(); // dp[i][k] := the number of possible lists of integers ending in num[i] with // the length of the last number being 1..k long[][] dp = new long[n][n + 1]; // lcs[i][j] := the number of the same digits in num[i..n) and num[j..n) int[][] lcs = new int[n + 1][n + 1]; for (int i = n - 1; i >= 0; --i) for (int j = i + 1; j < n; ++j) if (num.charAt(i) == num.charAt(j)) lcs[i][j] = lcs[i + 1][j + 1] + 1; for (int i = 0; i < n; ++i) for (int k = 1; k <= i + 1; ++k) { dp[i][k] += dp[i][k - 1]; dp[i][k] %= MOD; // The last number is num[s..i]. final int s = i - k + 1; if (num.charAt(s) == '0') // the number of possible lists of integers ending in num[i] with the // length of the last number being k continue; if (s == 0) { // the whole string dp[i][k] += 1; continue; } if (s < k) { // The length k is not enough, so add the number of possible lists of // integers in num[0..s - 1]. dp[i][k] += dp[s - 1][s]; continue; } final int l = lcs[s - k][s]; if (l >= k || num.charAt(s - k + l) <= num.charAt(s + l)) // Have enough length k and num[s - k..s - 1] <= num[j..i]. dp[i][k] += dp[s - 1][k]; else // Have enough length k but num[s - k..s - 1] > num[j..i]. dp[i][k] += dp[s - 1][k - 1]; } return (int) dp[n - 1][n] % MOD; } }
class Solution { public: int numberOfCombinations(string num) { if (num[0] == '0') return 0; constexpr int kMod = 1'000'000'007; const int n = num.size(); // dp[i][k] := the number of possible lists of integers ending in num[i] // with the length of the last number being 1..k vector<vector<long>> dp(n, vector<long>(n + 1)); // lcs[i][j] := the number of the same digits in num[i..n) and num[j..n) vector<vector<int>> lcs(n + 1, vector<int>(n + 1)); for (int i = n - 1; i >= 0; --i) for (int j = i + 1; j < n; ++j) if (num[i] == num[j]) lcs[i][j] = lcs[i + 1][j + 1] + 1; for (int i = 0; i < n; ++i) for (int k = 1; k <= i + 1; ++k) { dp[i][k] += dp[i][k - 1]; dp[i][k] %= kMod; // The last number is num[s..i]. const int s = i - k + 1; if (num[s] == '0') // the number of possible lists of integers ending in num[i] with the // length of the last number being k continue; if (s == 0) { // the whole string dp[i][k] += 1; continue; } if (s < k) { // The length k is not enough, so add the number of possible lists of // integers in num[0..s - 1]. dp[i][k] += dp[s - 1][s]; continue; } const int l = lcs[s - k][s]; if (l >= k || num[s - k + l] <= num[s + l]) // Have enough length k and num[s - k..s - 1] <= num[j..i]. dp[i][k] += dp[s - 1][k]; else // Have enough length k but num[s - k..s - 1] > num[j..i]. dp[i][k] += dp[s - 1][k - 1]; } return dp[n - 1][n] % kMod; } };
1,994
The Number of Good Subsets
3
numberOfGoodSubsets
You are given an integer array `nums`. We call a subset of `nums` good if its product can be represented as a product of one or more distinct prime numbers. * For example, if `nums = [1, 2, 3, 4]`: * `[2, 3]`, `[1, 2, 3]`, and `[1, 3]` are good subsets with products `6 = 2*3`, `6 = 2*3`, and `3 = 3` respectively. * `[1, 4]` and `[4]` are not good subsets with products `4 = 2*2` and `4 = 2*2` respectively. Return the number of different good subsets in `nums` modulo `109 + 7`. A subset of `nums` is any array that can be obtained by deleting some (possibly none or all) elements from `nums`. Two subsets are different if and only if the chosen indices to delete are different.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def numberOfGoodSubsets(self, nums: List[int]) -> int: kMod = 1_000_000_007 primes = [2, 3, 5, 7, 11, 13, 17, 19, 23, 29] n = 1 << len(primes) dp = [1] + [0] * (n - 1) count = collections.Counter(nums) for num, freq in count.items(): if num == 1: continue if any(num % squared == 0 for squared in [4, 9, 25]): continue numPrimesMask = 0 for i, prime in enumerate(primes): if num % prime == 0: numPrimesMask += 1 << i for primesMask in range(n): if primesMask & numPrimesMask > 0: continue nextPrimesMask = numPrimesMask | primesMask dp[nextPrimesMask] += dp[primesMask] * freq dp[nextPrimesMask] %= kMod return (1 << count[1]) * sum(dp[1:]) % kMod
class Solution { public int numberOfGoodSubsets(int[] nums) { final int[] primes = {2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; final int n = 1 << primes.length; final int maxNum = Arrays.stream(nums).max().getAsInt(); long[] dp = new long[n]; int[] count = new int[maxNum + 1]; dp[0] = 1; for (final int num : nums) ++count[num]; for (int num = 2; num <= maxNum; ++num) { if (count[num] == 0) continue; if (num % 4 == 0 || num % 9 == 0 || num % 25 == 0) continue; final int numPrimesMask = getPrimesMask(num, primes); for (int primesMask = 0; primesMask < n; ++primesMask) { if ((primesMask & numPrimesMask) > 0) continue; final int nextPrimesMask = primesMask | numPrimesMask; dp[nextPrimesMask] += dp[primesMask] * count[num]; dp[nextPrimesMask] %= MOD; } } return (int) (modPow(2, count[1]) * ((Arrays.stream(dp).sum() - 1) % MOD) % MOD); } private static final int MOD = 1_000_000_007; private int getPrimesMask(int num, int[] primes) { int primesMask = 0; for (int i = 0; i < primes.length; ++i) if (num % primes[i] == 0) primesMask |= 1 << i; return primesMask; } private long modPow(long x, long n) { if (n == 0) return 1; if (n % 2 == 1) return x * modPow(x, n - 1) % MOD; return modPow(x * x % MOD, n / 2); } }
class Solution { public: int numberOfGoodSubsets(vector<int>& nums) { const vector<int> primes{2, 3, 5, 7, 11, 13, 17, 19, 23, 29}; const int n = 1 << primes.size(); const int maxNum = ranges::max(nums); vector<long> dp(n); vector<int> count(maxNum + 1); dp[0] = 1; for (const int num : nums) ++count[num]; for (int num = 2; num <= maxNum; ++num) { if (count[num] == 0) continue; if (num % 4 == 0 || num % 9 == 0 || num % 25 == 0) continue; const int numPrimesMask = getPrimesMask(num, primes); for (int primesMask = 0; primesMask < n; ++primesMask) { if ((primesMask & numPrimesMask) > 0) continue; const int nextPrimesMask = primesMask | numPrimesMask; dp[nextPrimesMask] += dp[primesMask] * count[num]; dp[nextPrimesMask] %= kMod; } } return modPow(2, count[1]) * (accumulate(dp.begin() + 1, dp.end(), 0L) % kMod) % kMod; } private: static constexpr int kMod = 1'000'000'007; int getPrimesMask(int num, const vector<int>& primes) { int primesMask = 0; for (int i = 0; i < primes.size(); ++i) if (num % primes[i] == 0) primesMask |= 1 << i; return primesMask; } long modPow(long x, long n) { if (n == 0) return 1; if (n % 2 == 1) return x * modPow(x % kMod, (n - 1)) % kMod; return modPow(x * x % kMod, (n / 2)) % kMod; } };
1,998
GCD Sort of an Array
3
gcdSort
You are given an integer array `nums`, and you can perform the following operation any number of times on `nums`: * Swap the positions of two elements `nums[i]` and `nums[j]` if `gcd(nums[i], nums[j]) > 1` where `gcd(nums[i], nums[j])` is the greatest common divisor of `nums[i]` and `nums[j]`. Return `true` if it is possible to sort `nums` in non-decreasing order using the above swap method, or `false` otherwise.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class UnionFind: def __init__(self, n: int): self.id = list(range(n)) self.rank = [0] * n def unionByRank(self, u: int, v: int) -> None: i = self.find(u) j = self.find(v) if i == j: return False if self.rank[i] < self.rank[j]: self.id[i] = j elif self.rank[i] > self.rank[j]: self.id[j] = i else: self.id[i] = j self.rank[j] += 1 return True def find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self.find(self.id[u]) return self.id[u] class Solution: def gcdSort(self, nums: List[int]) -> bool: maxNum = max(nums) minPrimeFactors = self._sieveEratosthenes(maxNum + 1) uf = UnionFind(maxNum + 1) for num in nums: for primeFactor in self._getPrimeFactors(num, minPrimeFactors): uf.unionByRank(num, primeFactor) for a, b in zip(nums, sorted(nums)): if uf.find(a) != uf.find(b): return False return True def _sieveEratosthenes(self, n: int) -> List[int]: minPrimeFactors = [i for i in range(n + 1)] for i in range(2, int(n**0.5) + 1): if minPrimeFactors[i] == i: for j in range(i * i, n, i): minPrimeFactors[j] = min(minPrimeFactors[j], i) return minPrimeFactors def _getPrimeFactors(self, num: int, minPrimeFactors: List[int]) -> List[int]: primeFactors = [] while num > 1: divisor = minPrimeFactors[num] primeFactors.append(divisor) while num % divisor == 0: num //= divisor return primeFactors
class UnionFind { public UnionFind(int n) { id = new int[n]; rank = new int[n]; for (int i = 0; i < n; ++i) id[i] = i; } public void unionByRank(int u, int v) { final int i = find(u); final int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } public int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } private int[] id; private int[] rank; } class Solution { public boolean gcdSort(int[] nums) { final int mx = Arrays.stream(nums).max().getAsInt(); final int[] minPrimeFactors = sieveEratosthenes(mx + 1); UnionFind uf = new UnionFind(mx + 1); for (final int num : nums) for (final int primeFactor : getPrimeFactors(num, minPrimeFactors)) uf.unionByRank(num, primeFactor); int[] sortedNums = nums.clone(); Arrays.sort(sortedNums); for (int i = 0; i < nums.length; ++i) // Can't swap nums[i] with sortedNums[i]. if (uf.find(nums[i]) != uf.find(sortedNums[i])) return false; return true; } // Gets the minimum prime factor of i, where 1 < i <= n. private int[] sieveEratosthenes(int n) { int[] minPrimeFactors = new int[n + 1]; for (int i = 2; i <= n; ++i) minPrimeFactors[i] = i; for (int i = 2; i * i < n; ++i) if (minPrimeFactors[i] == i) // `i` is prime. for (int j = i * i; j < n; j += i) minPrimeFactors[j] = Math.min(minPrimeFactors[j], i); return minPrimeFactors; } private List<Integer> getPrimeFactors(int num, int[] minPrimeFactors) { List<Integer> primeFactors = new ArrayList<>(); while (num > 1) { final int divisor = minPrimeFactors[num]; primeFactors.add(divisor); while (num % divisor == 0) num /= divisor; } return primeFactors; } }
class UnionFind { public: UnionFind(int n) : id(n), rank(n) { iota(id.begin(), id.end(), 0); } void unionByRank(int u, int v) { const int i = find(u); const int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } private: vector<int> id; vector<int> rank; }; class Solution { public: bool gcdSort(vector<int>& nums) { const int mx = ranges::max(nums); const vector<int> minPrimeFactors = sieveEratosthenes(mx + 1); UnionFind uf(mx + 1); for (const int num : nums) for (const int primeFactor : getPrimeFactors(num, minPrimeFactors)) uf.unionByRank(num, primeFactor); vector<int> sortedNums(nums); ranges::sort(sortedNums); for (int i = 0; i < nums.size(); ++i) // Can't swap nums[i] with sortedNums[i]. if (uf.find(nums[i]) != uf.find(sortedNums[i])) return false; return true; } private: // Gets the minimum prime factor of i, where 1 < i <= n. vector<int> sieveEratosthenes(int n) { vector<int> minPrimeFactors(n + 1); iota(minPrimeFactors.begin() + 2, minPrimeFactors.end(), 2); for (int i = 2; i * i < n; ++i) if (minPrimeFactors[i] == i) // `i` is prime. for (int j = i * i; j < n; j += i) minPrimeFactors[j] = min(minPrimeFactors[j], i); return minPrimeFactors; } vector<int> getPrimeFactors(int num, const vector<int>& minPrimeFactors) { vector<int> primeFactors; while (num > 1) { const int divisor = minPrimeFactors[num]; primeFactors.push_back(divisor); while (num % divisor == 0) num /= divisor; } return primeFactors; } };
2,019
The Score of Students Solving Math Expression
3
scoreOfStudents
You are given a string `s` that contains digits `0-9`, addition symbols `'+'`, and multiplication symbols `'*'` only, representing a valid math expression of single digit numbers (e.g., `3+5*2`). This expression was given to `n` elementary school students. The students were instructed to get the answer of the expression by following this order of operations: 1. Compute multiplication, reading from left to right; Then, 2. Compute addition, reading from left to right. You are given an integer array `answers` of length `n`, which are the submitted answers of the students in no particular order. You are asked to grade the `answers`, by following these rules: * If an answer equals the correct answer of the expression, this student will be rewarded `5` points; * Otherwise, if the answer could be interpreted as if the student applied the operators in the wrong order but had correct arithmetic, this student will be rewarded `2` points; * Otherwise, this student will be rewarded `0` points. Return the sum of the points of the students.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers import operator from typing import List, Dict, Tuple, Iterator class Solution: def scoreOfStudents(self, s: str, answers: List[int]) -> int: n = len(s) // 2 + 1 ans = 0 func = {'+': operator.add, '*': operator.mul} dp = [[set() for j in range(n)] for _ in range(n)] for i in range(n): dp[i][i].add(int(s[i * 2])) for d in range(1, n): for i in range(n - d): j = i + d for k in range(i, j): op = s[k * 2 + 1] for a in dp[i][k]: for b in dp[k + 1][j]: res = func[op](a, b) if res <= 1000: dp[i][j].add(res) correctAnswer = eval(s) for answer, freq in collections.Counter(answers).items(): if answer == correctAnswer: ans += 5 * freq elif answer in dp[0][n - 1]: ans += 2 * freq return ans
class Solution { public int scoreOfStudents(String s, int[] answers) { final int n = s.length() / 2 + 1; int ans = 0; Set<Integer>[][] dp = new Set[n][n]; Map<Integer, Integer> count = new HashMap<>(); for (int i = 0; i < n; ++i) for (int j = i; j < n; ++j) dp[i][j] = new HashSet<>(); for (int i = 0; i < n; ++i) dp[i][i].add(s.charAt(i * 2) - '0'); for (int d = 1; d < n; ++d) for (int i = 0; i + d < n; ++i) { final int j = i + d; for (int k = i; k < j; ++k) { final char op = s.charAt(k * 2 + 1); for (final int a : dp[i][k]) for (final int b : dp[k + 1][j]) { final int res = func(op, a, b); if (res <= 1000) dp[i][j].add(res); } } } final int correctAnswer = eval(s); for (final int answer : answers) count.merge(answer, 1, Integer::sum); for (final int answer : count.keySet()) if (answer == correctAnswer) ans += 5 * count.get(answer); else if (dp[0][n - 1].contains(answer)) ans += 2 * count.get(answer); return ans; } private int eval(final String s) { int ans = 0; int currNum = 0; int prevNum = 0; char op = '+'; for (int i = 0; i < s.length(); ++i) { final char c = s.charAt(i); if (Character.isDigit(c)) currNum = currNum * 10 + (c - '0'); if (!Character.isDigit(c) || i == s.length() - 1) { if (op == '+') { ans += prevNum; prevNum = currNum; } else if (op == '*') { prevNum = prevNum * currNum; } op = c; currNum = 0; } } return ans + prevNum; } private int func(char op, int a, int b) { if (op == '+') return a + b; return a * b; } }
class Solution { public: int scoreOfStudents(string s, vector<int>& answers) { const int n = s.length() / 2 + 1; const unordered_map<char, function<int(int, int)>> func{ {'+', plus<int>()}, {'*', multiplies<int>()}}; int ans = 0; vector<vector<unordered_set<int>>> dp(n, vector<unordered_set<int>>(n)); unordered_map<int, int> count; for (int i = 0; i < n; ++i) dp[i][i].insert(s[i * 2] - '0'); for (int d = 1; d < n; ++d) for (int i = 0; i + d < n; ++i) { const int j = i + d; for (int k = i; k < j; ++k) { const char op = s[k * 2 + 1]; for (const int a : dp[i][k]) for (const int b : dp[k + 1][j]) { const int res = func.at(op)(a, b); if (res <= 1000) dp[i][j].insert(res); } } } const int correctAnswer = eval(s); for (const int answer : answers) ++count[answer]; for (const auto& [answer, freq] : count) if (answer == correctAnswer) ans += 5 * freq; else if (dp[0][n - 1].contains(answer)) ans += 2 * freq; return ans; } private: int eval(const string& s) { int ans = 0; int prevNum = 0; int currNum = 0; char op = '+'; for (int i = 0; i < s.length(); ++i) { const char c = s[i]; if (isdigit(c)) currNum = currNum * 10 + (c - '0'); if (!isdigit(c) || i == s.length() - 1) { if (op == '+') { ans += prevNum; prevNum = currNum; } else if (op == '*') { prevNum = prevNum * currNum; } op = c; currNum = 0; } } return ans + prevNum; } };
2,030
Smallest K-Length Subsequence With Occurrences of a Letter
3
smallestSubsequence
You are given a string `s`, an integer `k`, a letter `letter`, and an integer `repetition`. Return the lexicographically smallest subsequence of `s` of length `k` that has the letter `letter` appear at least `repetition` times. The test cases are generated so that the `letter` appears in `s` at least `repetition` times. A subsequence is a string that can be derived from another string by deleting some or no characters without changing the order of the remaining characters. A string `a` is lexicographically smaller than a string `b` if in the first position where `a` and `b` differ, string `a` has a letter that appears earlier in the alphabet than the corresponding letter in `b`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def smallestSubsequence(self, s: str, k: int, letter: str, repetition: int) -> str: stack = [] required = repetition nLetters = s.count(letter) for i, c in enumerate(s): while stack and stack[-1] > c and len(stack) + len(s) - i - 1 >= k and (stack[-1] != letter or nLetters > required): if stack.pop() == letter: required += 1 if len(stack) < k: if c == letter: stack.append(c) required -= 1 elif k - len(stack) > required: stack.append(c) if c == letter: nLetters -= 1 return ''.join(stack)
class Solution { public String smallestSubsequence(String s, int k, char letter, int repetition) { StringBuilder sb = new StringBuilder(); Deque<Character> stack = new ArrayDeque<>(); int required = repetition; int nLetters = (int) s.chars().filter(c -> c == letter).count(); for (int i = 0; i < s.length(); ++i) { final char c = s.charAt(i); while (!stack.isEmpty() && stack.peek() > c && stack.size() + s.length() - i - 1 >= k && (stack.peek() != letter || nLetters > required)) if (stack.pop() == letter) ++required; if (stack.size() < k) if (c == letter) { stack.push(c); --required; } else if (k - stack.size() > required) { stack.push(c); } if (c == letter) --nLetters; } for (final char c : stack) sb.append(c); return sb.reverse().toString(); } }
class Solution { public: string smallestSubsequence(string s, int k, char letter, int repetition) { string ans; vector<char> stack; int required = repetition; int nLetters = ranges::count(s, letter); for (int i = 0; i < s.length(); ++i) { const char c = s[i]; while (!stack.empty() && stack.back() > c && stack.size() + s.length() - i - 1 >= k && (stack.back() != letter || nLetters > required)) { const char popped = stack.back(); stack.pop_back(); if (popped == letter) ++required; } if (stack.size() < k) if (c == letter) { stack.push_back(c); --required; } else if (k > stack.size() + required) { stack.push_back(c); } if (c == letter) --nLetters; } for (const char c : stack) ans += c; return ans; } };
2,040
Kth Smallest Product of Two Sorted Arrays
3
kthSmallestProduct
Given two sorted 0-indexed integer arrays `nums1` and `nums2` as well as an integer `k`, return the `kth` (1-based) smallest product of `nums1[i] * nums2[j]` where `0 <= i < nums1.length` and `0 <= j < nums2.length`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def kthSmallestProduct(self, nums1: List[int], nums2: List[int], k: int) -> int: A1 = [-num for num in nums1 if num < 0][::-1] A2 = [num for num in nums1 if num >= 0] B1 = [-num for num in nums2 if num < 0][::-1] B2 = [num for num in nums2 if num >= 0] negCount = len(A1) * len(B2) + len(A2) * len(B1) if k > negCount: k -= negCount sign = 1 else: k = negCount - k + 1 sign = -1 B1, B2 = B2, B1 def numProductNoGreaterThan(A: List[int], B: List[int], m: int) -> int: ans = 0 j = len(B) - 1 for i in range(len(A)): while j >= 0 and A[i] * B[j] > m: j -= 1 ans += j + 1 return ans l = 0 r = 10**10 while l < r: m = (l + r) // 2 if numProductNoGreaterThan(A1, B1, m) + numProductNoGreaterThan(A2, B2, m) >= k: r = m else: l = m + 1 return sign * l
class Solution { public long kthSmallestProduct(int[] nums1, int[] nums2, long k) { List<Integer> A1 = new ArrayList<>(); List<Integer> A2 = new ArrayList<>(); List<Integer> B1 = new ArrayList<>(); List<Integer> B2 = new ArrayList<>(); seperate(nums1, A1, A2); seperate(nums2, B1, B2); final long negCount = A1.size() * B2.size() + A2.size() * B1.size(); int sign = 1; if (k > negCount) { k -= negCount; // Find the (k - negCount)-th positive. } else { k = negCount - k + 1; // Find the (negCount - k + 1)-th abs(negative). sign = -1; List<Integer> temp = B1; B1 = B2; B2 = temp; } long l = 0; long r = (long) 1e10; while (l < r) { final long m = (l + r) / 2; if (numProductNoGreaterThan(A1, B1, m) + numProductNoGreaterThan(A2, B2, m) >= k) r = m; else l = m + 1; } return sign * l; } private void seperate(int[] arr, List<Integer> A1, List<Integer> A2) { for (final int a : arr) if (a < 0) A1.add(-a); else A2.add(a); Collections.reverse(A1); // Reverse to sort ascending } private long numProductNoGreaterThan(List<Integer> A, List<Integer> B, long m) { long count = 0; int j = B.size() - 1; // For each a, find the first index j s.t. a * B[j] <= m // So numProductNoGreaterThan m for this row will be j + 1 for (final long a : A) { while (j >= 0 && a * B.get(j) > m) --j; count += j + 1; } return count; } }
class Solution { public: long long kthSmallestProduct(vector<int>& nums1, vector<int>& nums2, long long k) { vector<int> A1; vector<int> A2; vector<int> B1; vector<int> B2; seperate(nums1, A1, A2); seperate(nums2, B1, B2); const long negCount = A1.size() * B2.size() + A2.size() * B1.size(); int sign = 1; if (k > negCount) { k -= negCount; // Find the (k - negCount)-th positive. } else { k = negCount - k + 1; // Find the (negCount - k + 1)-th abs(negative). sign = -1; swap(B1, B2); } long l = 0; long r = 1e10; while (l < r) { const long m = (l + r) / 2; if (numProductNoGreaterThan(A1, B1, m) + numProductNoGreaterThan(A2, B2, m) >= k) r = m; else l = m + 1; } return sign * l; } private: void seperate(const vector<int>& arr, vector<int>& A1, vector<int>& A2) { for (const int a : arr) if (a < 0) A1.push_back(-a); else A2.push_back(a); ranges::reverse(A1); // Reverse to sort ascending } long numProductNoGreaterThan(const vector<int>& A, const vector<int>& B, long m) { long count = 0; int j = B.size() - 1; // For each a, find the first index j s.t. a * B[j] <= m // So numProductNoGreaterThan m for this row will be j + 1 for (const long a : A) { while (j >= 0 && a * B[j] > m) --j; count += j + 1; } return count; } };
2,045
Second Minimum Time to Reach Destination
3
secondMinimum
A city is represented as a bi-directional connected graph with `n` vertices where each vertex is labeled from `1` to `n` (inclusive). The edges in the graph are represented as a 2D integer array `edges`, where each `edges[i] = [ui, vi]` denotes a bi-directional edge between vertex `ui` and vertex `vi`. Every vertex pair is connected by at most one edge, and no vertex has an edge to itself. The time taken to traverse any edge is `time` minutes. Each vertex has a traffic signal which changes its color from green to red and vice versa every `change` minutes. All signals change at the same time. You can enter a vertex at any time, but can leave a vertex only when the signal is green. You cannot wait at a vertex if the signal is green. The second minimum value is defined as the smallest value strictly larger than the minimum value. * For example the second minimum value of `[2, 3, 4]` is `3`, and the second minimum value of `[2, 2, 4]` is `4`. Given `n`, `edges`, `time`, and `change`, return the second minimum time it will take to go from vertex `1` to vertex `n`. Notes: * You can go through any vertex any number of times, including `1` and `n`. * You can assume that when the journey starts, all signals have just turned green.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def secondMinimum(self, n: int, edges: List[List[int]], time: int, change: int) -> int: graph = [[] for _ in range(n + 1)] q = collections.deque([(1, 0)]) minTime = [[math.inf] * 2 for _ in range(n + 1)] minTime[1][0] = 0 for u, v in edges: graph[u].append(v) graph[v].append(u) while q: i, prevTime = q.popleft() numChangeSignal = prevTime // change waitTime = change - (prevTime % change) if numChangeSignal & 1 else 0 newTime = prevTime + waitTime + time for j in graph[i]: if newTime < minTime[j][0]: minTime[j][0] = newTime q.append((j, newTime)) elif minTime[j][0] < newTime < minTime[j][1]: if j == n: return newTime minTime[j][1] = newTime q.append((j, newTime))
class Solution { public int secondMinimum(int n, int[][] edges, int time, int change) { List<Integer>[] graph = new List[n + 1]; // (index, time) Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(1, 0))); // minTime[u][0] := the first minimum time to reach the node u // minTime[u][1] := the second minimum time to reach the node u int[][] minTime = new int[n + 1][2]; Arrays.stream(minTime).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); minTime[1][0] = 0; for (int i = 1; i <= n; ++i) graph[i] = new ArrayList<>(); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; graph[u].add(v); graph[v].add(u); } while (!q.isEmpty()) { final int u = q.peek().getKey(); final int prevTime = q.poll().getValue(); // Start from green. // If `numChangeSignal` is odd, now red. // If `numChangeSignal` is even, now green. final int numChangeSignal = prevTime / change; final int waitTime = numChangeSignal % 2 == 0 ? 0 : change - prevTime % change; final int newTime = prevTime + waitTime + time; for (final int v : graph[u]) if (newTime < minTime[v][0]) { minTime[v][0] = newTime; q.offer(new Pair<>(v, newTime)); } else if (minTime[v][0] < newTime && newTime < minTime[v][1]) { if (v == n) return newTime; minTime[v][1] = newTime; q.offer(new Pair<>(v, newTime)); } } throw new IllegalArgumentException(); } }
class Solution { public: int secondMinimum(int n, vector<vector<int>>& edges, int time, int change) { vector<vector<int>> graph(n + 1); queue<pair<int, int>> q{{{1, 0}}}; // minTime[u][0] := the first minimum time to reach the node u // minTime[u][1] := the second minimum time to reach the node u vector<vector<int>> minTime(n + 1, vector<int>(2, INT_MAX)); minTime[1][0] = 0; for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; graph[u].push_back(v); graph[v].push_back(u); } while (!q.empty()) { const auto [u, prevTime] = q.front(); q.pop(); // Start from green. // If `numChangeSignal` is odd, now red. // If `numChangeSignal` is even, now green. const int numChangeSignal = prevTime / change; const int waitTime = numChangeSignal % 2 == 0 ? 0 : change - prevTime % change; const int newTime = prevTime + waitTime + time; for (const int v : graph[u]) if (newTime < minTime[v][0]) { minTime[v][0] = newTime; q.emplace(v, newTime); } else if (minTime[v][0] < newTime && newTime < minTime[v][1]) { if (v == n) return newTime; minTime[v][1] = newTime; q.emplace(v, newTime); } } throw; } };
2,059
Minimum Operations to Convert Number
2
minimumOperations
You are given a 0-indexed integer array `nums` containing distinct numbers, an integer `start`, and an integer `goal`. There is an integer `x` that is initially set to `start`, and you want to perform operations on `x` such that it is converted to `goal`. You can perform the following operation repeatedly on the number `x`: If `0 <= x <= 1000`, then for any index `i` in the array (`0 <= i < nums.length`), you can set `x` to any of the following: * `x + nums[i]` * `x - nums[i]` * `x ^ nums[i]` (bitwise-XOR) Note that you can use each `nums[i]` any number of times in any order. Operations that set `x` to be out of the range `0 <= x <= 1000` are valid, but no more operations can be done afterward. Return the minimum number of operations needed to convert `x = start` into `goal`, and `-1` if it is not possible.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minimumOperations(self, nums: List[int], start: int, goal: int) -> int: ans = 0 q = collections.deque([start]) seen = {start} while q: ans += 1 for _ in range(len(q)): x = q.popleft() for num in nums: for res in (x + num, x - num, x ^ num): if res == goal: return ans if res < 0 or res > 1000 or res in seen: continue seen.add(res) q.append(res) return -1
class Solution { public int minimumOperations(int[] nums, int start, int goal) { Queue<Integer> q = new ArrayDeque<>(List.of(start)); boolean[] seen = new boolean[1001]; seen[start] = true; for (int step = 1; !q.isEmpty(); ++step) for (int sz = q.size(); sz > 0; --sz) { final int x = q.poll(); for (final int num : nums) { for (final int res : new int[] {x + num, x - num, x ^ num}) { if (res == goal) return step; if (res < 0 || res > 1000 || seen[res]) continue; seen[res] = true; q.offer(res); } } } return -1; } }
class Solution { public: int minimumOperations(vector<int>& nums, int start, int goal) { queue<int> q{{start}}; vector<bool> seen(1001); seen[start] = true; for (int step = 1; !q.empty(); ++step) for (int sz = q.size(); sz > 0; --sz) { const int x = q.front(); q.pop(); for (const int num : nums) { for (const int res : {x + num, x - num, x ^ num}) { if (res == goal) return step; if (res < 0 || res > 1000 || seen[res]) continue; seen[res] = true; q.push(res); } } } return -1; } };
2,076
Process Restricted Friend Requests
3
friendRequests
You are given an integer `n` indicating the number of people in a network. Each person is labeled from `0` to `n - 1`. You are also given a 0-indexed 2D integer array `restrictions`, where `restrictions[i] = [xi, yi]` means that person `xi` and person `yi` cannot become friends, either directly or indirectly through other people. Initially, no one is friends with each other. You are given a list of friend requests as a 0-indexed 2D integer array `requests`, where `requests[j] = [uj, vj]` is a friend request between person `uj` and person `vj`. A friend request is successful if `uj` and `vj` can be friends. Each friend request is processed in the given order (i.e., `requests[j]` occurs before `requests[j + 1]`), and upon a successful request, `uj` and `vj` become direct friends for all future friend requests. Return a boolean array `result`, where each `result[j]` is `true` if the `jth` friend request is successful or `false` if it is not. Note: If `uj` and `vj` are already direct friends, the request is still successful.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class UnionFind: def __init__(self, n: int): self.id = list(range(n)) self.rank = [0] * n def unionByRank(self, u: int, v: int) -> None: i = self.find(u) j = self.find(v) if i == j: return if self.rank[i] < self.rank[j]: self.id[i] = j elif self.rank[i] > self.rank[j]: self.id[j] = i else: self.id[i] = j self.rank[j] += 1 def find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self.find(self.id[u]) return self.id[u] class Solution: def friendRequests(self, n: int, restrictions: List[List[int]], requests: List[List[int]]) -> List[bool]: ans = [] uf = UnionFind(n) for u, v in requests: pu = uf.find(u) pv = uf.find(v) isValid = True if pu != pv: for x, y in restrictions: px = uf.find(x) py = uf.find(y) if (pu, pv) in [(px, py), (py, px)]: isValid = False break ans.append(isValid) if isValid: uf.unionByRank(pu, pv) return ans
class UnionFind { public UnionFind(int n) { id = new int[n]; rank = new int[n]; for (int i = 0; i < n; ++i) id[i] = i; } public void unionByRank(int u, int v) { final int i = find(u); final int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } public int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } private int[] id; private int[] rank; } class Solution { public boolean[] friendRequests(int n, int[][] restrictions, int[][] requests) { boolean[] ans = new boolean[requests.length]; UnionFind uf = new UnionFind(n); for (int i = 0; i < requests.length; ++i) { final int pu = uf.find(requests[i][0]); final int pv = uf.find(requests[i][1]); boolean isValid = true; if (pu != pv) for (int[] restriction : restrictions) { final int px = uf.find(restriction[0]); final int py = uf.find(restriction[1]); if (pu == px && pv == py || pu == py && pv == px) { isValid = false; break; } } ans[i] = isValid; if (isValid) uf.unionByRank(pu, pv); } return ans; } }
class UnionFind { public: UnionFind(int n) : id(n), rank(n) { iota(id.begin(), id.end(), 0); } void unionByRank(int u, int v) { const int i = find(u); const int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } private: vector<int> id; vector<int> rank; }; class Solution { public: vector<bool> friendRequests(int n, vector<vector<int>>& restrictions, vector<vector<int>>& requests) { vector<bool> ans; UnionFind uf(n); for (const vector<int>& request : requests) { const int i = uf.find(request[0]); const int j = uf.find(request[1]); bool isValid = true; if (i != j) for (const vector<int>& restriction : restrictions) { const int x = uf.find(restriction[0]); const int y = uf.find(restriction[1]); if (i == x && j == y || i == y && j == x) { isValid = false; break; } } ans.push_back(isValid); if (isValid) uf.unionByRank(i, j); } return ans; } };
2,086
Minimum Number of Buckets Required to Collect Rainwater from Houses
2
minimumBuckets
You are given a 0-indexed string `hamsters` where `hamsters[i]` is either: * `'H'` indicating that there is a hamster at index `i`, or * `'.'` indicating that index `i` is empty. You will add some number of food buckets at the empty indices in order to feed the hamsters. A hamster can be fed if there is at least one food bucket to its left or to its right. More formally, a hamster at index `i` can be fed if you place a food bucket at index `i - 1` and/or at index `i + 1`. Return the minimum number of food buckets you should place at empty indices to feed all the hamsters or `-1` if it is impossible to feed all of them.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minimumBuckets(self, street: str) -> int: A = list(street) for i, c in enumerate(A): if c == 'H': if i > 0 and A[i - 1] == 'B': continue if i + 1 < len(A) and A[i + 1] == '.': A[i + 1] = 'B' elif i > 0 and A[i - 1] == '.': A[i - 1] = 'B' else: return -1 return A.count('B')
class Solution { public int minimumBuckets(String street) { final char[] A = street.toCharArray(); for (int i = 0; i < A.length; ++i) if (A[i] == 'H') { if (i > 0 && A[i - 1] == 'B') continue; if (i + 1 < A.length && A[i + 1] == '.') // Always prefer place a bucket in (i + 1) because it enhances the // possibility to collect the upcoming houses. A[i + 1] = 'B'; else if (i > 0 && A[i - 1] == '.') A[i - 1] = 'B'; else return -1; } return (int) new String(A).chars().filter(a -> a == 'B').count(); } }
class Solution { public: int minimumBuckets(string street) { for (int i = 0; i < street.length(); ++i) if (street[i] == 'H') { if (i > 0 && street[i - 1] == 'B') continue; if (i + 1 < street.length() && street[i + 1] == '.') // Always prefer place a bucket in (i + 1) because it enhances the // possibility to collect the upcoming houses. street[i + 1] = 'B'; else if (i > 0 && street[i - 1] == '.') street[i - 1] = 'B'; else return -1; } return ranges::count(street, 'B'); } };
2,092
Find All People With Secret
3
findAllPeople
You are given an integer `n` indicating there are `n` people numbered from `0` to `n - 1`. You are also given a 0-indexed 2D integer array `meetings` where `meetings[i] = [xi, yi, timei]` indicates that person `xi` and person `yi` have a meeting at `timei`. A person may attend multiple meetings at the same time. Finally, you are given an integer `firstPerson`. Person `0` has a secret and initially shares the secret with a person `firstPerson` at time `0`. This secret is then shared every time a meeting takes place with a person that has the secret. More formally, for every meeting, if a person `xi` has the secret at `timei`, then they will share the secret with person `yi`, and vice versa. The secrets are shared instantaneously. That is, a person may receive the secret and share it with people in other meetings within the same time frame. Return a list of all the people that have the secret after all the meetings have taken place. You may return the answer in any order.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class UnionFind: def __init__(self, n: int): self.id = list(range(n)) self.rank = [0] * n def unionByRank(self, u: int, v: int) -> None: i = self._find(u) j = self._find(v) if i == j: return if self.rank[i] < self.rank[j]: self.id[i] = j elif self.rank[i] > self.rank[j]: self.id[j] = i else: self.id[i] = j self.rank[j] += 1 def connected(self, u: int, v: int) -> bool: return self._find(self.id[u]) == self._find(self.id[v]) def reset(self, u: int) -> None: self.id[u] = u def _find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self._find(self.id[u]) return self.id[u] class Solution: def findAllPeople(self, n: int, meetings: List[List[int]], firstPerson: int) -> List[int]: uf = UnionFind(n) timeToPairs = collections.defaultdict(list) uf.unionByRank(0, firstPerson) for x, y, time in meetings: timeToPairs[time].append((x, y)) for _, pairs in sorted(timeToPairs.items(), key=lambda x: x[0]): peopleUnioned = set() for x, y in pairs: uf.unionByRank(x, y) peopleUnioned.add(x) peopleUnioned.add(y) for person in peopleUnioned: if not uf.connected(person, 0): uf.reset(person) res=[] for i in range(n): if uf.connected(i, 0): res.append(i) return res
class UnionFind { public UnionFind(int n) { id = new int[n]; rank = new int[n]; for (int i = 0; i < n; ++i) id[i] = i; } public void unionByRank(int u, int v) { final int i = find(u); final int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } public boolean connected(int u, int v) { return find(u) == find(v); } public void reset(int u) { id[u] = u; } private int[] id; private int[] rank; private int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } } class Solution { public List<Integer> findAllPeople(int n, int[][] meetings, int firstPerson) { List<Integer> ans = new ArrayList<>(); UnionFind uf = new UnionFind(n); TreeMap<Integer, List<Pair<Integer, Integer>>> timeToPairs = new TreeMap<>(); uf.unionByRank(0, firstPerson); for (int[] meeting : meetings) { final int x = meeting[0]; final int y = meeting[1]; final int time = meeting[2]; timeToPairs.putIfAbsent(time, new ArrayList<>()); timeToPairs.get(time).add(new Pair<>(x, y)); } for (List<Pair<Integer, Integer>> pairs : timeToPairs.values()) { Set<Integer> peopleUnioned = new HashSet<>(); for (Pair<Integer, Integer> pair : pairs) { final int x = pair.getKey(); final int y = pair.getValue(); uf.unionByRank(x, y); peopleUnioned.add(x); peopleUnioned.add(y); } for (final int person : peopleUnioned) if (!uf.connected(person, 0)) uf.reset(person); } for (int i = 0; i < n; ++i) if (uf.connected(i, 0)) ans.add(i); return ans; } }
class UnionFind { public: UnionFind(int n) : id(n), rank(n) { iota(id.begin(), id.end(), 0); } void unionByRank(int u, int v) { const int i = find(u); const int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } bool connected(int u, int v) { return find(u) == find(v); } void reset(int u) { id[u] = u; } private: vector<int> id; vector<int> rank; int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } }; class Solution { public: vector<int> findAllPeople(int n, vector<vector<int>>& meetings, int firstPerson) { vector<int> ans; UnionFind uf(n); map<int, vector<pair<int, int>>> timeToPairs; uf.unionByRank(0, firstPerson); for (const vector<int>& meeting : meetings) { const int x = meeting[0]; const int y = meeting[1]; const int time = meeting[2]; timeToPairs[time].push_back({x, y}); } for (const auto& [_, pairs] : timeToPairs) { unordered_set<int> peopleUnioned; for (const auto& [x, y] : pairs) { uf.unionByRank(x, y); peopleUnioned.insert(x); peopleUnioned.insert(y); } for (const int person : peopleUnioned) if (!uf.connected(person, 0)) uf.reset(person); } for (int i = 0; i < n; ++i) if (uf.connected(i, 0)) ans.push_back(i); return ans; } };
2,115
Find All Possible Recipes from Given Supplies
2
findAllRecipes
You have information about `n` different recipes. You are given a string array `recipes` and a 2D string array `ingredients`. The `ith` recipe has the name `recipes[i]`, and you can create it if you have all the needed ingredients from `ingredients[i]`. Ingredients to a recipe may need to be created from other recipes, i.e., `ingredients[i]` may contain a string that is in `recipes`. You are also given a string array `supplies` containing all the ingredients that you initially have, and you have an infinite supply of all of them. Return a list of all the recipes that you can create. You may return the answer in any order. Note that two recipes may contain each other in their ingredients.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def findAllRecipes(self, recipes: List[str], ingredients: List[List[str]], supplies: List[str]) -> List[str]: ans = [] supplies = set(supplies) graph = collections.defaultdict(list) inDegrees = collections.Counter() q = collections.deque() for i, recipe in enumerate(recipes): for ingredient in ingredients[i]: if ingredient not in supplies: graph[ingredient].append(recipe) inDegrees[recipe] += 1 for recipe in recipes: if inDegrees[recipe] == 0: q.append(recipe) while q: u = q.popleft() ans.append(u) for v in graph[u]: inDegrees[v] -= 1 if inDegrees[v] == 0: q.append(v) return ans
class Solution { public List<String> findAllRecipes(String[] recipes, List<List<String>> ingredients, String[] supplies) { List<String> ans = new ArrayList<>(); Set<String> suppliesSet = new HashSet<>(); for (final String supply : supplies) suppliesSet.add(supply); Map<String, List<String>> graph = new HashMap<>(); Map<String, Integer> inDegrees = new HashMap<>(); // Build the graph. for (int i = 0; i < recipes.length; ++i) for (final String ingredient : ingredients.get(i)) if (!suppliesSet.contains(ingredient)) { graph.putIfAbsent(ingredient, new ArrayList<>()); graph.get(ingredient).add(recipes[i]); inDegrees.merge(recipes[i], 1, Integer::sum); } // Perform topological sorting. Queue<String> q = Arrays.stream(recipes) .filter(recipe -> inDegrees.getOrDefault(recipe, 0) == 0) .collect(Collectors.toCollection(ArrayDeque::new)); while (!q.isEmpty()) { final String u = q.poll(); ans.add(u); if (!graph.containsKey(u)) continue; for (final String v : graph.get(u)) { inDegrees.merge(v, -1, Integer::sum); if (inDegrees.get(v) == 0) q.offer(v); } } return ans; } }
class Solution { public: vector<string> findAllRecipes(vector<string>& recipes, vector<vector<string>>& ingredients, vector<string>& supplies) { vector<string> ans; unordered_set<string> suppliesSet(supplies.begin(), supplies.end()); unordered_map<string, vector<string>> graph; unordered_map<string, int> inDegrees; queue<string> q; // Build the graph. for (int i = 0; i < recipes.size(); ++i) for (const string& ingredient : ingredients[i]) if (!suppliesSet.contains(ingredient)) { graph[ingredient].push_back(recipes[i]); ++inDegrees[recipes[i]]; } // Perform topological sorting. for (const string& recipe : recipes) if (!inDegrees.contains(recipe)) q.push(recipe); while (!q.empty()) { const string u = q.front(); q.pop(); ans.push_back(u); if (!graph.contains(u)) continue; for (const string& v : graph[u]) if (--inDegrees[v] == 0) q.push(v); } return ans; } };
2,127
Maximum Employees to Be Invited to a Meeting
3
maximumInvitations
A company is organizing a meeting and has a list of `n` employees, waiting to be invited. They have arranged for a large circular table, capable of seating any number of employees. The employees are numbered from `0` to `n - 1`. Each employee has a favorite person and they will attend the meeting only if they can sit next to their favorite person at the table. The favorite person of an employee is not themself. Given a 0-indexed integer array `favorite`, where `favorite[i]` denotes the favorite person of the `ith` employee, return the maximum number of employees that can be invited to the meeting.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator from enum import Enum class State(Enum): kInit = 0 kVisiting = 1 kVisited = 2 class Solution: def maximumInvitations(self, favorite: List[int]) -> int: n = len(favorite) sumComponentsLength = 0 graph = [[] for _ in range(n)] inDegrees = [0] * n maxChainLength = [1] * n for i, f in enumerate(favorite): graph[i].append(f) inDegrees[f] += 1 q = collections.deque([i for i, d in enumerate(inDegrees) if d == 0]) while q: u = q.popleft() for v in graph[u]: inDegrees[v] -= 1 if inDegrees[v] == 0: q.append(v) maxChainLength[v] = max(maxChainLength[v], 1 + maxChainLength[u]) for i in range(n): if favorite[favorite[i]] == i: sumComponentsLength += maxChainLength[i] + maxChainLength[favorite[i]] maxCycleLength = 0 parent = [-1] * n seen = set() states = [State.kInit] * n def findCycle(u: int) -> None: nonlocal maxCycleLength seen.add(u) states[u] = State.kVisiting for v in graph[u]: if v not in seen: parent[v] = u findCycle(v) elif states[v] == State.kVisiting: curr = u cycleLength = 1 while curr != v: curr = parent[curr] cycleLength += 1 maxCycleLength = max(maxCycleLength, cycleLength) states[u] = State.kVisited for i in range(n): if i not in seen: findCycle(i) return max(sumComponentsLength // 2, maxCycleLength)
enum State { INIT, VISITING, VISITED } class Solution { public int maximumInvitations(int[] favorite) { final int n = favorite.length; int sumComponentsLength = 0; // the component: a -> b -> c <-> x <- y List<Integer>[] graph = new List[n]; int[] inDegrees = new int[n]; int[] maxChainLength = new int[n]; Arrays.fill(maxChainLength, 1); Arrays.setAll(graph, i -> new ArrayList<>()); // Build the graph. for (int i = 0; i < n; ++i) { graph[i].add(favorite[i]); ++inDegrees[favorite[i]]; } // Perform topological sorting. Queue<Integer> q = IntStream.range(0, n) .filter(i -> inDegrees[i] == 0) .boxed() .collect(Collectors.toCollection(ArrayDeque::new)); while (!q.isEmpty()) { final int u = q.poll(); for (final int v : graph[u]) { if (--inDegrees[v] == 0) q.offer(v); maxChainLength[v] = Math.max(maxChainLength[v], 1 + maxChainLength[u]); } } for (int i = 0; i < n; ++i) if (favorite[favorite[i]] == i) // i <-> favorite[i] (the cycle's length = 2) sumComponentsLength += maxChainLength[i] + maxChainLength[favorite[i]]; int[] parent = new int[n]; Arrays.fill(parent, -1); boolean[] seen = new boolean[n]; State[] states = new State[n]; for (int i = 0; i < n; ++i) if (!seen[i]) findCycle(graph, i, parent, seen, states); return Math.max(sumComponentsLength / 2, maxCycleLength); } private int maxCycleLength = 0; // the cycle : a -> b -> c -> a private void findCycle(List<Integer>[] graph, int u, int[] parent, boolean[] seen, State[] states) { seen[u] = true; states[u] = State.VISITING; for (final int v : graph[u]) { if (!seen[v]) { parent[v] = u; findCycle(graph, v, parent, seen, states); } else if (states[v] == State.VISITING) { // Find the cycle's length. int curr = u; int cycleLength = 1; while (curr != v) { curr = parent[curr]; ++cycleLength; } maxCycleLength = Math.max(maxCycleLength, cycleLength); } } states[u] = State.VISITED; } }
enum class State { kInit, kVisiting, kVisited }; class Solution { public: int maximumInvitations(vector<int>& favorite) { const int n = favorite.size(); int sumComponentsLength = 0; // the component: a -> b -> c <-> x <- y vector<vector<int>> graph(n); vector<int> inDegrees(n); vector<int> maxChainLength(n, 1); queue<int> q; // Build the graph. for (int i = 0; i < n; ++i) { graph[i].push_back(favorite[i]); ++inDegrees[favorite[i]]; } // Perform topological sorting. for (int i = 0; i < n; ++i) if (inDegrees[i] == 0) q.push(i); while (!q.empty()) { const int u = q.front(); q.pop(); for (const int v : graph[u]) { if (--inDegrees[v] == 0) q.push(v); maxChainLength[v] = max(maxChainLength[v], 1 + maxChainLength[u]); } } for (int i = 0; i < n; ++i) if (favorite[favorite[i]] == i) // i <-> favorite[i] (the cycle's length = 2) sumComponentsLength += maxChainLength[i] + maxChainLength[favorite[i]]; int maxCycleLength = 0; // the cycle : a -> b -> c -> a vector<int> parent(n, -1); vector<bool> seen(n); vector<State> states(n); for (int i = 0; i < n; ++i) if (!seen[i]) findCycle(graph, i, parent, seen, states, maxCycleLength); return max(sumComponentsLength / 2, maxCycleLength); } private: void findCycle(const vector<vector<int>>& graph, int u, vector<int>& parent, vector<bool>& seen, vector<State>& states, int& maxCycleLength) { seen[u] = true; states[u] = State::kVisiting; for (const int v : graph[u]) { if (!seen[v]) { parent[v] = u; findCycle(graph, v, parent, seen, states, maxCycleLength); } else if (states[v] == State::kVisiting) { // Find the cycle's length. int curr = u; int cycleLength = 1; while (curr != v) { curr = parent[curr]; ++cycleLength; } maxCycleLength = max(maxCycleLength, cycleLength); } } states[u] = State::kVisited; } };
2,132
Stamping the Grid
3
possibleToStamp
You are given an `m x n` binary matrix `grid` where each cell is either `0` (empty) or `1` (occupied). You are then given stamps of size `stampHeight x stampWidth`. We want to fit the stamps such that they follow the given restrictions and requirements: 1. Cover all the empty cells. 2. Do not cover any of the occupied cells. 3. We can put as many stamps as we want. 4. Stamps can overlap with each other. 5. Stamps are not allowed to be rotated. 6. Stamps must stay completely inside the grid. Return `true` if it is possible to fit the stamps while following the given restrictions and requirements. Otherwise, return `false`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def possibleToStamp(self, grid: List[List[int]], stampHeight: int, stampWidth: int) -> bool: m = len(grid) n = len(grid[0]) A = [[0] * (n + 1) for _ in range(m + 1)] B = [[0] * (n + 1) for _ in range(m + 1)] fit = [[False] * n for _ in range(m)] for i in range(m): for j in range(n): A[i + 1][j + 1] = A[i + 1][j] + A[i][j + 1] - A[i][j] + grid[i][j] if i + 1 >= stampHeight and j + 1 >= stampWidth: x = i - stampHeight + 1 y = j - stampWidth + 1 if A[i + 1][j + 1] - A[x][j + 1] - A[i + 1][y] + A[x][y] == 0: fit[i][j] = True for i in range(m): for j in range(n): B[i + 1][j + 1] = B[i + 1][j] + B[i][j + 1] - B[i][j] + fit[i][j] for i in range(m): for j in range(n): if not grid[i][j]: x = min(i + stampHeight, m) y = min(j + stampWidth, n) if B[x][y] - B[i][y] - B[x][j] + B[i][j] == 0: return False return True
class Solution { public boolean possibleToStamp(int[][] grid, int stampHeight, int stampWidth) { final int m = grid.length; final int n = grid[0].length; // A[i][j] := the number of 1s in grid[0..i)[0..j) int[][] A = new int[m + 1][n + 1]; // B[i][j] := the number of ways to stamp the submatrix in [0..i)[0..j) int[][] B = new int[m + 1][n + 1]; // fit[i][j] := 1 if the stamps can fit with the right-bottom at (i, j) int[][] fit = new int[m][n]; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { A[i + 1][j + 1] = A[i + 1][j] + A[i][j + 1] - A[i][j] + grid[i][j]; if (i + 1 >= stampHeight && j + 1 >= stampWidth) { final int x = i - stampHeight + 1; final int y = j - stampWidth + 1; if (A[i + 1][j + 1] - A[x][j + 1] - A[i + 1][y] + A[x][y] == 0) fit[i][j] = 1; } } for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) B[i + 1][j + 1] = B[i + 1][j] + B[i][j + 1] - B[i][j] + fit[i][j]; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 0) { final int x = Math.min(i + stampHeight, m); final int y = Math.min(j + stampWidth, n); if (B[x][y] - B[i][y] - B[x][j] + B[i][j] == 0) return false; } return true; } }
class Solution { public: bool possibleToStamp(vector<vector<int>>& grid, int stampHeight, int stampWidth) { const int m = grid.size(); const int n = grid[0].size(); // A[i][j] := the number of 1s in grid[0..i)[0..j) vector<vector<int>> A(m + 1, vector<int>(n + 1)); // B[i][j] := the number of ways to stamp the submatrix in [0..i)[0..j) vector<vector<int>> B(m + 1, vector<int>(n + 1)); // fit[i][j] := true if the stamps can fit with the right-bottom at (i, j) vector<vector<bool>> fit(m, vector<bool>(n)); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { A[i + 1][j + 1] = A[i + 1][j] + A[i][j + 1] - A[i][j] + grid[i][j]; if (i + 1 >= stampHeight && j + 1 >= stampWidth) { const int x = i - stampHeight + 1; const int y = j - stampWidth + 1; if (A[i + 1][j + 1] - A[x][j + 1] - A[i + 1][y] + A[x][y] == 0) fit[i][j] = true; } } for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) B[i + 1][j + 1] = B[i + 1][j] + B[i][j + 1] - B[i][j] + fit[i][j]; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (!grid[i][j]) { const int x = min(i + stampHeight, m); const int y = min(j + stampWidth, n); if (B[x][y] - B[i][y] - B[x][j] + B[i][j] == 0) return false; } return true; } };
2,146
K Highest Ranked Items Within a Price Range
2
highestRankedKItems
You are given a 0-indexed 2D integer array `grid` of size `m x n` that represents a map of the items in a shop. The integers in the grid represent the following: * `0` represents a wall that you cannot pass through. * `1` represents an empty cell that you can freely move to and from. * All other positive integers represent the price of an item in that cell. You may also freely move to and from these item cells. It takes `1` step to travel between adjacent grid cells. You are also given integer arrays `pricing` and `start` where `pricing = [low, high]` and `start = [row, col]` indicates that you start at the position `(row, col)` and are interested only in items with a price in the range of `[low, high]` (inclusive). You are further given an integer `k`. You are interested in the positions of the `k` highest-ranked items whose prices are within the given price range. The rank is determined by the first of these criteria that is different: 1. Distance, defined as the length of the shortest path from the `start` (shorter distance has a higher rank). 2. Price (lower price has a higher rank, but it must be in the price range). 3. The row number (smaller row number has a higher rank). 4. The column number (smaller column number has a higher rank). Return the `k` highest-ranked items within the price range sorted by their rank (highest to lowest). If there are fewer than `k` reachable items within the price range, return all of them.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def highestRankedKItems(self, grid: List[List[int]], pricing: List[int], start: List[int], k: int) -> List[List[int]]: dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) m = len(grid) n = len(grid[0]) low, high = pricing row, col = start ans = [] if low <= grid[row][col] <= high: ans.append([row, col]) if k == 1: return ans q = collections.deque([(row, col)]) seen = {(row, col)} while q: neighbors = [] for _ in range(len(q)): i, j = q.popleft() for t in range(4): x = i + dirs[t][0] y = j + dirs[t][1] if x < 0 or x == m or y < 0 or y == n: continue if not grid[x][y] or (x, y) in seen: continue if low <= grid[x][y] <= high: neighbors.append([x, y]) q.append((x, y)) seen.add((x, y)) neighbors.sort(key=lambda x: (grid[x[0]][x[1]], x[0], x[1])) for neighbor in neighbors: if len(ans) < k: ans.append(neighbor) if len(ans) == k: return ans return ans
class Solution { public List<List<Integer>> highestRankedKItems(int[][] grid, int[] pricing, int[] start, int k) { final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; final int m = grid.length; final int n = grid[0].length; final int low = pricing[0]; final int high = pricing[1]; final int row = start[0]; final int col = start[1]; List<List<Integer>> ans = new ArrayList<>(); if (low <= grid[row][col] && grid[row][col] <= high) { ans.add(Arrays.asList(row, col)); if (k == 1) return ans; } Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(row, col))); boolean[][] seen = new boolean[m][n]; seen[row][col] = true; // Mark as visited. while (!q.isEmpty()) { List<List<Integer>> neighbors = new ArrayList<>(); for (int sz = q.size(); sz > 0; --sz) { final int i = q.peek().getKey(); final int j = q.poll().getValue(); for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == m || y < 0 || y == n) continue; if (grid[x][y] == 0 || seen[x][y]) continue; if (low <= grid[x][y] && grid[x][y] <= high) neighbors.add(Arrays.asList(x, y)); q.offer(new Pair<>(x, y)); seen[x][y] = true; } } Collections.sort(neighbors, new Comparator<List<Integer>>() { @Override public int compare(List<Integer> a, List<Integer> b) { final int x1 = a.get(0); final int y1 = a.get(1); final int x2 = b.get(0); final int y2 = b.get(1); if (grid[x1][y1] != grid[x2][y2]) return grid[x1][y1] - grid[x2][y2]; return x1 == x2 ? y1 - y2 : x1 - x2; } }); for (List<Integer> neighbor : neighbors) { if (ans.size() < k) ans.add(neighbor); if (ans.size() == k) return ans; } } return ans; } }
class Solution { public: vector<vector<int>> highestRankedKItems(vector<vector<int>>& grid, vector<int>& pricing, vector<int>& start, int k) { constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; const int m = grid.size(); const int n = grid[0].size(); const int low = pricing[0]; const int high = pricing[1]; const int row = start[0]; const int col = start[1]; vector<vector<int>> ans; if (low <= grid[row][col] && grid[row][col] <= high) { ans.push_back({row, col}); if (k == 1) return ans; } queue<pair<int, int>> q{{{row, col}}}; vector<vector<bool>> seen(m, vector<bool>(n)); seen[row][col] = true; // Mark as visited. while (!q.empty()) { vector<vector<int>> neighbors; for (int sz = q.size(); sz > 0; --sz) { const auto [i, j] = q.front(); q.pop(); for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == m || y < 0 || y == n) continue; if (!grid[x][y] || seen[x][y]) continue; if (low <= grid[x][y] && grid[x][y] <= high) neighbors.push_back({x, y}); q.emplace(x, y); seen[x][y] = true; } } ranges::sort(neighbors, [&](const vector<int>& a, const vector<int>& b) { const int x1 = a[0]; const int y1 = a[1]; const int x2 = b[0]; const int y2 = b[1]; if (grid[x1][y1] != grid[x2][y2]) return grid[x1][y1] < grid[x2][y2]; return x1 == x2 ? y1 < y2 : x1 < x2; }); for (const vector<int>& neighbor : neighbors) { if (ans.size() < k) ans.push_back(neighbor); if (ans.size() == k) return ans; } } return ans; } };
2,157
Groups of Strings
3
groupStrings
You are given a 0-indexed array of strings `words`. Each string consists of lowercase English letters only. No letter occurs more than once in any string of `words`. Two strings `s1` and `s2` are said to be connected if the set of letters of `s2` can be obtained from the set of letters of `s1` by any one of the following operations: * Adding exactly one letter to the set of the letters of `s1`. * Deleting exactly one letter from the set of the letters of `s1`. * Replacing exactly one letter from the set of the letters of `s1` with any letter, including itself. The array `words` can be divided into one or more non-intersecting groups. A string belongs to a group if any one of the following is true: * It is connected to at least one other string of the group. * It is the only string present in the group. Note that the strings in `words` should be grouped in such a manner that a string belonging to a group cannot be connected to a string present in any other group. It can be proved that such an arrangement is always unique. Return an array `ans` of size `2` where: * `ans[0]` is the maximum number of groups `words` can be divided into, and * `ans[1]` is the size of the largest group.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class UnionFind: def __init__(self, n: int): self.count = n self.id = list(range(n)) self.sz = [1] * n def unionBySize(self, u: int, v: int) -> None: i = self._find(u) j = self._find(v) if i == j: return if self.sz[i] < self.sz[j]: self.sz[j] += self.sz[i] self.id[i] = j else: self.sz[i] += self.sz[j] self.id[j] = i self.count -= 1 def _find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self._find(self.id[u]) return self.id[u] class Solution: def groupStrings(self, words: List[str]) -> List[int]: uf = UnionFind(len(words)) def getMask(s: str) -> int: mask = 0 for c in s: mask |= 1 << ord(c) - ord('a') return mask def getAddedMasks(mask: int): for i in range(26): if not (mask >> i & 1): yield mask | 1 << i def getDeletedMasks(mask: int): for i in range(26): if mask >> i & 1: yield mask ^ 1 << i maskToIndex = {getMask(word): i for i, word in enumerate(words)} deletedMaskToIndex = {} for i, word in enumerate(words): mask = getMask(word) for m in getAddedMasks(mask): if m in maskToIndex: uf.unionBySize(i, maskToIndex[m]) for m in getDeletedMasks(mask): if m in maskToIndex: uf.unionBySize(i, maskToIndex[m]) if m in deletedMaskToIndex: uf.unionBySize(i, deletedMaskToIndex[m]) else: deletedMaskToIndex[m] = i return [uf.count, max(uf.sz)]
class UnionFind { public UnionFind(int n) { count = n; id = new int[n]; sz = new int[n]; for (int i = 0; i < n; ++i) id[i] = i; for (int i = 0; i < n; ++i) sz[i] = 1; } public void unionBySize(int u, int v) { final int i = find(u); final int j = find(v); if (i == j) return; if (sz[i] < sz[j]) { sz[j] += sz[i]; id[i] = j; } else { sz[i] += sz[j]; id[j] = i; } --count; } public int getCount() { return count; } public int getMaxSize() { return Arrays.stream(sz).max().getAsInt(); } private int count; private int[] id; private int[] sz; private int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } } class Solution { public int[] groupStrings(String[] words) { UnionFind uf = new UnionFind(words.length); Map<Integer, Integer> maskToIndex = new HashMap<>(); Map<Integer, Integer> deletedMaskToIndex = new HashMap<>(); for (int i = 0; i < words.length; ++i) { final int mask = getMask(words[i]); for (int j = 0; j < 26; ++j) if ((mask >> j & 1) == 1) { // Going to delete this bit. final int m = mask ^ 1 << j; if (maskToIndex.containsKey(m)) uf.unionBySize(i, maskToIndex.get(m)); if (deletedMaskToIndex.containsKey(m)) uf.unionBySize(i, deletedMaskToIndex.get(m)); else deletedMaskToIndex.put(m, i); } else { // Going to add this bit. final int m = mask | 1 << j; if (maskToIndex.containsKey(m)) uf.unionBySize(i, maskToIndex.get(m)); } maskToIndex.put(mask, i); } return new int[] {uf.getCount(), uf.getMaxSize()}; } private int getMask(final String s) { int mask = 0; for (final char c : s.toCharArray()) mask |= 1 << c - 'a'; return mask; } }
class UnionFind { public: UnionFind(int n) : count(n), id(n), sz(n, 1) { iota(id.begin(), id.end(), 0); } void unionBySize(int u, int v) { const int i = find(u); const int j = find(v); if (i == j) return; if (sz[i] < sz[j]) { sz[j] += sz[i]; id[i] = j; } else { sz[i] += sz[j]; id[j] = i; } --count; } int getCount() const { return count; } int getMaxSize() const { return ranges::max(sz); } private: int count; vector<int> id; vector<int> sz; int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } }; class Solution { public: vector<int> groupStrings(vector<string>& words) { UnionFind uf(words.size()); unordered_map<int, int> maskToIndex; unordered_map<int, int> deletedMaskToIndex; for (int i = 0; i < words.size(); ++i) { const int mask = getMask(words[i]); for (int j = 0; j < 26; ++j) if (mask >> j & 1) { // Going to delete this bit. const int m = mask ^ 1 << j; if (const auto it = maskToIndex.find(m); it != maskToIndex.cend()) uf.unionBySize(i, it->second); if (const auto it = deletedMaskToIndex.find(m); it != deletedMaskToIndex.cend()) uf.unionBySize(i, it->second); else deletedMaskToIndex[m] = i; } else { // Going to add this bit. const int m = mask | 1 << j; if (const auto it = maskToIndex.find(m); it != maskToIndex.cend()) uf.unionBySize(i, it->second); } maskToIndex[mask] = i; } return {uf.getCount(), uf.getMaxSize()}; } private: int getMask(const string& s) { int mask = 0; for (const char c : s) mask |= 1 << c - 'a'; return mask; } };
2,182
Construct String With Repeat Limit
2
repeatLimitedString
You are given a string `s` and an integer `repeatLimit`. Construct a new string `repeatLimitedString` using the characters of `s` such that no letter appears more than `repeatLimit` times in a row. You do not have to use all characters from `s`. Return the lexicographically largest `repeatLimitedString` possible. A string `a` is lexicographically larger than a string `b` if in the first position where `a` and `b` differ, string `a` has a letter that appears later in the alphabet than the corresponding letter in `b`. If the first `min(a.length, b.length)` characters do not differ, then the longer string is the lexicographically larger one.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def repeatLimitedString(self, s: str, repeatLimit: int) -> str: ans = '' count = collections.Counter(s) while True: addOne = ans and self._shouldAddOne(ans, count) c = self._getLargestChar(ans, count) if c == ' ': break repeats = 1 if addOne else min(count[c], repeatLimit) ans += c * repeats count[c] -= repeats return ans def _shouldAddOne(self, ans: str, count: collections.Counter) -> bool: for c in reversed(string.ascii_lowercase): if count[c]: return ans[-1] == c return False def _getLargestChar(self, ans: str, count: collections.Counter) -> int: for c in reversed(string.ascii_lowercase): if count[c] and (not ans or ans[-1] != c): return c return ' '
class Solution { public String repeatLimitedString(String s, int repeatLimit) { StringBuilder sb = new StringBuilder(); int[] count = new int[26]; for (final char c : s.toCharArray()) ++count[c - 'a']; while (true) { final boolean addOne = !sb.isEmpty() && shouldAddOne(sb, count); final int i = getLargestChar(sb, count); if (i == -1) break; final int repeats = addOne ? 1 : Math.min(count[i], repeatLimit); sb.append(String.valueOf((char) ('a' + i)).repeat(repeats)); count[i] -= repeats; } return sb.toString(); } private boolean shouldAddOne(StringBuilder sb, int[] count) { for (int i = 25; i >= 0; --i) if (count[i] > 0) return sb.charAt(sb.length() - 1) == 'a' + i; return false; } private int getLargestChar(StringBuilder sb, int[] count) { for (int i = 25; i >= 0; --i) if (count[i] > 0 && (sb.isEmpty() || sb.charAt(sb.length() - 1) != 'a' + i)) return i; return -1; } }
class Solution { public: string repeatLimitedString(string s, int repeatLimit) { string ans; vector<int> count(26); for (const char c : s) ++count[c - 'a']; while (true) { const bool addOne = !ans.empty() && shouldAddOne(ans, count); const int i = getLargestChar(ans, count); if (i == -1) break; const int repeats = addOne ? 1 : min(count[i], repeatLimit); ans += string(repeats, 'a' + i); count[i] -= repeats; } return ans; } private: bool shouldAddOne(const string& ans, const vector<int>& count) { for (int i = 25; i >= 0; --i) if (count[i]) return ans.back() == 'a' + i; return false; } int getLargestChar(const string& ans, const vector<int>& count) { for (int i = 25; i >= 0; --i) if (count[i] && (ans.empty() || ans.back() != 'a' + i)) return i; return -1; } };
2,203
Minimum Weighted Subgraph With the Required Paths
3
minimumWeight
You are given an integer `n` denoting the number of nodes of a weighted directed graph. The nodes are numbered from `0` to `n - 1`. You are also given a 2D integer array `edges` where `edges[i] = [fromi, toi, weighti]` denotes that there exists a directed edge from `fromi` to `toi` with weight `weighti`. Lastly, you are given three distinct integers `src1`, `src2`, and `dest` denoting three distinct nodes of the graph. Return the minimum weight of a subgraph of the graph such that it is possible to reach `dest` from both `src1` and `src2` via a set of edges of this subgraph. In case such a subgraph does not exist, return `-1`. A subgraph is a graph whose vertices and edges are subsets of the original graph. The weight of a subgraph is the sum of weights of its constituent edges.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minimumWeight(self, n: int, edges: List[List[int]], src1: int, src2: int, dest: int) -> int: graph = [[] for _ in range(n)] reversedGraph = [[] for _ in range(n)] for u, v, w in edges: graph[u].append((v, w)) reversedGraph[v].append((u, w)) fromSrc1 = self._dijkstra(graph, src1) fromSrc2 = self._dijkstra(graph, src2) fromDest = self._dijkstra(reversedGraph, dest) minWeight = min(a + b + c for a, b, c in zip(fromSrc1, fromSrc2, fromDest)) if minWeight == math.inf: return -1 else: return minWeight def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int) -> List[int]: dist = [math.inf] * len(graph) dist[src] = 0 minHeap = [(dist[src], src)] while minHeap: d, u = heapq.heappop(minHeap) if d > dist[u]: continue for v, w in graph[u]: if d + w < dist[v]: dist[v] = d + w heapq.heappush(minHeap, (dist[v], v)) return dist
class Solution { public long minimumWeight(int n, int[][] edges, int src1, int src2, int dest) { List<Pair<Integer, Integer>>[] graph = new List[n]; List<Pair<Integer, Integer>>[] reversedGraph = new List[n]; for (int i = 0; i < n; ++i) { graph[i] = new ArrayList<>(); reversedGraph[i] = new ArrayList<>(); } for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; final int w = edge[2]; graph[u].add(new Pair<>(v, w)); reversedGraph[v].add(new Pair<>(u, w)); } long[] fromSrc1 = dijkstra(graph, src1); long[] fromSrc2 = dijkstra(graph, src2); long[] fromDest = dijkstra(reversedGraph, dest); long ans = MAX; for (int i = 0; i < n; ++i) { if (fromSrc1[i] == MAX || fromSrc2[i] == MAX || fromDest[i] == MAX) continue; ans = Math.min(ans, fromSrc1[i] + fromSrc2[i] + fromDest[i]); } return ans == MAX ? -1 : ans; } private static long MAX = (long) 1e10; private long[] dijkstra(List<Pair<Integer, Integer>>[] graph, int src) { long[] dist = new long[graph.length]; Arrays.fill(dist, MAX); dist[src] = 0; Queue<Pair<Long, Integer>> minHeap = new PriorityQueue<>(Comparator.comparingLong(Pair::getKey)) { { offer(new Pair<>(dist[src], src)); // (d, u) } }; while (!minHeap.isEmpty()) { final long d = minHeap.peek().getKey(); final int u = minHeap.poll().getValue(); if (d > dist[u]) continue; for (Pair<Integer, Integer> pair : graph[u]) { final int v = pair.getKey(); final int w = pair.getValue(); if (d + w < dist[v]) { dist[v] = d + w; minHeap.offer(new Pair<>(dist[v], v)); } } } return dist; } }
class Solution { public: long long minimumWeight(int n, vector<vector<int>>& edges, int src1, int src2, int dest) { vector<vector<pair<int, int>>> graph(n); vector<vector<pair<int, int>>> reversedGraph(n); for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; const int w = edge[2]; graph[u].emplace_back(v, w); reversedGraph[v].emplace_back(u, w); } const vector<long> fromSrc1 = dijkstra(graph, src1); const vector<long> fromSrc2 = dijkstra(graph, src2); const vector<long> fromDest = dijkstra(reversedGraph, dest); long ans = kMax; for (int i = 0; i < n; ++i) { if (fromSrc1[i] == kMax || fromSrc2[i] == kMax || fromDest[i] == kMax) continue; ans = min(ans, fromSrc1[i] + fromSrc2[i] + fromDest[i]); } return ans == kMax ? -1 : ans; } private: static constexpr long kMax = 10'000'000'000; vector<long> dijkstra(const vector<vector<pair<int, int>>>& graph, int src) { vector<long> dist(graph.size(), kMax); dist[src] = 0; using P = pair<long, int>; // (d, u) priority_queue<P, vector<P>, greater<>> minHeap; minHeap.emplace(dist[src], src); while (!minHeap.empty()) { const auto [d, u] = minHeap.top(); minHeap.pop(); if (d > dist[u]) continue; for (const auto& [v, w] : graph[u]) if (d + w < dist[v]) { dist[v] = d + w; minHeap.emplace(dist[v], v); } } return dist; } };
2,242
Maximum Score of a Node Sequence
3
maximumScore
There is an undirected graph with `n` nodes, numbered from `0` to `n - 1`. You are given a 0-indexed integer array `scores` of length `n` where `scores[i]` denotes the score of node `i`. You are also given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an undirected edge connecting nodes `ai` and `bi`. A node sequence is valid if it meets the following conditions: * There is an edge connecting every pair of adjacent nodes in the sequence. * No node appears more than once in the sequence. The score of a node sequence is defined as the sum of the scores of the nodes in the sequence. Return the maximum score of a valid node sequence with a length of `4`. If no such sequence exists, return `-1`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int: n = len(scores) ans = -1 graph = [[] for _ in range(n)] for u, v in edges: graph[u].append((scores[v], v)) graph[v].append((scores[u], u)) for i in range(n): graph[i] = heapq.nlargest(3, graph[i]) for u, v in edges: for scoreA, a in graph[u]: for scoreB, b in graph[v]: if a != b and a != v and b != u: ans = max(ans, scoreA + scores[u] + scores[v] + scoreB) return ans
class Solution { public int maximumScore(int[] scores, int[][] edges) { final int n = scores.length; int ans = -1; Queue<Integer>[] graph = new Queue[n]; for (int i = 0; i < n; ++i) graph[i] = new PriorityQueue<>(Comparator.comparingInt(a -> scores[a])); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; graph[u].offer(v); graph[v].offer(u); if (graph[u].size() > 3) graph[u].poll(); if (graph[v].size() > 3) graph[v].poll(); } // To find the target sequence: a - u - v - b, enumerate each edge (u, v), // and find a (u's child) and b (v's child). That's why we find the 3 // children that have the highest scores because one of the 3 children is // guaranteed to be valid. for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; for (final int a : graph[u]) for (final int b : graph[v]) if (a != b && a != v && b != u) ans = Math.max(ans, scores[a] + scores[u] + scores[v] + scores[b]); } return ans; } }
class Solution { public: int maximumScore(vector<int>& scores, vector<vector<int>>& edges) { int ans = -1; vector<set<pair<int, int>>> graph(scores.size()); // {(score, node)} for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; graph[u].emplace(scores[v], v); graph[v].emplace(scores[u], u); if (graph[u].size() > 3) graph[u].erase(graph[u].begin()); if (graph[v].size() > 3) graph[v].erase(graph[v].begin()); } // To find the target sequence: a - u - v - b, enumerate each edge (u, v), // and find a (u's child) and b (v's child). That's why we find the 3 // children that have the highest scores because one of the 3 children is // guaranteed to be valid. for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; for (const auto& [scoreA, a] : graph[u]) for (const auto& [scoreB, b] : graph[v]) if (a != b && a != v && b != u) ans = max(ans, scoreA + scores[u] + scores[v] + scoreB); } return ans; } };
2,245
Maximum Trailing Zeros in a Cornered Path
2
maxTrailingZeros
You are given a 2D integer array `grid` of size `m x n`, where each cell contains a positive integer. A cornered path is defined as a set of adjacent cells with at most one turn. More specifically, the path should exclusively move either horizontally or vertically up to the turn (if there is one), without returning to a previously visited cell. After the turn, the path will then move exclusively in the alternate direction: move vertically if it moved horizontally, and vice versa, also without returning to a previously visited cell. The product of a path is defined as the product of all the values in the path. Return the maximum number of trailing zeros in the product of a cornered path found in `grid`. Note: * Horizontal movement means moving in either the left or right direction. * Vertical movement means moving in either the up or down direction.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def maxTrailingZeros(self, grid: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) leftPrefix2 = [[0] * n for _ in range(m)] leftPrefix5 = [[0] * n for _ in range(m)] topPrefix2 = [[0] * n for _ in range(m)] topPrefix5 = [[0] * n for _ in range(m)] def getCount(num: int, factor: int) -> int: count = 0 while num % factor == 0: num //= factor count += 1 return count for i in range(m): for j in range(n): leftPrefix2[i][j] = getCount(grid[i][j], 2) leftPrefix5[i][j] = getCount(grid[i][j], 5) if j: leftPrefix2[i][j] += leftPrefix2[i][j - 1] leftPrefix5[i][j] += leftPrefix5[i][j - 1] for j in range(n): for i in range(m): topPrefix2[i][j] = getCount(grid[i][j], 2) topPrefix5[i][j] = getCount(grid[i][j], 5) if i: topPrefix2[i][j] += topPrefix2[i - 1][j] topPrefix5[i][j] += topPrefix5[i - 1][j] ans = 0 for i in range(m): for j in range(n): curr2 = getCount(grid[i][j], 2) curr5 = getCount(grid[i][j], 5) l2 = leftPrefix2[i][j] l5 = leftPrefix5[i][j] r2 = leftPrefix2[i][n - 1] - (0 if j == 0 else leftPrefix2[i][j - 1]) r5 = leftPrefix5[i][n - 1] - (0 if j == 0 else leftPrefix5[i][j - 1]) t2 = topPrefix2[i][j] t5 = topPrefix5[i][j] d2 = topPrefix2[m - 1][j] - (0 if i == 0 else topPrefix2[i - 1][j]) d5 = topPrefix5[m - 1][j] - (0 if i == 0 else topPrefix5[i - 1][j]) ans = max(ans, min(l2 + t2 - curr2, l5 + t5 - curr5), min(r2 + t2 - curr2, r5 + t5 - curr5), min(l2 + d2 - curr2, l5 + d5 - curr5), min(r2 + d2 - curr2, r5 + d5 - curr5)) return ans
class Solution { public int maxTrailingZeros(int[][] grid) { final int m = grid.length; final int n = grid[0].length; // leftPrefix2[i][j] := the number of 2 in grid[i][0..j] // leftPrefix5[i][j] := the number of 5 in grid[i][0..j] // topPrefix2[i][j] := the number of 2 in grid[0..i][j] // topPrefix5[i][j] := the number of 5 in grid[0..i][j] int[][] leftPrefix2 = new int[m][n]; int[][] leftPrefix5 = new int[m][n]; int[][] topPrefix2 = new int[m][n]; int[][] topPrefix5 = new int[m][n]; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { leftPrefix2[i][j] = getCount(grid[i][j], 2); leftPrefix5[i][j] = getCount(grid[i][j], 5); if (j > 0) { leftPrefix2[i][j] += leftPrefix2[i][j - 1]; leftPrefix5[i][j] += leftPrefix5[i][j - 1]; } } for (int j = 0; j < n; ++j) for (int i = 0; i < m; ++i) { topPrefix2[i][j] = getCount(grid[i][j], 2); topPrefix5[i][j] = getCount(grid[i][j], 5); if (i > 0) { topPrefix2[i][j] += topPrefix2[i - 1][j]; topPrefix5[i][j] += topPrefix5[i - 1][j]; } } int ans = 0; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { final int curr2 = getCount(grid[i][j], 2); final int curr5 = getCount(grid[i][j], 5); final int l2 = leftPrefix2[i][j]; final int l5 = leftPrefix5[i][j]; final int r2 = leftPrefix2[i][n - 1] - (j > 0 ? leftPrefix2[i][j - 1] : 0); final int r5 = leftPrefix5[i][n - 1] - (j > 0 ? leftPrefix5[i][j - 1] : 0); final int t2 = topPrefix2[i][j]; final int t5 = topPrefix5[i][j]; final int d2 = topPrefix2[m - 1][j] - (i > 0 ? topPrefix2[i - 1][j] : 0); final int d5 = topPrefix5[m - 1][j] - (i > 0 ? topPrefix5[i - 1][j] : 0); ans = Math.max(ans, Math.max(Math.max(Math.min(l2 + t2 - curr2, l5 + t5 - curr5), Math.min(r2 + t2 - curr2, r5 + t5 - curr5)), Math.max(Math.min(l2 + d2 - curr2, l5 + d5 - curr5), Math.min(r2 + d2 - curr2, r5 + d5 - curr5)))); } return ans; } private int getCount(int num, int factor) { int count = 0; while (num % factor == 0) { num /= factor; ++count; } return count; } }
class Solution { public: int maxTrailingZeros(vector<vector<int>>& grid) { const int m = grid.size(); const int n = grid[0].size(); // leftPrefix2[i][j] := the number of 2 in grid[i][0..j] // leftPrefix5[i][j] := the number of 5 in grid[i][0..j] // topPrefix2[i][j] := the number of 2 in grid[0..i][j] // topPrefix5[i][j] := the number of 5 in grid[0..i][j] vector<vector<int>> leftPrefix2(m, vector<int>(n)); vector<vector<int>> leftPrefix5(m, vector<int>(n)); vector<vector<int>> topPrefix2(m, vector<int>(n)); vector<vector<int>> topPrefix5(m, vector<int>(n)); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { leftPrefix2[i][j] = getCount(grid[i][j], 2); leftPrefix5[i][j] = getCount(grid[i][j], 5); if (j > 0) { leftPrefix2[i][j] += leftPrefix2[i][j - 1]; leftPrefix5[i][j] += leftPrefix5[i][j - 1]; } } for (int j = 0; j < n; ++j) for (int i = 0; i < m; ++i) { topPrefix2[i][j] = getCount(grid[i][j], 2); topPrefix5[i][j] = getCount(grid[i][j], 5); if (i > 0) { topPrefix2[i][j] += topPrefix2[i - 1][j]; topPrefix5[i][j] += topPrefix5[i - 1][j]; } } int ans = 0; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { const int curr2 = getCount(grid[i][j], 2); const int curr5 = getCount(grid[i][j], 5); const int l2 = leftPrefix2[i][j]; const int l5 = leftPrefix5[i][j]; const int r2 = leftPrefix2[i][n - 1] - (j ? leftPrefix2[i][j - 1] : 0); const int r5 = leftPrefix5[i][n - 1] - (j ? leftPrefix5[i][j - 1] : 0); const int t2 = topPrefix2[i][j]; const int t5 = topPrefix5[i][j]; const int d2 = topPrefix2[m - 1][j] - (i ? topPrefix2[i - 1][j] : 0); const int d5 = topPrefix5[m - 1][j] - (i ? topPrefix5[i - 1][j] : 0); ans = max({ans, min(l2 + t2 - curr2, l5 + t5 - curr5), min(r2 + t2 - curr2, r5 + t5 - curr5), min(l2 + d2 - curr2, l5 + d5 - curr5), min(r2 + d2 - curr2, r5 + d5 - curr5)}); } return ans; } private: int getCount(int num, int factor) { int count = 0; while (num % factor == 0) { num /= factor; ++count; } return count; } };
2,257
Count Unguarded Cells in the Grid
2
countUnguarded
You are given two integers `m` and `n` representing a 0-indexed `m x n` grid. You are also given two 2D integer arrays `guards` and `walls` where `guards[i] = [rowi, coli]` and `walls[j] = [rowj, colj]` represent the positions of the `ith` guard and `jth` wall respectively. A guard can see every cell in the four cardinal directions (north, east, south, or west) starting from their position unless obstructed by a wall or another guard. A cell is guarded if there is at least one guard that can see it. Return the number of unoccupied cells that are not guarded.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def countUnguarded(self, m: int, n: int, guards: List[List[int]], walls: List[List[int]]) -> int: ans = 0 grid = [[0] * n for _ in range(m)] left = [[0] * n for _ in range(m)] right = [[0] * n for _ in range(m)] up = [[0] * n for _ in range(m)] down = [[0] * n for _ in range(m)] for row, col in guards: grid[row][col] = 'G' for row, col in walls: grid[row][col] = 'W' for i in range(m): lastCell = 0 for j in range(n): if grid[i][j] == 'G' or grid[i][j] == 'W': lastCell = grid[i][j] else: left[i][j] = lastCell lastCell = 0 for j in range(n - 1, -1, -1): if grid[i][j] == 'G' or grid[i][j] == 'W': lastCell = grid[i][j] else: right[i][j] = lastCell for j in range(n): lastCell = 0 for i in range(m): if grid[i][j] == 'G' or grid[i][j] == 'W': lastCell = grid[i][j] else: up[i][j] = lastCell lastCell = 0 for i in range(m - 1, -1, -1): if grid[i][j] == 'G' or grid[i][j] == 'W': lastCell = grid[i][j] else: down[i][j] = lastCell for i in range(m): for j in range(n): if grid[i][j] == 0 and left[i][j] != 'G' and right[i][j] != 'G' and up[i][j] != 'G' and down[i][j] != 'G': ans += 1 return ans
class Solution { public int countUnguarded(int m, int n, int[][] guards, int[][] walls) { int ans = 0; char[][] grid = new char[m][n]; char[][] left = new char[m][n]; char[][] right = new char[m][n]; char[][] up = new char[m][n]; char[][] down = new char[m][n]; for (int[] guard : guards) grid[guard[0]][guard[1]] = 'G'; for (int[] wall : walls) grid[wall[0]][wall[1]] = 'W'; for (int i = 0; i < m; ++i) { char lastCell = 0; for (int j = 0; j < n; ++j) if (grid[i][j] == 'G' || grid[i][j] == 'W') lastCell = grid[i][j]; else left[i][j] = lastCell; lastCell = 0; for (int j = n - 1; j >= 0; --j) if (grid[i][j] == 'G' || grid[i][j] == 'W') lastCell = grid[i][j]; else right[i][j] = lastCell; } for (int j = 0; j < n; ++j) { char lastCell = 0; for (int i = 0; i < m; ++i) if (grid[i][j] == 'G' || grid[i][j] == 'W') lastCell = grid[i][j]; else up[i][j] = lastCell; lastCell = 0; for (int i = m - 1; i >= 0; --i) if (grid[i][j] == 'G' || grid[i][j] == 'W') lastCell = grid[i][j]; else down[i][j] = lastCell; } for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 0 && left[i][j] != 'G' && right[i][j] != 'G' && up[i][j] != 'G' && down[i][j] != 'G') ++ans; return ans; } }
class Solution { public: int countUnguarded(int m, int n, vector<vector<int>>& guards, vector<vector<int>>& walls) { int ans = 0; vector<vector<char>> grid(m, vector<char>(n)); vector<vector<char>> left(m, vector<char>(n)); vector<vector<char>> right(m, vector<char>(n)); vector<vector<char>> up(m, vector<char>(n)); vector<vector<char>> down(m, vector<char>(n)); for (const vector<int>& guard : guards) grid[guard[0]][guard[1]] = 'G'; for (const vector<int>& wall : walls) grid[wall[0]][wall[1]] = 'W'; for (int i = 0; i < m; ++i) { char lastCell = 0; for (int j = 0; j < n; ++j) recordOrFill(grid[i][j], lastCell, left[i][j]); lastCell = 0; for (int j = n - 1; j >= 0; --j) recordOrFill(grid[i][j], lastCell, right[i][j]); } for (int j = 0; j < n; ++j) { char lastCell = 0; for (int i = 0; i < m; ++i) recordOrFill(grid[i][j], lastCell, up[i][j]); lastCell = 0; for (int i = m - 1; i >= 0; --i) recordOrFill(grid[i][j], lastCell, down[i][j]); } for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 0 && left[i][j] != 'G' && right[i][j] != 'G' && up[i][j] != 'G' && down[i][j] != 'G') ++ans; return ans; } private: void recordOrFill(char currCell, char& lastCell, char& infoCell) { if (currCell == 'G' || currCell == 'W') lastCell = currCell; else infoCell = lastCell; } };
2,258
Escape the Spreading Fire
3
maximumMinutes
You are given a 0-indexed 2D integer array `grid` of size `m x n` which represents a field. Each cell has one of three values: * `0` represents grass, * `1` represents fire, * `2` represents a wall that you and fire cannot pass through. You are situated in the top-left cell, `(0, 0)`, and you want to travel to the safehouse at the bottom-right cell, `(m - 1, n - 1)`. Every minute, you may move to an adjacent grass cell. After your move, every fire cell will spread to all adjacent cells that are not walls. Return the maximum number of minutes that you can stay in your initial position before moving while still safely reaching the safehouse. If this is impossible, return `-1`. If you can always reach the safehouse regardless of the minutes stayed, return `109`. Note that even if the fire spreads to the safehouse immediately after you have reached it, it will be counted as safely reaching the safehouse. A cell is adjacent to another cell if the former is directly north, east, south, or west of the latter (i.e., their sides are touching).
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def maximumMinutes(self, grid: List[List[int]]) -> int: dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) kMax = len(grid) * len(grid[0]) fireGrid = [[-1] * len(grid[0]) for _ in range(len(grid))] self._buildFireGrid(grid, fireGrid, dirs) ans = -1 l = 0 r = kMax while l <= r: m = (l + r) // 2 if self._canStayFor(grid, fireGrid, m, dirs): ans = m l = m + 1 else: r = m - 1 return int(1e9) if ans == kMax else ans def _buildFireGrid(self, grid: List[List[int]], fireMinute: List[List[int]], dirs: List[int]) -> None: minuteFromFire = 0 q = collections.deque() for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == 1: q.append((i, j)) fireMinute[i][j] = 0 while q: minuteFromFire += 1 for _ in range(len(q)): i, j = q.popleft() for dx, dy in dirs: x = i + dx y = j + dy if x < 0 or x == len(grid) or y < 0 or y == len(grid[0]): continue if grid[x][y] == 2: continue if fireMinute[x][y] != -1: continue fireMinute[x][y] = minuteFromFire q.append((x, y)) def _canStayFor(self, grid: List[List[int]], fireMinute: List[List[int]], minute: int, dirs: List[int]) -> bool: q = collections.deque([(0, 0)]) seen = {(0, 0)} while q: minute += 1 for _ in range(len(q)): i, j = q.popleft() for dx, dy in dirs: x = i + dx y = j + dy if x < 0 or x == len(grid) or y < 0 or y == len(grid[0]): continue if grid[x][y] == 2: continue if x == len(grid) - 1 and y == len(grid[0]) - 1: if fireMinute[x][y] != -1 and fireMinute[x][y] < minute: continue return True if fireMinute[x][y] != -1 and fireMinute[x][y] <= minute: continue if (x, y) in seen: continue q.append((x, y)) seen.add((x, y)) return False
class Solution { public int maximumMinutes(int[][] grid) { final int MAX = grid.length * grid[0].length; int[][] fireMinute = new int[grid.length][grid[0].length]; Arrays.stream(fireMinute).forEach(A -> Arrays.fill(A, -1)); buildFireGrid(grid, fireMinute); int ans = -1; int l = 0; int r = MAX; while (l <= r) { final int m = (l + r) / 2; if (canStayFor(grid, fireMinute, m)) { ans = m; l = m + 1; } else { r = m - 1; } } return ans == MAX ? 1_000_000_000 : ans; } private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; private void buildFireGrid(int[][] grid, int[][] fireMinute) { Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(); for (int i = 0; i < grid.length; ++i) for (int j = 0; j < grid[0].length; ++j) if (grid[i][j] == 1) { // the fire q.offer(new Pair<>(i, j)); fireMinute[i][j] = 0; } for (int minuteFromFire = 1; !q.isEmpty(); ++minuteFromFire) for (int sz = q.size(); sz > 0; --sz) { final int i = q.peek().getKey(); final int j = q.poll().getValue(); for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == grid.length || y < 0 || y == grid[0].length) continue; if (grid[x][y] == 2) // the wall continue; if (fireMinute[x][y] != -1) continue; fireMinute[x][y] = minuteFromFire; q.offer(new Pair<>(x, y)); } } } boolean canStayFor(int[][] grid, int[][] fireMinute, int minute) { Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(0, 0))); // the start position boolean[][] seen = new boolean[grid.length][grid[0].length]; seen[0][0] = true; while (!q.isEmpty()) { ++minute; for (int sz = q.size(); sz > 0; --sz) { final int i = q.peek().getKey(); final int j = q.poll().getValue(); for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == grid.length || y < 0 || y == grid[0].length) continue; if (grid[x][y] == 2) // the wall continue; if (x == grid.length - 1 && y == grid[0].length - 1) { if (fireMinute[x][y] != -1 && fireMinute[x][y] < minute) continue; return true; } if (fireMinute[x][y] != -1 && fireMinute[x][y] <= minute) continue; if (seen[x][y]) continue; q.offer(new Pair<>(x, y)); seen[x][y] = true; } } } return false; } }
class Solution { public: int maximumMinutes(vector<vector<int>>& grid) { const int kMax = grid.size() * grid[0].size(); vector<vector<int>> fireMinute(grid.size(), vector<int>(grid[0].size(), -1)); buildFireGrid(grid, fireMinute); int ans = -1; int l = 0; int r = kMax; while (l <= r) { const int m = (l + r) / 2; if (canStayFor(grid, fireMinute, m)) { ans = m; l = m + 1; } else { r = m - 1; } } return ans == kMax ? 1'000'000'000 : ans; } private: static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; void buildFireGrid(const vector<vector<int>>& grid, vector<vector<int>>& fireMinute) { queue<pair<int, int>> q; for (int i = 0; i < grid.size(); ++i) for (int j = 0; j < grid[0].size(); ++j) if (grid[i][j] == 1) { // the fire q.emplace(i, j); fireMinute[i][j] = 0; } for (int minuteFromFire = 1; !q.empty(); ++minuteFromFire) for (int sz = q.size(); sz > 0; --sz) { const auto [i, j] = q.front(); q.pop(); for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == grid.size() || y < 0 || y == grid[0].size()) continue; if (grid[x][y] == 2) // the wall continue; if (fireMinute[x][y] != -1) continue; fireMinute[x][y] = minuteFromFire; q.emplace(x, y); } } } bool canStayFor(const vector<vector<int>>& grid, const vector<vector<int>>& fireMinute, int minute) { queue<pair<int, int>> q{{{0, 0}}}; // the start position vector<vector<bool>> seen(grid.size(), vector<bool>(grid[0].size())); seen[0][0] = true; while (!q.empty()) { ++minute; for (int sz = q.size(); sz > 0; --sz) { const auto [i, j] = q.front(); q.pop(); for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == grid.size() || y < 0 || y == grid[0].size()) continue; if (grid[x][y] == 2) // the wall continue; if (x == grid.size() - 1 && y == grid[0].size() - 1) { if (fireMinute[x][y] != -1 && fireMinute[x][y] < minute) continue; return true; } if (fireMinute[x][y] != -1 && fireMinute[x][y] <= minute) continue; if (seen[x][y]) continue; q.emplace(x, y); seen[x][y] = true; } } } return false; } };
2,290
Minimum Obstacle Removal to Reach Corner
3
minimumObstacles
You are given a 0-indexed 2D integer array `grid` of size `m x n`. Each cell has one of two values: * `0` represents an empty cell, * `1` represents an obstacle that may be removed. You can move up, down, left, or right from and to an empty cell. Return the minimum number of obstacles to remove so you can move from the upper left corner `(0, 0)` to the lower right corner `(m - 1, n - 1)`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minimumObstacles(self, grid: List[List[int]]) -> int: dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) m = len(grid) n = len(grid[0]) minHeap = [(grid[0][0], 0, 0)] # (d, i, j) dist = [[math.inf] * n for _ in range(m)] dist[0][0] = grid[0][0] while minHeap: d, i, j = heapq.heappop(minHeap) if i == m - 1 and j == n - 1: return d for dx, dy in dirs: x = i + dx y = j + dy if x < 0 or x == m or y < 0 or y == n: continue newDist = d + grid[i][j] if newDist < dist[x][y]: dist[x][y] = newDist heapq.heappush(minHeap, (newDist, x, y)) return dist[m - 1][n - 1]
class Solution { public int minimumObstacles(int[][] grid) { final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; final int m = grid.length; final int n = grid[0].length; Queue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])) { { offer(new int[] {grid[0][0], 0, 0}); } // (d, i, j) }; int[][] dist = new int[m][n]; Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); dist[0][0] = grid[0][0]; while (!minHeap.isEmpty()) { final int d = minHeap.peek()[0]; final int i = minHeap.peek()[1]; final int j = minHeap.poll()[2]; if (i == m - 1 && j == n - 1) return d; for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == m || y < 0 || y == n) continue; final int newDist = d + grid[i][j]; if (newDist < dist[x][y]) { dist[x][y] = newDist; minHeap.offer(new int[] {newDist, x, y}); } } } return dist[m - 1][n - 1]; } }
class Solution { public: int minimumObstacles(vector<vector<int>>& grid) { const int m = grid.size(); const int n = grid[0].size(); constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; using T = tuple<int, int, int>; // (d, i, j) priority_queue<T, vector<T>, greater<>> minHeap; vector<vector<int>> dist(m, vector<int>(n, INT_MAX)); minHeap.emplace(grid[0][0], 0, 0); dist[0][0] = grid[0][0]; while (!minHeap.empty()) { const auto [d, i, j] = minHeap.top(); minHeap.pop(); if (i == m - 1 && j == n - 1) return d; for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == m || y < 0 || y == n) continue; const int newDist = d + grid[i][j]; if (newDist < dist[x][y]) { dist[x][y] = newDist; minHeap.emplace(newDist, x, y); } } } return dist[m - 1][n - 1]; } };
2,299
Strong Password Checker II
1
strongPasswordCheckerII
A password is said to be strong if it satisfies all the following criteria: * It has at least `8` characters. * It contains at least one lowercase letter. * It contains at least one uppercase letter. * It contains at least one digit. * It contains at least one special character. The special characters are the characters in the following string: `"!@#$%^&*()-+"`. * It does not contain `2` of the same character in adjacent positions (i.e., `"aab"` violates this condition, but `"aba"` does not). Given a string `password`, return `true` if it is a strong password. Otherwise, return `false`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def strongPasswordCheckerII(self, password: str) -> bool: if len(password) < 8: return False if not any(c.islower() for c in password): return False if not any(c.isupper() for c in password): return False if not any(c.isdigit() for c in password): return False if not any("!@#$%^&*()-+".find(c) != -1 for c in password): return False return all(a != b for a, b in zip(password, password[1:]))
class Solution { public boolean strongPasswordCheckerII(String password) { if (password.length() < 8) return false; final boolean hasLowerCase = password.chars().anyMatch(c -> Character.isLowerCase(c)); if (!hasLowerCase) return false; final boolean hasUpperCase = password.chars().anyMatch(c -> Character.isUpperCase(c)); if (!hasUpperCase) return false; final boolean hasDigit = password.chars().anyMatch(c -> Character.isDigit(c)); if (!hasDigit) return false; final boolean hasSpecial = password.chars().anyMatch(c -> "!@#$%^&*()-+".indexOf(c) != -1); if (!hasSpecial) return false; for (int i = 1; i < password.length(); ++i) if (password.charAt(i) == password.charAt(i - 1)) return false; return true; } }
class Solution { public: bool strongPasswordCheckerII(string password) { if (password.length() < 8) return false; const bool hasLowerCase = ranges::any_of(password, [](const char c) { return islower(c); }); if (!hasLowerCase) return false; const bool hasUpperCase = ranges::any_of(password, [](const char c) { return isupper(c); }); if (!hasUpperCase) return false; const bool hasDigit = ranges::any_of(password, [](const char c) { return isdigit(c); }); if (!hasDigit) return false; const bool hasSpecial = ranges::any_of(password, [](const char c) { return string("!@#$%^&*()-+").find(c) != string::npos; }); if (!hasSpecial) return false; for (int i = 1; i < password.length(); ++i) if (password[i] == password[i - 1]) return false; return true; } };
2,301
Match Substring After Replacement
3
matchReplacement
You are given two strings `s` and `sub`. You are also given a 2D character array `mappings` where `mappings[i] = [oldi, newi]` indicates that you may perform the following operation any number of times: * Replace a character `oldi` of `sub` with `newi`. Each character in `sub` cannot be replaced more than once. Return `true` if it is possible to make `sub` a substring of `s` by replacing zero or more characters according to `mappings`. Otherwise, return `false`. A substring is a contiguous non-empty sequence of characters within a string.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def matchReplacement(self, s: str, sub: str, mappings: List[List[str]]) -> bool: isMapped = [[False] * 128 for _ in range(128)] for old, new in mappings: isMapped[ord(old)][ord(new)] = True for i in range(len(s)): if self._canTransform(s, i, sub, isMapped): return True return False def _canTransform(self, s: str, start: int, sub: str, isMapped: List[List[bool]]) -> bool: if start + len(sub) > len(s): return False for i in range(len(sub)): a = sub[i] b = s[start + i] if a != b and not isMapped[ord(a)][ord(b)]: return False return True
class Solution { public boolean matchReplacement(String s, String sub, char[][] mappings) { boolean[][] isMapped = new boolean[128][128]; for (char[] m : mappings) { final char old = m[0]; final char _new = m[1]; isMapped[old][_new] = true; } for (int i = 0; i < s.length(); ++i) if (canTransform(s, i, sub, isMapped)) return true; return false; } private boolean canTransform(final String s, int start, final String sub, boolean[][] isMapped) { if (start + sub.length() > s.length()) return false; for (int i = 0; i < sub.length(); ++i) { final char a = sub.charAt(i); final char b = s.charAt(start + i); if (a != b && !isMapped[a][b]) return false; } return true; } }
class Solution { public: bool matchReplacement(string s, string sub, vector<vector<char>>& mappings) { vector<vector<bool>> isMapped(128, vector<bool>(128)); for (const vector<char>& m : mappings) { const char old = m[0]; const char _new = m[1]; isMapped[old][_new] = true; } for (int i = 0; i < s.length(); ++i) if (canTransform(s, i, sub, isMapped)) return true; return false; } private: bool canTransform(const string& s, int start, const string& sub, const vector<vector<bool>>& isMapped) { if (start + sub.length() > s.length()) return false; for (int i = 0; i < sub.length(); ++i) { const char a = sub[i]; const char b = s[start + i]; if (a != b && !isMapped[a][b]) return false; } return true; } };
2,322
Minimum Score After Removals on a Tree
3
minimumScore
There is an undirected connected tree with `n` nodes labeled from `0` to `n - 1` and `n - 1` edges. You are given a 0-indexed integer array `nums` of length `n` where `nums[i]` represents the value of the `ith` node. You are also given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. Remove two distinct edges of the tree to form three connected components. For a pair of removed edges, the following steps are defined: 1. Get the XOR of all the values of the nodes for each of the three components respectively. 2. The difference between the largest XOR value and the smallest XOR value is the score of the pair. * For example, say the three components have the node values: `[4,5,7]`, `[1,9]`, and `[3,3,3]`. The three XOR values are `4 ^ 5 ^ 7 = 6`, `1 ^ 9 = 8`, and `3 ^ 3 ^ 3 = 3`. The largest XOR value is `8` and the smallest XOR value is `3`. The score is then `8 - 3 = 5`. Return the minimum score of any possible pair of edge removals on the given tree.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator, Set class Solution: def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int: n = len(nums) xors = functools.reduce(lambda x, y: x ^ y, nums) subXors = nums[:] tree = [[] for _ in range(n)] children = [{i} for i in range(n)] for u, v in edges: tree[u].append(v) tree[v].append(u) def dfs(u: int, parent: int) -> Tuple[int, Set[int]]: for v in tree[u]: if v == parent: continue vXor, vChildren = dfs(v, u) subXors[u] ^= vXor children[u] |= vChildren return subXors[u], children[u] dfs(0, -1) ans = math.inf for i in range(len(edges)): a, b = edges[i] if b in children[a]: a, b = b, a for j in range(i): c, d = edges[j] if d in children[c]: c, d = d, c if c in children[a] and a != c: cands = [subXors[c], subXors[a] ^ subXors[c], xors ^ subXors[a]] elif a in children[c] and a != c: cands = [subXors[a], subXors[c] ^ subXors[a], xors ^ subXors[c]] else: cands = [subXors[a], subXors[c], xors ^ subXors[a] ^ subXors[c]] ans = min(ans, max(cands) - min(cands)) return ans
class Solution { public int minimumScore(int[] nums, int[][] edges) { final int n = nums.length; final int xors = getXors(nums); int[] subXors = nums.clone(); List<Integer>[] tree = new List[n]; Set<Integer>[] children = new Set[n]; for (int i = 0; i < n; ++i) tree[i] = new ArrayList<>(); for (int i = 0; i < n; ++i) children[i] = new HashSet<>(Arrays.asList(i)); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; tree[u].add(v); tree[v].add(u); } dfs(tree, 0, -1, subXors, children); int ans = Integer.MAX_VALUE; for (int i = 0; i < edges.length; ++i) { int a = edges[i][0]; int b = edges[i][1]; if (children[a].contains(b)) { final int temp = a; a = b; b = a; } for (int j = 0; j < i; ++j) { int c = edges[j][0]; int d = edges[j][1]; if (children[c].contains(d)) { final int temp = c; c = d; d = temp; } int[] cands; if (a != c && children[a].contains(c)) cands = new int[] {subXors[c], subXors[a] ^ subXors[c], xors ^ subXors[a]}; else if (a != c && children[c].contains(a)) cands = new int[] {subXors[a], subXors[c] ^ subXors[a], xors ^ subXors[c]}; else cands = new int[] {subXors[a], subXors[c], xors ^ subXors[a] ^ subXors[c]}; ans = Math.min(ans, Arrays.stream(cands).max().getAsInt() - Arrays.stream(cands).min().getAsInt()); } } return ans; } private Pair<Integer, Set<Integer>> dfs(List<Integer>[] tree, int u, int prev, int[] subXors, Set<Integer>[] children) { for (final int v : tree[u]) { if (v == prev) continue; final Pair<Integer, Set<Integer>> pair = dfs(tree, v, u, subXors, children); final int vXor = pair.getKey(); final Set<Integer> vChildren = pair.getValue(); subXors[u] ^= vXor; for (final int child : vChildren) children[u].add(child); } return new Pair<>(subXors[u], children[u]); } private int getXors(int[] nums) { int xors = 0; for (final int num : nums) xors ^= num; return xors; } }
class Solution { public: int minimumScore(vector<int>& nums, vector<vector<int>>& edges) { const int n = nums.size(); const int xors = reduce(nums.begin(), nums.end(), 0, bit_xor()); vector<int> subXors(nums); vector<vector<int>> tree(n); vector<unordered_set<int>> children(n); for (int i = 0; i < n; ++i) children[i].insert(i); for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; tree[u].push_back(v); tree[v].push_back(u); } dfs(tree, 0, -1, subXors, children); int ans = INT_MAX; for (int i = 0; i < edges.size(); ++i) { int a = edges[i][0]; int b = edges[i][1]; if (children[a].contains(b)) swap(a, b); for (int j = 0; j < i; ++j) { int c = edges[j][0]; int d = edges[j][1]; if (children[c].contains(d)) swap(c, d); vector<int> cands; if (a != c && children[a].contains(c)) cands = {subXors[c], subXors[a] ^ subXors[c], xors ^ subXors[a]}; else if (a != c && children[c].contains(a)) cands = {subXors[a], subXors[c] ^ subXors[a], xors ^ subXors[c]}; else cands = {subXors[a], subXors[c], xors ^ subXors[a] ^ subXors[c]}; ans = min(ans, ranges::max(cands) - ranges::min(cands)); } } return ans; } private: pair<int, unordered_set<int>> dfs(const vector<vector<int>>& tree, int u, int prev, vector<int>& subXors, vector<unordered_set<int>>& children) { for (const int v : tree[u]) { if (v == prev) continue; const auto& [vXor, vChildren] = dfs(tree, v, u, subXors, children); subXors[u] ^= vXor; children[u].insert(vChildren.begin(), vChildren.end()); } return {subXors[u], children[u]}; } };
2,332
The Latest Time to Catch a Bus
2
latestTimeCatchTheBus
You are given a 0-indexed integer array `buses` of length `n`, where `buses[i]` represents the departure time of the `ith` bus. You are also given a 0-indexed integer array `passengers` of length `m`, where `passengers[j]` represents the arrival time of the `jth` passenger. All bus departure times are unique. All passenger arrival times are unique. You are given an integer `capacity`, which represents the maximum number of passengers that can get on each bus. When a passenger arrives, they will wait in line for the next available bus. You can get on a bus that departs at `x` minutes if you arrive at `y` minutes where `y <= x`, and the bus is not full. Passengers with the earliest arrival times get on the bus first. More formally when a bus arrives, either: * If `capacity` or fewer passengers are waiting for a bus, they will all get on the bus, or * The `capacity` passengers with the earliest arrival times will get on the bus. Return the latest time you may arrive at the bus station to catch a bus. You cannot arrive at the same time as another passenger. Note: The arrays `buses` and `passengers` are not necessarily sorted.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def latestTimeCatchTheBus(self, buses: List[int], passengers: List[int], capacity: int) -> int: buses.sort() passengers.sort() if passengers[0] > buses[-1]: return buses[-1] ans = passengers[0] - 1 i = 0 j = 0 while i < len(buses): arrived = 0 while arrived < capacity and j < len(passengers) and passengers[j] <= buses[i]: if j > 0 and passengers[j] != passengers[j - 1] + 1: ans = passengers[j] - 1 j += 1 arrived += 1 if arrived < capacity and j > 0 and passengers[j - 1] != buses[i]: ans = buses[i] i += 1 return ans
class Solution { public int latestTimeCatchTheBus(int[] buses, int[] passengers, int capacity) { Arrays.sort(buses); Arrays.sort(passengers); if (passengers[0] > buses[buses.length - 1]) return buses[buses.length - 1]; int ans = passengers[0] - 1; int i = 0; // buses' index int j = 0; // passengers' index while (i < buses.length) { // Greedily make passengers catch `buses[i]`. int arrived = 0; while (arrived < capacity && j < passengers.length && passengers[j] <= buses[i]) { if (j > 0 && passengers[j] != passengers[j - 1] + 1) ans = passengers[j] - 1; ++j; ++arrived; } // There's room for `buses[i]` to carry a passenger arriving at the // `buses[i]`. if (arrived < capacity && j > 0 && passengers[j - 1] != buses[i]) ans = buses[i]; ++i; } return ans; } }
class Solution { public: int latestTimeCatchTheBus(vector<int>& buses, vector<int>& passengers, int capacity) { ranges::sort(buses); ranges::sort(passengers); if (passengers.front() > buses.back()) return buses.back(); int ans = passengers[0] - 1; int i = 0; // buses' index int j = 0; // passengers' index while (i < buses.size()) { // Greedily make passengers catch `buses[i]`. int arrived = 0; while (arrived < capacity && j < passengers.size() && passengers[j] <= buses[i]) { if (j > 0 && passengers[j] != passengers[j - 1] + 1) ans = passengers[j] - 1; ++j; ++arrived; } // There's room for `buses[i]` to carry a passenger arriving at // `buses[i]`. if (arrived < capacity && j > 0 && passengers[j - 1] != buses[i]) ans = buses[i]; ++i; } return ans; } };
2,337
Move Pieces to Obtain a String
2
canChange
You are given two strings `start` and `target`, both of length `n`. Each string consists only of the characters `'L'`, `'R'`, and `'_'` where: * The characters `'L'` and `'R'` represent pieces, where a piece `'L'` can move to the left only if there is a blank space directly to its left, and a piece `'R'` can move to the right only if there is a blank space directly to its right. * The character `'_'` represents a blank space that can be occupied by any of the `'L'` or `'R'` pieces. Return `true` if it is possible to obtain the string `target` by moving the pieces of the string `start` any number of times. Otherwise, return `false`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def canChange(self, start: str, target: str) -> bool: n = len(start) i = 0 j = 0 while i <= n and j <= n: while i < n and start[i] == '_': i += 1 while j < n and target[j] == '_': j += 1 if i == n or j == n: return i == n and j == n if start[i] != target[j]: return False if start[i] == 'R' and i > j: return False if start[i] == 'L' and i < j: return False i += 1 j += 1 return True
class Solution { public boolean canChange(String start, String target) { final int n = start.length(); int i = 0; // start's index int j = 0; // target's index while (i <= n && j <= n) { while (i < n && start.charAt(i) == '_') ++i; while (j < n && target.charAt(j) == '_') ++j; if (i == n || j == n) return i == n && j == n; if (start.charAt(i) != target.charAt(j)) return false; if (start.charAt(i) == 'R' && i > j) return false; if (start.charAt(i) == 'L' && i < j) return false; ++i; ++j; } return true; } }
class Solution { public: bool canChange(string start, string target) { const int n = start.length(); int i = 0; // start's index int j = 0; // target's index while (i <= n && j <= n) { while (i < n && start[i] == '_') ++i; while (j < n && target[j] == '_') ++j; if (i == n || j == n) return i == n && j == n; if (start[i] != target[j]) return false; if (start[i] == 'R' && i > j) return false; if (start[i] == 'L' && i < j) return false; ++i; ++j; } return true; } };
2,392
Build a Matrix With Conditions
3
buildMatrix
You are given a positive integer `k`. You are also given: * a 2D integer array `rowConditions` of size `n` where `rowConditions[i] = [abovei, belowi]`, and * a 2D integer array `colConditions` of size `m` where `colConditions[i] = [lefti, righti]`. The two arrays contain integers from `1` to `k`. You have to build a `k x k` matrix that contains each of the numbers from `1` to `k` exactly once. The remaining cells should have the value `0`. The matrix should also satisfy the following conditions: * The number `abovei` should appear in a row that is strictly above the row at which the number `belowi` appears for all `i` from `0` to `n - 1`. * The number `lefti` should appear in a column that is strictly left of the column at which the number `righti` appears for all `i` from `0` to `m - 1`. Return any matrix that satisfies the conditions. If no answer exists, return an empty matrix.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def buildMatrix(self, k: int, rowConditions: List[List[int]], colConditions: List[List[int]]) -> List[List[int]]: rowOrder = self._topologicalSort(rowConditions, k) if not rowOrder: return [] colOrder = self._topologicalSort(colConditions, k) if not colOrder: return [] ans = [[0] * k for _ in range(k)] nodeToRowIndex = [0] * (k + 1) for i, node in enumerate(rowOrder): nodeToRowIndex[node] = i for j, node in enumerate(colOrder): i = nodeToRowIndex[node] ans[i][j] = node return ans def _topologicalSort(self, conditions: List[List[int]], n: int) -> List[int]: order = [] graph = [[] for _ in range(n + 1)] inDegrees = [0] * (n + 1) for u, v in conditions: graph[u].append(v) inDegrees[v] += 1 q = collections.deque([i for i in range(1, n + 1) if inDegrees[i] == 0]) while q: u = q.popleft() order.append(u) for v in graph[u]: inDegrees[v] -= 1 if inDegrees[v] == 0: q.append(v) if len(order) == n: return order else: return []
class Solution { public int[][] buildMatrix(int k, int[][] rowConditions, int[][] colConditions) { List<Integer> rowOrder = topologicalSort(rowConditions, k); if (rowOrder.isEmpty()) return new int[][] {}; List<Integer> colOrder = topologicalSort(colConditions, k); if (colOrder.isEmpty()) return new int[][] {}; int[][] ans = new int[k][k]; int[] nodeToRowIndex = new int[k + 1]; for (int i = 0; i < k; ++i) nodeToRowIndex[rowOrder.get(i)] = i; for (int j = 0; j < k; ++j) { final int node = colOrder.get(j); final int i = nodeToRowIndex[node]; ans[i][j] = node; } return ans; } private List<Integer> topologicalSort(int[][] conditions, int n) { List<Integer> order = new ArrayList<>(); List<Integer>[] graph = new List[n + 1]; int[] inDegrees = new int[n + 1]; Queue<Integer> q = new ArrayDeque<>(); for (int i = 1; i <= n; ++i) graph[i] = new ArrayList<>(); // Build the graph. for (int[] condition : conditions) { final int u = condition[0]; final int v = condition[1]; graph[u].add(v); ++inDegrees[v]; } // Perform topological sorting. for (int i = 1; i <= n; ++i) if (inDegrees[i] == 0) q.offer(i); while (!q.isEmpty()) { final int u = q.poll(); order.add(u); for (final int v : graph[u]) if (--inDegrees[v] == 0) q.offer(v); } return order.size() == n ? order : new ArrayList<>(); } }
class Solution { public: vector<vector<int>> buildMatrix(int k, vector<vector<int>>& rowConditions, vector<vector<int>>& colConditions) { const vector<int> rowOrder = topologicalSort(rowConditions, k); if (rowOrder.empty()) return {}; const vector<int> colOrder = topologicalSort(colConditions, k); if (colOrder.empty()) return {}; vector<vector<int>> ans(k, vector<int>(k)); vector<int> nodeToRowIndex(k + 1); for (int i = 0; i < k; ++i) nodeToRowIndex[rowOrder[i]] = i; for (int j = 0; j < k; ++j) { const int node = colOrder[j]; const int i = nodeToRowIndex[node]; ans[i][j] = node; } return ans; } private: vector<int> topologicalSort(const vector<vector<int>>& conditions, int n) { vector<int> order; vector<vector<int>> graph(n + 1); vector<int> inDegrees(n + 1); queue<int> q; // Build the graph. for (const vector<int>& condition : conditions) { const int u = condition[0]; const int v = condition[1]; graph[u].push_back(v); ++inDegrees[v]; } // Perform topological sorting. for (int i = 1; i <= n; ++i) if (inDegrees[i] == 0) q.push(i); while (!q.empty()) { const int u = q.front(); q.pop(); order.push_back(u); for (const int v : graph[u]) if (--inDegrees[v] == 0) q.push(v); } return order.size() == n ? order : vector<int>(); } };
2,437
Number of Valid Clock Times
1
countTime
You are given a string of length `5` called `time`, representing the current time on a digital clock in the format `"hh:mm"`. The earliest possible time is `"00:00"` and the latest possible time is `"23:59"`. In the string `time`, the digits represented by the `?` symbol are unknown, and must be replaced with a digit from `0` to `9`. Return an integer `answer`, the number of valid clock times that can be created by replacing every `?` with a digit from `0` to `9`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def countTime(self, time: str) -> int: ans = 1 if time[3] == '?': ans *= 6 if time[4] == '?': ans *= 10 if time[0] == '?' and time[1] == '?': return ans * 24 if time[0] == '?': if time[1] < '4': return ans * 3 else: return ans * 2 if time[1] == '?': if time[0] == '2': return ans * 4 else: return ans * 10 return ans
class Solution { public int countTime(String time) { int ans = 1; if (time.charAt(3) == '?') ans *= 6; if (time.charAt(4) == '?') ans *= 10; if (time.charAt(0) == '?' && time.charAt(1) == '?') return ans * 24; if (time.charAt(0) == '?') return time.charAt(1) < '4' ? ans * 3 : ans * 2; if (time.charAt(1) == '?') return time.charAt(0) == '2' ? ans * 4 : ans * 10; return ans; } }
class Solution { public: int countTime(string time) { int ans = 1; if (time[3] == '?') ans *= 6; if (time[4] == '?') ans *= 10; if (time[0] == '?' && time[1] == '?') return ans * 24; if (time[0] == '?') return time[1] < '4' ? ans * 3 : ans * 2; if (time[1] == '?') return time[0] == '2' ? ans * 4 : ans * 10; return ans; } };
2,456
Most Popular Video Creator
2
mostPopularCreator
You are given two string arrays `creators` and `ids`, and an integer array `views`, all of length `n`. The `ith` video on a platform was created by `creator[i]`, has an id of `ids[i]`, and has `views[i]` views. The popularity of a creator is the sum of the number of views on all of the creator's videos. Find the creator with the highest popularity and the id of their most viewed video. * If multiple creators have the highest popularity, find all of them. * If multiple videos have the highest view count for a creator, find the lexicographically smallest id. Return a 2D array of strings `answer` where `answer[i] = [creatori, idi]` means that `creatori` has the highest popularity and `idi` is the id of their most popular video. The answer can be returned in any order.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Creator: def __init__(self, popularity: int, videoId: str, maxView: int): self.popularity = popularity self.videoId = videoId self.maxView = maxView class Solution: def mostPopularCreator(self, creators: List[str], ids: List[str], views: List[int]) -> List[List[str]]: ans = [] maxPopularity = 0 nameToCreator = {} for name, id, view in zip(creators, ids, views): if name not in nameToCreator: nameToCreator[name] = Creator(view, id, view) maxPopularity = max(maxPopularity, view) continue creator = nameToCreator[name] creator.popularity += view maxPopularity = max(maxPopularity, creator.popularity) if creator.maxView < view or creator.maxView == view and creator.videoId > id: creator.videoId = id creator.maxView = view for name, creator in nameToCreator.items(): if creator.popularity == maxPopularity: ans.append([name, creator.videoId]) return ans
class Creator { public long popularity; // the popularity sum public String videoId; // the video id that has the maximum view public int maxView; // the maximum view of the creator public Creator(long popularity, String videoId, int maxView) { this.popularity = popularity; this.videoId = videoId; this.maxView = maxView; } } class Solution { public List<List<String>> mostPopularCreator(String[] creators, String[] ids, int[] views) { List<List<String>> ans = new ArrayList<>(); Map<String, Creator> nameToCreator = new HashMap<>(); long maxPopularity = 0; for (int i = 0; i < creators.length; ++i) { if (!nameToCreator.containsKey(creators[i])) { nameToCreator.put(creators[i], new Creator(views[i], ids[i], views[i])); maxPopularity = Math.max(maxPopularity, (long) views[i]); continue; } Creator creator = nameToCreator.get(creators[i]); creator.popularity += views[i]; maxPopularity = Math.max(maxPopularity, (long) creator.popularity); if (creator.maxView < views[i] || creator.maxView == views[i] && creator.videoId.compareTo(ids[i]) > 0) { creator.videoId = ids[i]; creator.maxView = views[i]; } } for (Map.Entry<String, Creator> entry : nameToCreator.entrySet()) if (entry.getValue().popularity == maxPopularity) ans.add(Arrays.asList(entry.getKey(), entry.getValue().videoId)); return ans; } }
struct Creator { long popularity; // the popularity sum string videoId; // the video id that has the maximum view int maxView; // the maximum view of the creator }; class Solution { public: vector<vector<string>> mostPopularCreator(vector<string>& creators, vector<string>& ids, vector<int>& views) { vector<vector<string>> ans; unordered_map<string, Creator> nameToCreator; long maxPopularity = 0; for (int i = 0; i < creators.size(); ++i) { if (!nameToCreator.contains(creators[i])) { nameToCreator[creators[i]] = Creator{ .popularity = views[i], .videoId = ids[i], .maxView = views[i], }; maxPopularity = max(maxPopularity, static_cast<long>(views[i])); continue; } Creator& creator = nameToCreator[creators[i]]; creator.popularity += views[i]; maxPopularity = max(maxPopularity, static_cast<long>(creator.popularity)); if (creator.maxView < views[i] || creator.maxView == views[i] && creator.videoId > ids[i]) { creator.videoId = ids[i]; creator.maxView = views[i]; } } for (const auto& [name, creator] : nameToCreator) if (creator.popularity == maxPopularity) ans.push_back({name, creator.videoId}); return ans; } };
2,462
Total Cost to Hire K Workers
2
totalCost
You are given a 0-indexed integer array `costs` where `costs[i]` is the cost of hiring the `ith` worker. You are also given two integers `k` and `candidates`. We want to hire exactly `k` workers according to the following rules: * You will run `k` sessions and hire exactly one worker in each session. * In each hiring session, choose the worker with the lowest cost from either the first `candidates` workers or the last `candidates` workers. Break the tie by the smallest index. * For example, if `costs = [3,2,7,7,1,2]` and `candidates = 2`, then in the first hiring session, we will choose the `4th` worker because they have the lowest cost `[3,2,7,7,1,2]`. * In the second hiring session, we will choose `1st` worker because they have the same lowest cost as `4th` worker but they have the smallest index `[3,2,7,7,2]`. Please note that the indexing may be changed in the process. * If there are fewer than candidates workers remaining, choose the worker with the lowest cost among them. Break the tie by the smallest index. * A worker can only be chosen once. Return the total cost to hire exactly `k` workers.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def totalCost(self, costs: List[int], k: int, candidates: int) -> int: ans = 0 i = 0 j = len(costs) - 1 minHeapL = [] minHeapR = [] for _ in range(k): while len(minHeapL) < candidates and i <= j: heapq.heappush(minHeapL, costs[i]) i += 1 while len(minHeapR) < candidates and i <= j: heapq.heappush(minHeapR, costs[j]) j -= 1 if not minHeapL: ans += heapq.heappop(minHeapR) elif not minHeapR: ans += heapq.heappop(minHeapL) elif minHeapL[0] <= minHeapR[0]: ans += heapq.heappop(minHeapL) else: ans += heapq.heappop(minHeapR) return ans
class Solution { public long totalCost(int[] costs, int k, int candidates) { long ans = 0; int i = 0; int j = costs.length - 1; Queue<Integer> minHeapL = new PriorityQueue<>(); Queue<Integer> minHeapR = new PriorityQueue<>(); for (int hired = 0; hired < k; ++hired) { while (minHeapL.size() < candidates && i <= j) minHeapL.offer(costs[i++]); while (minHeapR.size() < candidates && i <= j) minHeapR.offer(costs[j--]); if (minHeapL.isEmpty()) ans += minHeapR.poll(); else if (minHeapR.isEmpty()) ans += minHeapL.poll(); // Both `minHeapL` and `minHeapR` are not empty. else if (minHeapL.peek() <= minHeapR.peek()) ans += minHeapL.poll(); else ans += minHeapR.poll(); } return ans; } }
class Solution { public: long long totalCost(vector<int>& costs, int k, int candidates) { long ans = 0; int i = 0; int j = costs.size() - 1; priority_queue<int, vector<int>, greater<>> minHeapL; priority_queue<int, vector<int>, greater<>> minHeapR; for (int hired = 0; hired < k; ++hired) { while (minHeapL.size() < candidates && i <= j) minHeapL.push(costs[i++]); while (minHeapR.size() < candidates && i <= j) minHeapR.push(costs[j--]); if (minHeapL.empty()) ans += minHeapR.top(), minHeapR.pop(); else if (minHeapR.empty()) ans += minHeapL.top(), minHeapL.pop(); // Both `minHeapL` and `minHeapR` are not empty. else if (minHeapL.top() <= minHeapR.top()) ans += minHeapL.top(), minHeapL.pop(); else ans += minHeapR.top(), minHeapR.pop(); } return ans; } };
2,467
Most Profitable Path in a Tree
2
mostProfitablePath
There is an undirected tree with `n` nodes labeled from `0` to `n - 1`, rooted at node `0`. You are given a 2D integer array `edges` of length `n - 1` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. At every node `i`, there is a gate. You are also given an array of even integers `amount`, where `amount[i]` represents: * the price needed to open the gate at node `i`, if `amount[i]` is negative, or, * the cash reward obtained on opening the gate at node `i`, otherwise. The game goes on as follows: * Initially, Alice is at node `0` and Bob is at node `bob`. * At every second, Alice and Bob each move to an adjacent node. Alice moves towards some leaf node, while Bob moves towards node `0`. * For every node along their path, Alice and Bob either spend money to open the gate at that node, or accept the reward. Note that: * If the gate is already open, no price will be required, nor will there be any cash reward. * If Alice and Bob reach the node simultaneously, they share the price/reward for opening the gate there. In other words, if the price to open the gate is `c`, then both Alice and Bob pay `c / 2` each. Similarly, if the reward at the gate is `c`, both of them receive `c / 2` each. * If Alice reaches a leaf node, she stops moving. Similarly, if Bob reaches node `0`, he stops moving. Note that these events are independent of each other. Return the maximum net income Alice can have if she travels towards the optimal leaf node.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def mostProfitablePath(self, edges: List[List[int]], bob: int, amount: List[int]) -> int: n = len(amount) tree = [[] for _ in range(n)] parent = [0] * n aliceDist = [-1] * n for u, v in edges: tree[u].append(v) tree[v].append(u) def dfs(u: int, prev: int, d: int) -> None: parent[u] = prev aliceDist[u] = d for v in tree[u]: if aliceDist[v] == -1: dfs(v, u, d + 1) dfs(0, -1, 0) u = bob bobDist = 0 while u != 0: if bobDist < aliceDist[u]: amount[u] = 0 elif bobDist == aliceDist[u]: amount[u] //= 2 u = parent[u] bobDist += 1 return self._getMoney(tree, 0, -1, amount) def _getMoney(self, tree: List[List[int]], u: int, prev: int, amount: List[int]) -> int: if len(tree[u]) == 1 and tree[u][0] == prev: return amount[u] maxPath = -math.inf for v in tree[u]: if v != prev: maxPath = max(maxPath, self._getMoney(tree, v, u, amount)) return amount[u] + maxPath
class Solution { public int mostProfitablePath(int[][] edges, int bob, int[] amount) { final int n = amount.length; List<Integer>[] tree = new List[n]; int[] parent = new int[n]; int[] aliceDist = new int[n]; Arrays.fill(aliceDist, -1); for (int i = 0; i < n; ++i) tree[i] = new ArrayList<>(); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; tree[u].add(v); tree[v].add(u); } dfs(tree, 0, -1, 0, parent, aliceDist); // Modify the amount along the path from node Bob to node 0. // For each node, // 1. If Bob reaches earlier than Alice does, change the amount to 0. // 2. If Bob and Alice reach simultaneously, devide the amount by 2. for (int u = bob, bobDist = 0; u != 0; u = parent[u], ++bobDist) if (bobDist < aliceDist[u]) amount[u] = 0; else if (bobDist == aliceDist[u]) amount[u] /= 2; return getMoney(tree, 0, -1, amount); } // Fills `parent` and `dist`. private void dfs(List<Integer>[] tree, int u, int prev, int d, int[] parent, int[] dist) { parent[u] = prev; dist[u] = d; for (final int v : tree[u]) { if (dist[v] == -1) dfs(tree, v, u, d + 1, parent, dist); } } private int getMoney(List<Integer>[] tree, int u, int prev, int[] amount) { // a leaf node if (tree[u].size() == 1 && tree[u].get(0) == prev) return amount[u]; int maxPath = Integer.MIN_VALUE; for (final int v : tree[u]) if (v != prev) maxPath = Math.max(maxPath, getMoney(tree, v, u, amount)); return amount[u] + maxPath; } }
class Solution { public: int mostProfitablePath(vector<vector<int>>& edges, int bob, vector<int>& amount) { const int n = amount.size(); vector<vector<int>> tree(n); vector<int> parent(n); vector<int> aliceDist(n, -1); for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; tree[u].push_back(v); tree[v].push_back(u); } dfs(tree, 0, -1, 0, parent, aliceDist); // Modify the amount along the path from node Bob to node 0. // For each node, // 1. If Bob reaches earlier than Alice does, change the amount to 0. // 2. If Bob and Alice reach simultaneously, devide the amount by 2. for (int u = bob, bobDist = 0; u != 0; u = parent[u], ++bobDist) if (bobDist < aliceDist[u]) amount[u] = 0; else if (bobDist == aliceDist[u]) amount[u] /= 2; return getMoney(tree, 0, -1, amount); } private: // Fills `parent` and `dist`. void dfs(const vector<vector<int>>& tree, int u, int prev, int d, vector<int>& parent, vector<int>& dist) { parent[u] = prev; dist[u] = d; for (const int v : tree[u]) { if (dist[v] == -1) dfs(tree, v, u, d + 1, parent, dist); } } int getMoney(const vector<vector<int>>& tree, int u, int prev, const vector<int>& amount) { // a leaf node if (tree[u].size() == 1 && tree[u][0] == prev) return amount[u]; int maxPath = INT_MIN; for (const int v : tree[u]) if (v != prev) maxPath = max(maxPath, getMoney(tree, v, u, amount)); return amount[u] + maxPath; } };
2,499
Minimum Total Cost to Make Arrays Unequal
3
minimumTotalCost
You are given two 0-indexed integer arrays `nums1` and `nums2`, of equal length `n`. In one operation, you can swap the values of any two indices of `nums1`. The cost of this operation is the sum of the indices. Find the minimum total cost of performing the given operation any number of times such that `nums1[i] != nums2[i]` for all `0 <= i <= n - 1` after performing all the operations. Return the minimum total cost such that `nums1` and `nums2` satisfy the above condition. In case it is not possible, return `-1`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minimumTotalCost(self, nums1: List[int], nums2: List[int]) -> int: n = len(nums1) ans = 0 maxFreq = 0 maxFreqNum = 0 shouldBeSwapped = 0 conflictedNumCount = [0] * (n + 1) for i, (num1, num2) in enumerate(zip(nums1, nums2)): if num1 == num2: conflictedNum = num1 conflictedNumCount[conflictedNum] += 1 if conflictedNumCount[conflictedNum] > maxFreq: maxFreq = conflictedNumCount[conflictedNum] maxFreqNum = conflictedNum shouldBeSwapped += 1 ans += i for i, (num1, num2) in enumerate(zip(nums1, nums2)): if maxFreq * 2 <= shouldBeSwapped: break if num1 == num2: continue if num1 == maxFreqNum or num2 == maxFreqNum: continue shouldBeSwapped += 1 ans += i if maxFreq * 2 > shouldBeSwapped: return -1 else: return ans
class Solution { public long minimumTotalCost(int[] nums1, int[] nums2) { final int n = nums1.length; long ans = 0; int maxFreq = 0; int maxFreqNum = 0; int shouldBeSwapped = 0; int[] conflictedNumCount = new int[n + 1]; // Collect the indices i s.t. nums1[i] == nums2[i] and record their `maxFreq` // and `maxFreqNum`. for (int i = 0; i < n; ++i) if (nums1[i] == nums2[i]) { final int conflictedNum = nums1[i]; if (++conflictedNumCount[conflictedNum] > maxFreq) { maxFreq = conflictedNumCount[conflictedNum]; maxFreqNum = conflictedNum; } ++shouldBeSwapped; ans += i; } // Collect the indices with nums1[i] != nums2[i] that contribute less cost. // This can be greedily achieved by iterating from 0 to n - 1. for (int i = 0; i < n; ++i) { // Since we have over `maxFreq * 2` spaces, `maxFreqNum` can be // successfully distributed, so no need to collectextra spaces. if (maxFreq * 2 <= shouldBeSwapped) break; if (nums1[i] == nums2[i]) continue; // The numbers == `maxFreqNum` worsen the result since they increase the // `maxFreq`. if (nums1[i] == maxFreqNum || nums2[i] == maxFreqNum) continue; ++shouldBeSwapped; ans += i; } return maxFreq * 2 > shouldBeSwapped ? -1 : ans; } }
class Solution { public: long long minimumTotalCost(vector<int>& nums1, vector<int>& nums2) { const int n = nums1.size(); long ans = 0; int maxFreq = 0; int maxFreqNum = 0; int shouldBeSwapped = 0; vector<int> conflictedNumCount(n + 1); // Collect the indices i s.t. nums1[i] == nums2[i] and record their // `maxFreq` and `maxFreqNum`. for (int i = 0; i < n; ++i) if (nums1[i] == nums2[i]) { const int conflictedNum = nums1[i]; if (++conflictedNumCount[conflictedNum] > maxFreq) { maxFreq = conflictedNumCount[conflictedNum]; maxFreqNum = conflictedNum; } ++shouldBeSwapped; ans += i; } // Collect the indices with nums1[i] != nums2[i] that contribute less cost. // This can be greedily achieved by iterating from 0 to n - 1. for (int i = 0; i < n; ++i) { // Since we have over `maxFreq * 2` spaces, `maxFreqNum` can be // successfully distributed, so no need to collectextra spaces. if (maxFreq * 2 <= shouldBeSwapped) break; if (nums1[i] == nums2[i]) continue; // The numbers == `maxFreqNum` worsen the result since they increase the // `maxFreq`. if (nums1[i] == maxFreqNum || nums2[i] == maxFreqNum) continue; ++shouldBeSwapped; ans += i; } return maxFreq * 2 > shouldBeSwapped ? -1 : ans; } };
2,503
Maximum Number of Points From Grid Queries
3
maxPoints
You are given an `m x n` integer matrix `grid` and an array `queries` of size `k`. Find an array `answer` of size `k` such that for each integer `queries[i]` you start in the top left cell of the matrix and repeat the following process: * If `queries[i]` is strictly greater than the value of the current cell that you are in, then you get one point if it is your first time visiting this cell, and you can move to any adjacent cell in all `4` directions: up, down, left, and right. * Otherwise, you do not get any points, and you end this process. After the process, `answer[i]` is the maximum number of points you can get. Note that for each query you are allowed to visit the same cell multiple times. Return the resulting array `answer`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class IndexedQuery: def __init__(self, queryIndex: int, query: int): self.queryIndex = queryIndex self.query = query def __iter__(self): yield self.queryIndex yield self.query class Solution: def maxPoints(self, grid: List[List[int]], queries: List[int]) -> List[int]: dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) m = len(grid) n = len(grid[0]) ans = [0] * len(queries) minHeap = [(grid[0][0], 0, 0)] seen = {(0, 0)} accumulate = 0 for queryIndex, query in sorted([IndexedQuery(i, query) for i, query in enumerate(queries)], key=lambda iq: iq.query): while minHeap: val, i, j = heapq.heappop(minHeap) if val >= query: heapq.heappush(minHeap, (val, i, j)) break accumulate += 1 for dx, dy in dirs: x = i + dx y = j + dy if x < 0 or x == m or y < 0 or y == n: continue if (x, y) in seen: continue heapq.heappush(minHeap, (grid[x][y], x, y)) seen.add((x, y)) ans[queryIndex] = accumulate return ans
class Solution { public int[] maxPoints(int[][] grid, int[] queries) { record T(int i, int j, int val) {} final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; final int m = grid.length; final int n = grid[0].length; int[] ans = new int[queries.length]; Queue<T> minHeap = new PriorityQueue<>(Comparator.comparingInt(T::val)); boolean[][] seen = new boolean[m][n]; minHeap.offer(new T(0, 0, grid[0][0])); seen[0][0] = true; int accumulate = 0; for (IndexedQuery indexedQuery : getIndexedQueries(queries)) { final int queryIndex = indexedQuery.queryIndex; final int query = indexedQuery.query; while (!minHeap.isEmpty()) { final int i = minHeap.peek().i; final int j = minHeap.peek().j; final int val = minHeap.poll().val; if (val >= query) { // The smallest neighbor is still larger than `query`, so no need to // keep exploring. Re-push (i, j, grid[i][j]) back to the `minHeap`. minHeap.offer(new T(i, j, val)); break; } ++accumulate; for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == m || y < 0 || y == n) continue; if (seen[x][y]) continue; minHeap.offer(new T(x, y, grid[x][y])); seen[x][y] = true; } } ans[queryIndex] = accumulate; } return ans; } private record IndexedQuery(int queryIndex, int query) {} private IndexedQuery[] getIndexedQueries(int[] queries) { IndexedQuery[] indexedQueries = new IndexedQuery[queries.length]; for (int i = 0; i < queries.length; ++i) indexedQueries[i] = new IndexedQuery(i, queries[i]); Arrays.sort(indexedQueries, Comparator.comparingInt(IndexedQuery::query)); return indexedQueries; } }
struct IndexedQuery { int queryIndex; int query; }; struct T { int i; int j; int val; // grid[i][j] }; class Solution { public: vector<int> maxPoints(vector<vector<int>>& grid, vector<int>& queries) { constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; const int m = grid.size(); const int n = grid[0].size(); vector<int> ans(queries.size()); auto compare = [](const T& a, const T& b) { return a.val > b.val; }; priority_queue<T, vector<T>, decltype(compare)> minHeap(compare); vector<vector<bool>> seen(m, vector<bool>(n)); minHeap.emplace(0, 0, grid[0][0]); seen[0][0] = true; int accumulate = 0; for (const auto& [queryIndex, query] : getIndexedQueries(queries)) { while (!minHeap.empty()) { const auto [i, j, val] = minHeap.top(); minHeap.pop(); if (val >= query) { // The smallest neighbor is still larger than `query`, so no need to // keep exploring. Re-push (i, j, grid[i][j]) back to the `minHeap`. minHeap.emplace(i, j, val); break; } ++accumulate; for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == m || y < 0 || y == n) continue; if (seen[x][y]) continue; minHeap.emplace(x, y, grid[x][y]); seen[x][y] = true; } } ans[queryIndex] = accumulate; } return ans; } private: vector<IndexedQuery> getIndexedQueries(const vector<int>& queries) { vector<IndexedQuery> indexedQueries; for (int i = 0; i < queries.size(); ++i) indexedQueries.push_back({i, queries[i]}); ranges::sort( indexedQueries, ranges::less{}, [](const IndexedQuery& indexedQuery) { return indexedQuery.query; }); return indexedQueries; } };
2,508
Add Edges to Make Degrees of All Nodes Even
3
isPossible
There is an undirected graph consisting of `n` nodes numbered from `1` to `n`. You are given the integer `n` and a 2D array `edges` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi`. The graph can be disconnected. You can add at most two additional edges (possibly none) to this graph so that there are no repeated edges and no self-loops. Return `true` if it is possible to make the degree of each node in the graph even, otherwise return `false`. The degree of a node is the number of edges connected to it.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def isPossible(self, n: int, edges: List[List[int]]) -> bool: graph = [set() for _ in range(n)] for u, v in edges: graph[u - 1].add(v - 1) graph[v - 1].add(u - 1) oddNodes = [i for i, neighbor in enumerate(graph) if len(neighbor) & 1] if not oddNodes: return True if len(oddNodes) == 2: a, b = oddNodes return any(a not in graph[i] and b not in graph[i] for i in range(n)) if len(oddNodes) == 4: a, b, c, d = oddNodes return (b not in graph[a] and d not in graph[c]) or (c not in graph[a] and d not in graph[b]) or (d not in graph[a] and c not in graph[b]) return False
class Solution { public boolean isPossible(int n, List<List<Integer>> edges) { Set<Integer>[] graph = new Set[n]; for (int i = 0; i < n; ++i) graph[i] = new HashSet<>(); for (List<Integer> edge : edges) { final int u = edge.get(0) - 1; final int v = edge.get(1) - 1; graph[u].add(v); graph[v].add(u); } List<Integer> oddNodes = getOddNodes(graph); if (oddNodes.isEmpty()) return true; if (oddNodes.size() == 2) { final int a = oddNodes.get(0); final int b = oddNodes.get(1); for (int i = 0; i < n; ++i) // Can connect i with a and i with b. if (!graph[i].contains(a) && !graph[i].contains(b)) return true; } if (oddNodes.size() == 4) { final int a = oddNodes.get(0); final int b = oddNodes.get(1); final int c = oddNodes.get(2); final int d = oddNodes.get(3); return (!graph[a].contains(b) && !graph[c].contains(d)) || (!graph[a].contains(c) && !graph[b].contains(d)) || (!graph[a].contains(d) && !graph[b].contains(c)); } return false; } private List<Integer> getOddNodes(Set<Integer>[] graph) { List<Integer> oddNodes = new ArrayList<>(); for (int i = 0; i < graph.length; ++i) if (graph[i].size() % 2 == 1) oddNodes.add(i); return oddNodes; } }
class Solution { public: bool isPossible(int n, vector<vector<int>>& edges) { vector<unordered_set<int>> graph(n); for (const vector<int>& edge : edges) { const int u = edge[0] - 1; const int v = edge[1] - 1; graph[u].insert(v); graph[v].insert(u); } const vector<int> oddNodes = getOddNodes(graph); if (oddNodes.empty()) return true; if (oddNodes.size() == 2) { const int a = oddNodes[0]; const int b = oddNodes[1]; for (int i = 0; i < n; ++i) // Can connect i with a and i with b. if (!graph[i].contains(a) && !graph[i].contains(b)) return true; } if (oddNodes.size() == 4) { const int a = oddNodes[0]; const int b = oddNodes[1]; const int c = oddNodes[2]; const int d = oddNodes[3]; return (!graph[a].contains(b) && !graph[c].contains(d)) || (!graph[a].contains(c) && !graph[b].contains(d)) || (!graph[a].contains(d) && !graph[b].contains(c)); } return false; } private: vector<int> getOddNodes(const vector<unordered_set<int>>& graph) { vector<int> oddNodes; for (int i = 0; i < graph.size(); ++i) if (graph[i].size() % 2 == 1) oddNodes.push_back(i); return oddNodes; } };
2,523
Closest Prime Numbers in Range
2
closestPrimes
Given two positive integers `left` and `right`, find the two integers `num1` and `num2` such that: * `left <= num1 < num2 <= right `. * `num1` and `num2` are both prime numbers. * `num2 - num1` is the minimum amongst all other pairs satisfying the above conditions. Return the positive integer array `ans = [num1, num2]`. If there are multiple pairs satisfying these conditions, return the one with the minimum `num1` value or `[-1, -1]` if such numbers do not exist. A number greater than `1` is called prime if it is only divisible by `1` and itself.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def closestPrimes(self, left: int, right: int) -> List[int]: isPrime = self._sieveEratosthenes(right + 1) primes=[] for i in range(left, right+1): if isPrime[i]: primes.append(i) if len(primes) < 2: return [-1, -1] minDiff = math.inf num1 = -1 num2 = -1 for a, b in zip(primes, primes[1:]): diff = b - a if diff < minDiff: minDiff = diff num1 = a num2 = b return [num1, num2] def _sieveEratosthenes(self, n: int) -> List[bool]: isPrime = [True] * n isPrime[0] = False isPrime[1] = False for i in range(2, int(n**0.5) + 1): if isPrime[i]: for j in range(i * i, n, i): isPrime[j] = False return isPrime
class Solution { public int[] closestPrimes(int left, int right) { final boolean[] isPrime = sieveEratosthenes(right + 1); List<Integer> primes = new ArrayList<>(); for (int i = left; i <= right; ++i) if (isPrime[i]) primes.add(i); if (primes.size() < 2) return new int[] {-1, -1}; int minDiff = Integer.MAX_VALUE; int num1 = -1; int num2 = -1; for (int i = 1; i < primes.size(); ++i) { final int diff = primes.get(i) - primes.get(i - 1); if (diff < minDiff) { minDiff = diff; num1 = primes.get(i - 1); num2 = primes.get(i); } } return new int[] {num1, num2}; } private boolean[] sieveEratosthenes(int n) { boolean[] isPrime = new boolean[n]; Arrays.fill(isPrime, true); isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i < n; ++i) if (isPrime[i]) for (int j = i * i; j < n; j += i) isPrime[j] = false; return isPrime; } }
class Solution { public: vector<int> closestPrimes(int left, int right) { const vector<bool> isPrime = sieveEratosthenes(right + 1); vector<int> primes; for (int i = left; i <= right; ++i) if (isPrime[i]) primes.push_back(i); if (primes.size() < 2) return {-1, -1}; int minDiff = INT_MAX; int num1 = -1; int num2 = -1; for (int i = 1; i < primes.size(); ++i) { const int diff = primes[i] - primes[i - 1]; if (diff < minDiff) { minDiff = diff; num1 = primes[i - 1]; num2 = primes[i]; } } return {num1, num2}; } private: vector<bool> sieveEratosthenes(int n) { vector<bool> isPrime(n, true); isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i < n; ++i) if (isPrime[i]) for (int j = i * i; j < n; j += i) isPrime[j] = false; return isPrime; } };
2,532
Time to Cross a Bridge
3
findCrossingTime
There are `k` workers who want to move `n` boxes from an old warehouse to a new one. You are given the two integers `n` and `k`, and a 2D integer array `time` of size `k x 4` where `time[i] = [leftToRighti, pickOldi, rightToLefti, putNewi]`. The warehouses are separated by a river and connected by a bridge. The old warehouse is on the right bank of the river, and the new warehouse is on the left bank of the river. Initially, all `k` workers are waiting on the left side of the bridge. To move the boxes, the `ith` worker (0-indexed) can : * Cross the bridge from the left bank (new warehouse) to the right bank (old warehouse) in `leftToRighti` minutes. * Pick a box from the old warehouse and return to the bridge in `pickOldi` minutes. Different workers can pick up their boxes simultaneously. * Cross the bridge from the right bank (old warehouse) to the left bank (new warehouse) in `rightToLefti` minutes. * Put the box in the new warehouse and return to the bridge in `putNewi` minutes. Different workers can put their boxes simultaneously. A worker `i` is less efficient than a worker `j` if either condition is met: * `leftToRighti + rightToLefti > leftToRightj + rightToLeftj` * `leftToRighti + rightToLefti == leftToRightj + rightToLeftj` and `i > j` The following rules regulate the movement of the workers through the bridge : * If a worker `x` reaches the bridge while another worker `y` is crossing the bridge, `x` waits at their side of the bridge. * If the bridge is free, the worker waiting on the right side of the bridge gets to cross the bridge. If more than one worker is waiting on the right side, the one with the lowest efficiency crosses first. * If the bridge is free and no worker is waiting on the right side, and at least one box remains at the old warehouse, the worker on the left side of the river gets to cross the bridge. If more than one worker is waiting on the left side, the one with the lowest efficiency crosses first. Return the instance of time at which the last worker reaches the left bank of the river after all n boxes have been put in the new warehouse.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def findCrossingTime(self, n: int, k: int, time: List[List[int]]) -> int: ans = 0 leftBridgeQueue = [(-leftToRight - rightToLeft, -i) for i, (leftToRight, pickOld, rightToLeft, pickNew) in enumerate(time)] rightBridgeQueue = [] leftWorkers = [] rightWorkers = [] heapq.heapify(leftBridgeQueue) while n > 0 or rightBridgeQueue or rightWorkers: while leftWorkers and leftWorkers[0][0] <= ans: i = heapq.heappop(leftWorkers)[1] heapq.heappush(leftBridgeQueue, (-time[i][0] - time[i][2], -i)) while rightWorkers and rightWorkers[0][0] <= ans: i = heapq.heappop(rightWorkers)[1] heapq.heappush(rightBridgeQueue, (-time[i][0] - time[i][2], -i)) if rightBridgeQueue: i = -heapq.heappop(rightBridgeQueue)[1] ans += time[i][2] heapq.heappush(leftWorkers, (ans + time[i][3], i)) elif leftBridgeQueue and n > 0: i = -heapq.heappop(leftBridgeQueue)[1] ans += time[i][0] heapq.heappush(rightWorkers, (ans + time[i][1], i)) n -= 1 else: if leftWorkers and n > 0: ans1=leftWorkers[0][0] else: ans1=math.inf if rightWorkers: ans2=rightWorkers[0][0] else: ans2=math.inf ans=min(ans1,ans2) return ans
class Solution { public int findCrossingTime(int n, int k, int[][] time) { int ans = 0; // (leftToRight + rightToLeft, i) Queue<Pair<Integer, Integer>> leftBridgeQueue = createMaxHeap(); Queue<Pair<Integer, Integer>> rightBridgeQueue = createMaxHeap(); // (time to be idle, i) Queue<Pair<Integer, Integer>> leftWorkers = createMinHeap(); Queue<Pair<Integer, Integer>> rightWorkers = createMinHeap(); for (int i = 0; i < k; ++i) leftBridgeQueue.offer(new Pair<>( /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i)); while (n > 0 || !rightBridgeQueue.isEmpty() || !rightWorkers.isEmpty()) { // Idle left workers get on the left bridge. while (!leftWorkers.isEmpty() && leftWorkers.peek().getKey() <= ans) { final int i = leftWorkers.poll().getValue(); leftBridgeQueue.offer(new Pair<>( /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i)); } // Idle right workers get on the right bridge. while (!rightWorkers.isEmpty() && rightWorkers.peek().getKey() <= ans) { final int i = rightWorkers.poll().getValue(); rightBridgeQueue.offer(new Pair<>( /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i)); } if (!rightBridgeQueue.isEmpty()) { // If the bridge is free, the worker waiting on the right side of the // bridge gets to cross the bridge. If more than one worker is waiting // on the right side, the one with the lowest efficiency crosses first. final int i = rightBridgeQueue.poll().getValue(); ans += /*rightToLeft*/ time[i][2]; leftWorkers.offer(new Pair<>(ans + /*putNew*/ time[i][3], i)); } else if (!leftBridgeQueue.isEmpty() && n > 0) { // If the bridge is free and no worker is waiting on the right side, and // at least one box remains at the old warehouse, the worker on the left // side of the river gets to cross the bridge. If more than one worker // is waiting on the left side, the one with the lowest efficiency // crosses first. final int i = leftBridgeQueue.poll().getValue(); ans += /*leftToRight*/ time[i][0]; rightWorkers.offer(new Pair<>(ans + /*pickOld*/ time[i][1], i)); --n; } else { // Advance the time of the last crossing worker. ans = Math.min(!leftWorkers.isEmpty() && n > 0 ? leftWorkers.peek().getKey() : Integer.MAX_VALUE, !rightWorkers.isEmpty() ? rightWorkers.peek().getKey() : Integer.MAX_VALUE); } } return ans; } private Queue<Pair<Integer, Integer>> createMaxHeap() { return new PriorityQueue<>( Comparator.comparing(Pair<Integer, Integer>::getKey, Comparator.reverseOrder()) .thenComparing(Pair<Integer, Integer>::getValue, Comparator.reverseOrder())); } private Queue<Pair<Integer, Integer>> createMinHeap() { return new PriorityQueue<>(Comparator.comparingInt(Pair<Integer, Integer>::getKey) .thenComparingInt(Pair<Integer, Integer>::getValue)); } }
class Solution { public: int findCrossingTime(int n, int k, vector<vector<int>>& time) { int ans = 0; using P = pair<int, int>; // (leftToRight + rightToLeft, i) priority_queue<P> leftBridgeQueue; priority_queue<P> rightBridgeQueue; // (time to be idle, i) priority_queue<P, vector<P>, greater<>> leftWorkers; priority_queue<P, vector<P>, greater<>> rightWorkers; for (int i = 0; i < k; ++i) leftBridgeQueue.emplace( /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i); while (n > 0 || !rightBridgeQueue.empty() || !rightWorkers.empty()) { // Idle left workers get on the left bridge. while (!leftWorkers.empty() && leftWorkers.top().first <= ans) { const int i = leftWorkers.top().second; leftWorkers.pop(); leftBridgeQueue.emplace( /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i); } // Idle right workers get on the right bridge. while (!rightWorkers.empty() && rightWorkers.top().first <= ans) { const int i = rightWorkers.top().second; rightWorkers.pop(); rightBridgeQueue.emplace( /*leftToRight*/ time[i][0] + /*rightToLeft*/ time[i][2], i); } if (!rightBridgeQueue.empty()) { // If the bridge is free, the worker waiting on the right side of the // bridge gets to cross the bridge. If more than one worker is waiting // on the right side, the one with the lowest efficiency crosses first. const int i = rightBridgeQueue.top().second; rightBridgeQueue.pop(); ans += /*rightToLeft*/ time[i][2]; leftWorkers.emplace(ans + /*putNew*/ time[i][3], i); } else if (!leftBridgeQueue.empty() && n > 0) { // If the bridge is free and no worker is waiting on the right side, and // at least one box remains at the old warehouse, the worker on the left // side of the river gets to cross the bridge. If more than one worker // is waiting on the left side, the one with the lowest efficiency // crosses first. const int i = leftBridgeQueue.top().second; leftBridgeQueue.pop(); ans += /*leftToRight*/ time[i][0]; rightWorkers.emplace(ans + /*pickOld*/ time[i][1], i); --n; } else { // Advance the time of the last crossing worker. ans = min( !leftWorkers.empty() && n > 0 ? leftWorkers.top().first : INT_MAX, !rightWorkers.empty() ? rightWorkers.top().first : INT_MAX); } } return ans; } };
2,577
Minimum Time to Visit a Cell In a Grid
3
minimumTime
You are given a `m x n` matrix `grid` consisting of non-negative integers where `grid[row][col]` represents the minimum time required to be able to visit the cell `(row, col)`, which means you can visit the cell `(row, col)` only when the time you visit it is greater than or equal to `grid[row][col]`. You are standing in the top-left cell of the matrix in the `0th` second, and you must move to any adjacent cell in the four directions: up, down, left, and right. Each move you make takes 1 second. Return the minimum time required in which you can visit the bottom-right cell of the matrix. If you cannot visit the bottom-right cell, then return `-1`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minimumTime(self, grid: List[List[int]]) -> int: if grid[0][1] > 1 and grid[1][0] > 1: return -1 dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) m = len(grid) n = len(grid[0]) minHeap = [(0, 0, 0)] seen = {(0, 0)} while minHeap: time, i, j = heapq.heappop(minHeap) if i == m - 1 and j == n - 1: return time for dx, dy in dirs: x = i + dx y = j + dy if x < 0 or x == m or y < 0 or y == n: continue if (x, y) in seen: continue if (grid[x][y] - time) % 2 == 0: extraWait = 1 else: extraWait = 0 nextTime = max(time + 1, grid[x][y] + extraWait) heapq.heappush(minHeap, (nextTime, x, y)) seen.add((x, y))
class Solution { public int minimumTime(int[][] grid) { if (grid[0][1] > 1 && grid[1][0] > 1) return -1; final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; final int m = grid.length; final int n = grid[0].length; Queue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])) { { offer(new int[] {0, 0, 0}); } // (time, i, j) }; boolean[][] seen = new boolean[m][n]; seen[0][0] = true; while (!minHeap.isEmpty()) { final int time = minHeap.peek()[0]; final int i = minHeap.peek()[1]; final int j = minHeap.poll()[2]; if (i == m - 1 && j == n - 1) return time; for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == m || y < 0 || y == n) continue; if (seen[x][y]) continue; final int extraWait = (grid[x][y] - time) % 2 == 0 ? 1 : 0; final int nextTime = Math.max(time + 1, grid[x][y] + extraWait); minHeap.offer(new int[] {nextTime, x, y}); seen[x][y] = true; } } throw new IllegalArgumentException(); } }
class Solution { public: int minimumTime(vector<vector<int>>& grid) { if (grid[0][1] > 1 && grid[1][0] > 1) return -1; constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; const int m = grid.size(); const int n = grid[0].size(); using T = tuple<int, int, int>; // (time, i, j) priority_queue<T, vector<T>, greater<>> minHeap; vector<vector<bool>> seen(m, vector<bool>(n)); minHeap.emplace(0, 0, 0); seen[0][0] = true; while (!minHeap.empty()) { const auto [time, i, j] = minHeap.top(); minHeap.pop(); if (i == m - 1 && j == n - 1) return time; for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == m || y < 0 || y == n) continue; if (seen[x][y]) continue; const int extraWait = (grid[x][y] - time) % 2 == 0 ? 1 : 0; const int nextTime = max(time + 1, grid[x][y] + extraWait); minHeap.emplace(nextTime, x, y); seen[x][y] = true; } } throw; } };
2,601
Prime Subtraction Operation
2
primeSubOperation
You are given a 0-indexed integer array `nums` of length `n`. You can perform the following operation as many times as you want: * Pick an index `i` that you haven’t picked before, and pick a prime `p` strictly less than `nums[i]`, then subtract `p` from `nums[i]`. Return true if you can make `nums` a strictly increasing array using the above operation and false otherwise. A strictly increasing array is an array whose each element is strictly greater than its preceding element.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def primeSubOperation(self, nums: List[int]) -> bool: kMax = 1000 primes = self._sieveEratosthenes(kMax) prevNum = 0 for num in nums: i = bisect.bisect_left(primes, num - prevNum) if i > 0: num -= primes[i - 1] if num <= prevNum: return False prevNum = num return True def _sieveEratosthenes(self, n: int) -> List[int]: isPrime = [True] * n isPrime[0] = False isPrime[1] = False for i in range(2, int(n**0.5) + 1): if isPrime[i]: for j in range(i * i, n, i): isPrime[j] = False return [i for i in range(n) if isPrime[i]]
class Solution { public boolean primeSubOperation(int[] nums) { final int MAX = 1000; final List<Integer> primes = sieveEratosthenes(MAX); int prevNum = 0; for (int num : nums) { // Make nums[i] the smallest as possible and still > nums[i - 1]. final int i = firstGreaterEqual(primes, num - prevNum); if (i > 0) num -= primes.get(i - 1); if (num <= prevNum) return false; prevNum = num; } return true; } private List<Integer> sieveEratosthenes(int n) { List<Integer> primes = new ArrayList<>(); boolean[] isPrime = new boolean[n]; Arrays.fill(isPrime, true); isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i < n; ++i) if (isPrime[i]) for (int j = i * i; j < n; j += i) isPrime[j] = false; for (int i = 2; i < n; ++i) if (isPrime[i]) primes.add(i); return primes; } private int firstGreaterEqual(List<Integer> A, int target) { final int i = Collections.binarySearch(A, target); return i < 0 ? -i - 1 : i; } }
class Solution { public: bool primeSubOperation(vector<int>& nums) { constexpr int kMax = 1000; const vector<int> primes = sieveEratosthenes(kMax); int prevNum = 0; for (int num : nums) { // Make nums[i] the smallest as possible and still > nums[i - 1]. const auto it = ranges::lower_bound(primes, num - prevNum); if (it != primes.begin()) num -= *prev(it); if (num <= prevNum) return false; prevNum = num; } return true; } vector<int> sieveEratosthenes(int n) { vector<int> primes; vector<bool> isPrime(n, true); isPrime[0] = false; isPrime[1] = false; for (int i = 2; i * i < n; ++i) if (isPrime[i]) for (int j = i * i; j < n; j += i) isPrime[j] = false; for (int i = 2; i < n; ++i) if (isPrime[i]) primes.push_back(i); return primes; } };
2,603
Collect Coins in a Tree
3
collectTheCoins
There exists an undirected and unrooted tree with `n` nodes indexed from `0` to `n - 1`. You are given an integer `n` and a 2D integer array edges of length `n - 1`, where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. You are also given an array `coins` of size `n` where `coins[i]` can be either `0` or `1`, where `1` indicates the presence of a coin in the vertex `i`. Initially, you choose to start at any vertex in the tree. Then, you can perform the following operations any number of times: * Collect all the coins that are at a distance of at most `2` from the current vertex, or * Move to any adjacent vertex in the tree. Find the minimum number of edges you need to go through to collect all the coins and go back to the initial vertex. Note that if you pass an edge several times, you need to count it into the answer several times.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def collectTheCoins(self, coins: List[int], edges: List[List[int]]) -> int: n = len(coins) tree = [set() for _ in range(n)] leavesToBeRemoved = collections.deque() for u, v in edges: tree[u].add(v) tree[v].add(u) for u in range(n): while len(tree[u]) == 1 and coins[u] == 0: v = tree[u].pop() tree[v].remove(u) u = v if len(tree[u]) == 1: leavesToBeRemoved.append(u) for _ in range(2): for _ in range(len(leavesToBeRemoved)): u = leavesToBeRemoved.popleft() if tree[u]: v = tree[u].pop() tree[v].remove(u) if len(tree[v]) == 1: leavesToBeRemoved.append(v) return sum(len(children) for children in tree)
class Solution { public int collectTheCoins(int[] coins, int[][] edges) { final int n = coins.length; Set<Integer>[] tree = new Set[n]; Deque<Integer> leavesToBeRemoved = new ArrayDeque<>(); for (int i = 0; i < n; ++i) tree[i] = new HashSet<>(); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; tree[u].add(v); tree[v].add(u); } for (int i = 0; i < n; ++i) { int u = i; // Remove the leaves that don't have coins. while (tree[u].size() == 1 && coins[u] == 0) { final int v = tree[u].iterator().next(); tree[u].clear(); tree[v].remove(u); u = v; // Walk up to its parent. } // After trimming leaves without coins, leaves with coins may satisfy // `leavesToBeRemoved`. if (tree[u].size() == 1) leavesToBeRemoved.offer(u); } // Remove each remaining leaf node and its parent. The remaining nodes are // the ones that must be visited. for (int i = 0; i < 2; ++i) for (int sz = leavesToBeRemoved.size(); sz > 0; --sz) { final int u = leavesToBeRemoved.poll(); if (!tree[u].isEmpty()) { final int v = tree[u].iterator().next(); tree[u].clear(); tree[v].remove(u); if (tree[v].size() == 1) leavesToBeRemoved.offer(v); } } return Arrays.stream(tree).mapToInt(children -> children.size()).sum(); } }
class Solution { public: int collectTheCoins(vector<int>& coins, vector<vector<int>>& edges) { const int n = coins.size(); vector<unordered_set<int>> tree(n); queue<int> leavesToBeRemoved; for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; tree[u].insert(v); tree[v].insert(u); } for (int i = 0; i < n; ++i) { int u = i; // Remove the leaves that don't have coins. while (tree[u].size() == 1 && coins[u] == 0) { const int v = *tree[u].begin(); tree[u].clear(); tree[v].erase(u); u = v; // Walk up to its parent. } // After trimming leaves without coins, leaves with coins may satisfy // `leavesToBeRemoved`. if (tree[u].size() == 1) leavesToBeRemoved.push(u); } // Remove each remaining leaf node and its parent. The remaining nodes are // the ones that must be visited. for (int i = 0; i < 2; ++i) for (int sz = leavesToBeRemoved.size(); sz > 0; --sz) { const int u = leavesToBeRemoved.front(); leavesToBeRemoved.pop(); if (!tree[u].empty()) { const int v = *tree[u].begin(); tree[u].clear(); tree[v].erase(u); if (tree[v].size() == 1) leavesToBeRemoved.push(v); } } return accumulate(tree.begin(), tree.end(), 0, [](int acc, const unordered_set<int>& children) { return acc + children.size(); }); } };
2,653
Sliding Subarray Beauty
2
getSubarrayBeauty
Given an integer array `nums` containing `n` integers, find the beauty of each subarray of size `k`. The beauty of a subarray is the `xth` smallest integer in the subarray if it is negative, or `0` if there are fewer than `x` negative integers. Return an integer array containing `n - k + 1` integers, which denote the beauty of the subarrays in order from the first index in the array. * A subarray is a contiguous non-empty sequence of elements within an array.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def getSubarrayBeauty(self, nums: List[int], k: int, x: int) -> List[int]: ans = [] count = [0] * 50 for i, num in enumerate(nums): if num < 0: count[num + 50] += 1 if i - k >= 0 and nums[i - k] < 0: count[nums[i - k] + 50] -= 1 if i + 1 >= k: ans.append(self._getXthSmallestNum(count, x)) return ans def _getXthSmallestNum(self, count: List[int], x: int) -> int: prefix = 0 for i in range(50): prefix += count[i] if prefix >= x: return i - 50 return 0
class Solution { public int[] getSubarrayBeauty(int[] nums, int k, int x) { int[] ans = new int[nums.length - k + 1]; int[] count = new int[50]; // count[i] := the frequency of (i + 50) for (int i = 0; i < nums.length; ++i) { if (nums[i] < 0) ++count[nums[i] + 50]; if (i - k >= 0 && nums[i - k] < 0) --count[nums[i - k] + 50]; if (i + 1 >= k) ans[i - k + 1] = getXthSmallestNum(count, x); } return ans; } private int getXthSmallestNum(int[] count, int x) { int prefix = 0; for (int i = 0; i < 50; ++i) { prefix += count[i]; if (prefix >= x) return i - 50; } return 0; } }
class Solution { public: vector<int> getSubarrayBeauty(vector<int>& nums, int k, int x) { vector<int> ans; vector<int> count(50); // count[i] := the frequency of (i + 50) for (int i = 0; i < nums.size(); ++i) { if (nums[i] < 0) ++count[nums[i] + 50]; if (i - k >= 0 && nums[i - k] < 0) --count[nums[i - k] + 50]; if (i + 1 >= k) ans.push_back(getXthSmallestNum(count, x)); } return ans; } private: int getXthSmallestNum(const vector<int>& count, int x) { int prefix = 0; for (int i = 0; i < 50; ++i) { prefix += count[i]; if (prefix >= x) return i - 50; } return 0; } };
2,662
Minimum Cost of a Path With Special Roads
2
minimumCost
You are given an array `start` where `start = [startX, startY]` represents your initial position `(startX, startY)` in a 2D space. You are also given the array `target` where `target = [targetX, targetY]` represents your target position `(targetX, targetY)`. The cost of going from a position `(x1, y1)` to any other position in the space `(x2, y2)` is `|x2 - x1| + |y2 - y1|`. There are also some special roads. You are given a 2D array `specialRoads` where `specialRoads[i] = [x1i, y1i, x2i, y2i, costi]` indicates that the `ith` special road can take you from `(x1i, y1i)` to `(x2i, y2i)` with a cost equal to `costi`. You can use each special road any number of times. Return the minimum cost required to go from `(startX, startY)` to `(targetX, targetY)`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minimumCost(self, start: List[int], target: List[int], specialRoads: List[List[int]]) -> int: return self.dijkstra(specialRoads, *start, *target) def dijkstra(self, specialRoads: List[List[int]], srcX: int, srcY: int, dstX: int, dstY: int) -> int: n = len(specialRoads) dist = [math.inf] * n minHeap = [] for u, (x1, y1, _, _, cost) in enumerate(specialRoads): d = abs(x1 - srcX) + abs(y1 - srcY) + cost dist[u] = d heapq.heappush(minHeap, (dist[u], u)) while minHeap: d, u = heapq.heappop(minHeap) if d > dist[u]: continue _, _, ux2, uy2, _ = specialRoads[u] for v in range(n): if v == u: continue vx1, vy1, _, _, vcost = specialRoads[v] newDist = d + abs(vx1 - ux2) + abs(vy1 - uy2) + vcost if newDist < dist[v]: dist[v] = newDist heapq.heappush(minHeap, (dist[v], v)) ans = abs(dstX - srcX) + abs(dstY - srcY) for u in range(n): _, _, x2, y2, _ = specialRoads[u] ans = min(ans, dist[u] + abs(dstX - x2) + abs(dstY - y2)) return ans
class Solution { public int minimumCost(int[] start, int[] target, int[][] specialRoads) { return dijkstra(specialRoads, start[0], start[1], target[0], target[1]); } private int dijkstra(int[][] specialRoads, int srcX, int srcY, int dstX, int dstY) { final int n = specialRoads.length; // dist[i] := the minimum distance of (srcX, srcY) to // specialRoads[i](x2, y2) int[] dist = new int[n]; Arrays.fill(dist, Integer.MAX_VALUE); // (d, u), where u := the i-th specialRoads Queue<Pair<Integer, Integer>> minHeap = new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)); // (srcX, srcY) -> (x1, y1) to cost -> (x2, y2) for (int u = 0; u < n; ++u) { final int x1 = specialRoads[u][0]; final int y1 = specialRoads[u][1]; final int cost = specialRoads[u][4]; final int d = Math.abs(x1 - srcX) + Math.abs(y1 - srcY) + cost; dist[u] = d; minHeap.offer(new Pair<>(dist[u], u)); } while (!minHeap.isEmpty()) { final int d = minHeap.peek().getKey(); final int u = minHeap.poll().getValue(); if (d > dist[u]) continue; final int ux2 = specialRoads[u][2]; final int uy2 = specialRoads[u][3]; for (int v = 0; v < n; ++v) { if (v == u) continue; final int vx1 = specialRoads[v][0]; final int vy1 = specialRoads[v][1]; final int vcost = specialRoads[v][4]; // (ux2, uy2) -> (vx1, vy1) to vcost -> (vx2, vy2) final int newDist = d + Math.abs(vx1 - ux2) + Math.abs(vy1 - uy2) + vcost; if (newDist < dist[v]) { dist[v] = newDist; minHeap.offer(new Pair<>(dist[v], v)); } } } int ans = Math.abs(dstX - srcX) + Math.abs(dstY - srcY); for (int u = 0; u < n; ++u) { final int x2 = specialRoads[u][2]; final int y2 = specialRoads[u][3]; // (srcX, srcY) -> (x2, y2) -> (dstX, dstY). ans = Math.min(ans, dist[u] + Math.abs(dstX - x2) + Math.abs(dstY - y2)); } return ans; } }
class Solution { public: int minimumCost(vector<int>& start, vector<int>& target, vector<vector<int>>& specialRoads) { return dijkstra(specialRoads, start[0], start[1], target[0], target[1]); } private: int dijkstra(const vector<vector<int>>& specialRoads, int srcX, int srcY, int dstX, int dstY) { const int n = specialRoads.size(); // dist[i] := the minimum distance of (srcX, srcY) to // specialRoads[i](x2, y2) vector<int> dist(specialRoads.size(), INT_MAX); using P = pair<int, int>; // (d, u), where u := the i-th specialRoads priority_queue<P, vector<P>, greater<>> minHeap; // (srcX, srcY) -> (x1, y1) to cost -> (x2, y2) for (int u = 0; u < n; ++u) { const int x1 = specialRoads[u][0]; const int y1 = specialRoads[u][1]; const int cost = specialRoads[u][4]; const int d = abs(x1 - srcX) + abs(y1 - srcY) + cost; dist[u] = d; minHeap.emplace(dist[u], u); } while (!minHeap.empty()) { const auto [d, u] = minHeap.top(); minHeap.pop(); if (d > dist[u]) continue; const int ux2 = specialRoads[u][2]; const int uy2 = specialRoads[u][3]; for (int v = 0; v < n; ++v) { if (v == u) continue; const int vx1 = specialRoads[v][0]; const int vy1 = specialRoads[v][1]; const int vcost = specialRoads[v][4]; // (ux2, uy2) -> (vx1, vy1) to vcost -> (vx2, vy2) const int newDist = d + abs(vx1 - ux2) + abs(vy1 - uy2) + vcost; if (newDist < dist[v]) { dist[v] = newDist; minHeap.emplace(dist[v], v); } } } int ans = abs(dstX - srcX) + abs(dstY - srcY); for (int u = 0; u < n; ++u) { const int x2 = specialRoads[u][2]; const int y2 = specialRoads[u][3]; // (srcX, srcY) -> (x2, y2) -> (dstX, dstY). ans = min(ans, dist[u] + abs(dstX - x2) + abs(dstY - y2)); } return ans; } };
2,663
Lexicographically Smallest Beautiful String
3
smallestBeautifulString
A string is beautiful if: * It consists of the first `k` letters of the English lowercase alphabet. * It does not contain any substring of length `2` or more which is a palindrome. You are given a beautiful string `s` of length `n` and a positive integer `k`. Return the lexicographically smallest string of length `n`, which is larger than `s` and is beautiful. If there is no such string, return an empty string. A string `a` is lexicographically larger than a string `b` (of the same length) if in the first position where `a` and `b` differ, `a` has a character strictly larger than the corresponding character in `b`. * For example, `"abcd"` is lexicographically larger than `"abcc"` because the first position they differ is at the fourth character, and `d` is greater than `c`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def smallestBeautifulString(self, s: str, k: int) -> str: chars = list(s) for i in reversed(range(len(chars))): chars[i] = chr(ord(chars[i]) + 1) while self._containsPalindrome(chars, i): chars[i] = chr(ord(chars[i]) + 1) if chars[i] < chr(ord('a') + k): return self._changeSuffix(chars, i + 1) return '' def _containsPalindrome(self, chars: List[str], i: int) -> bool: return (i > 0 and chars[i] == chars[i - 1]) or (i > 1 and chars[i] == chars[i - 2]) def _changeSuffix(self, chars: List[str], i: int) -> str: for j in range(i, len(chars)): chars[j] = 'a' while self._containsPalindrome(chars, j): chars[j] = chr(ord(chars[j]) + 1) return ''.join(chars)
class Solution { public String smallestBeautifulString(String s, int k) { StringBuilder sb = new StringBuilder(s); for (int i = s.length() - 1; i >= 0; --i) { do { sb.setCharAt(i, (char) (sb.charAt(i) + 1)); } while (containsPalindrome(sb, i)); if (sb.charAt(i) < 'a' + k) // If sb[i] is among the first k letters, then change the letters after // sb[i] to the smallest ones that don't form any palindrome substring. return changeSuffix(sb, i + 1); } return ""; } // Returns true if sb[0..i] contains any palindrome. private boolean containsPalindrome(StringBuilder sb, int i) { return (i > 0 && sb.charAt(i) == sb.charAt(i - 1)) || (i > 1 && sb.charAt(i) == sb.charAt(i - 2)); } // Returns a string, where replacing sb[i..n) with the smallest possible // letters don't form any palindrome substring. private String changeSuffix(StringBuilder sb, int i) { for (int j = i; j < sb.length(); ++j) for (sb.setCharAt(j, 'a'); containsPalindrome(sb, j); sb.setCharAt(j, (char) (sb.charAt(j) + 1))) ; return sb.toString(); } }
class Solution { public: string smallestBeautifulString(string s, int k) { for (int i = s.length() - 1; i >= 0; --i) { do { ++s[i]; } while (containsPalindrome(s, i)); if (s[i] < 'a' + k) // If s[i] is among the first k letters, then change the letters after // s[i] to the smallest ones that don't form any palindrome substring. return changeSuffix(s, i + 1); } return ""; } private: // Returns true if s[0..i] contains any palindrome. bool containsPalindrome(const string& s, int i) { return (i > 0 && s[i] == s[i - 1]) || (i > 1 && s[i] == s[i - 2]); } // Returns a string, where replacing s[i..n) with the smallest possible // letters don't form any palindrome substring. string changeSuffix(string& s, int i) { for (int j = i; j < s.length(); ++j) for (s[j] = 'a'; containsPalindrome(s, j); ++s[j]) ; return s; } };
2,672
Number of Adjacent Elements With the Same Color
2
colorTheArray
There is a 0-indexed array `nums` of length `n`. Initially, all elements are uncolored (has a value of `0`). You are given a 2D integer array `queries` where `queries[i] = [indexi, colori]`. For each query, you color the index `indexi` with the color `colori` in the array `nums`. Return an array `answer` of the same length as `queries` where `answer[i]` is the number of adjacent elements with the same color after the `ith` query. More formally, `answer[i]` is the number of indices `j`, such that `0 <= j < n - 1` and `nums[j] == nums[j + 1]` and `nums[j] != 0` after the `ith` query.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def colorTheArray(self, n: int, queries: List[List[int]]) -> List[int]: ans = [] arr = [0] * n sameColors = 0 for i, color in queries: if i + 1 < n: if arr[i + 1] > 0 and arr[i + 1] == arr[i]: sameColors -= 1 if arr[i + 1] == color: sameColors += 1 if i > 0: if arr[i - 1] > 0 and arr[i - 1] == arr[i]: sameColors -= 1 if arr[i - 1] == color: sameColors += 1 arr[i] = color ans.append(sameColors) return ans
class Solution { public int[] colorTheArray(int n, int[][] queries) { int[] ans = new int[queries.length]; int[] arr = new int[n]; int sameColors = 0; for (int i = 0; i < queries.length; ++i) { final int j = queries[i][0]; final int color = queries[i][1]; if (j + 1 < n) { if (arr[j + 1] > 0 && arr[j + 1] == arr[j]) --sameColors; if (arr[j + 1] == color) ++sameColors; } if (j > 0) { if (arr[j - 1] > 0 && arr[j - 1] == arr[j]) --sameColors; if (arr[j - 1] == color) ++sameColors; } arr[j] = color; ans[i] = sameColors; } return ans; } }
class Solution { public: vector<int> colorTheArray(int n, vector<vector<int>>& queries) { vector<int> ans; vector<int> arr(n); int sameColors = 0; for (const vector<int>& query : queries) { const int i = query[0]; const int color = query[1]; if (i + 1 < n) { if (arr[i + 1] > 0 && arr[i + 1] == arr[i]) --sameColors; if (arr[i + 1] == color) ++sameColors; } if (i > 0) { if (arr[i - 1] > 0 && arr[i - 1] == arr[i]) --sameColors; if (arr[i - 1] == color) ++sameColors; } arr[i] = color; ans.push_back(sameColors); } return ans; } };
2,684
Maximum Number of Moves in a Grid
2
maxMoves
You are given a 0-indexed `m x n` matrix `grid` consisting of positive integers. You can start at any cell in the first column of the matrix, and traverse the grid in the following way: * From a cell `(row, col)`, you can move to any of the cells: `(row - 1, col + 1)`, `(row, col + 1)` and `(row + 1, col + 1)` such that the value of the cell you move to, should be strictly bigger than the value of the current cell. Return the maximum number of moves that you can perform.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def maxMoves(self, grid: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) dp = [[0] * n for _ in range(m)] for j in range(n - 2, -1, -1): for i in range(m): if grid[i][j + 1] > grid[i][j]: dp[i][j] = 1 + dp[i][j + 1] if i > 0 and grid[i - 1][j + 1] > grid[i][j]: dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j + 1]) if i + 1 < m and grid[i + 1][j + 1] > grid[i][j]: dp[i][j] = max(dp[i][j], 1 + dp[i + 1][j + 1]) return max(dp[i][0] for i in range(m))
class Solution { public int maxMoves(int[][] grid) { final int m = grid.length; final int n = grid[0].length; int ans = 0; // dp[i][j] := the maximum number of moves you can perform from (i, j) int[][] dp = new int[m][n]; for (int j = n - 2; j >= 0; --j) for (int i = 0; i < m; ++i) { if (grid[i][j + 1] > grid[i][j]) dp[i][j] = 1 + dp[i][j + 1]; if (i > 0 && grid[i - 1][j + 1] > grid[i][j]) dp[i][j] = Math.max(dp[i][j], 1 + dp[i - 1][j + 1]); if (i + 1 < m && grid[i + 1][j + 1] > grid[i][j]) dp[i][j] = Math.max(dp[i][j], 1 + dp[i + 1][j + 1]); } for (int i = 0; i < m; ++i) ans = Math.max(ans, dp[i][0]); return ans; } }
class Solution { public: int maxMoves(vector<vector<int>>& grid) { const int m = grid.size(); const int n = grid[0].size(); int ans = 0; // dp[i][j] := the maximum number of moves you can perform from (i, j) vector<vector<int>> dp(m, vector<int>(n)); for (int j = n - 2; j >= 0; --j) for (int i = 0; i < m; ++i) { if (grid[i][j + 1] > grid[i][j]) dp[i][j] = 1 + dp[i][j + 1]; if (i > 0 && grid[i - 1][j + 1] > grid[i][j]) dp[i][j] = max(dp[i][j], 1 + dp[i - 1][j + 1]); if (i + 1 < m && grid[i + 1][j + 1] > grid[i][j]) dp[i][j] = max(dp[i][j], 1 + dp[i + 1][j + 1]); } for (int i = 0; i < m; ++i) ans = max(ans, dp[i][0]); return ans; } };
2,685
Count the Number of Complete Components
2
countCompleteComponents
You are given an integer `n`. There is an undirected graph with `n` vertices, numbered from `0` to `n - 1`. You are given a 2D integer array `edges` where `edges[i] = [ai, bi]` denotes that there exists an undirected edge connecting vertices `ai` and `bi`. Return the number of complete connected components of the graph. A connected component is a subgraph of a graph in which there exists a path between any two vertices, and no vertex of the subgraph shares an edge with a vertex outside of the subgraph. A connected component is said to be complete if there exists an edge between every pair of its vertices.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class UnionFind: def __init__(self, n: int): self.id = list(range(n)) self.rank = [0] * n self.nodeCount = [1] * n self.edgeCount = [0] * n def unionByRank(self, u: int, v: int) -> None: i = self.find(u) j = self.find(v) self.edgeCount[i] += 1 if i == j: return if self.rank[i] < self.rank[j]: self.id[i] = j self.edgeCount[j] += self.edgeCount[i] self.nodeCount[j] += self.nodeCount[i] elif self.rank[i] > self.rank[j]: self.id[j] = i self.edgeCount[i] += self.edgeCount[j] self.nodeCount[i] += self.nodeCount[j] else: self.id[i] = j self.edgeCount[j] += self.edgeCount[i] self.nodeCount[j] += self.nodeCount[i] self.rank[j] += 1 def find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self.find(self.id[u]) return self.id[u] def isComplete(self, u): return self.nodeCount[u] * (self.nodeCount[u] - 1) // 2 == self.edgeCount[u] class Solution: def countCompleteComponents(self, n: int, edges: List[List[int]]) -> int: ans = 0 uf = UnionFind(n) parents = set() for u, v in edges: uf.unionByRank(u, v) for i in range(n): parent = uf.find(i) if parent not in parents and uf.isComplete(parent): ans += 1 parents.add(parent) return ans
class UnionFind { public UnionFind(int n) { id = new int[n]; rank = new int[n]; nodeCount = new int[n]; edgeCount = new int[n]; for (int i = 0; i < n; ++i) { id[i] = i; nodeCount[i] = 1; } } public void unionByRank(int u, int v) { final int i = find(u); final int j = find(v); ++edgeCount[i]; if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; edgeCount[j] += edgeCount[i]; nodeCount[j] += nodeCount[i]; } else if (rank[i] > rank[j]) { id[j] = i; edgeCount[i] += edgeCount[j]; nodeCount[i] += nodeCount[j]; } else { id[i] = j; edgeCount[j] += edgeCount[i]; nodeCount[j] += nodeCount[i]; ++rank[j]; } } public int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } public boolean isComplete(int u) { return nodeCount[u] * (nodeCount[u] - 1) / 2 == edgeCount[u]; } private int[] id; private int[] rank; private int[] nodeCount; private int[] edgeCount; } class Solution { public int countCompleteComponents(int n, int[][] edges) { int ans = 0; UnionFind uf = new UnionFind(n); Set<Integer> parents = new HashSet<>(); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; uf.unionByRank(u, v); } for (int i = 0; i < n; ++i) { final int parent = uf.find(i); if (parents.add(parent) && uf.isComplete(parent)) ++ans; } return ans; } }
class UnionFind { public: UnionFind(int n) : id(n), rank(n), nodeCount(n, 1), edgeCount(n) { iota(id.begin(), id.end(), 0); } void unionByRank(int u, int v) { const int i = find(u); const int j = find(v); ++edgeCount[i]; if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; edgeCount[j] += edgeCount[i]; nodeCount[j] += nodeCount[i]; } else if (rank[i] > rank[j]) { id[j] = i; edgeCount[i] += edgeCount[j]; nodeCount[i] += nodeCount[j]; } else { id[i] = j; edgeCount[j] += edgeCount[i]; nodeCount[j] += nodeCount[i]; ++rank[j]; } } int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } bool isComplete(int u) { return nodeCount[u] * (nodeCount[u] - 1) / 2 == edgeCount[u]; } private: vector<int> id; vector<int> rank; vector<int> nodeCount; vector<int> edgeCount; }; class Solution { public: int countCompleteComponents(int n, vector<vector<int>>& edges) { int ans = 0; UnionFind uf(n); unordered_set<int> parents; for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; uf.unionByRank(u, v); } for (int i = 0; i < n; ++i) { const int parent = uf.find(i); if (parents.insert(parent).second && uf.isComplete(parent)) ++ans; } return ans; } };
2,699
Modify Graph Edge Weights
3
modifiedGraphEdges
You are given an undirected weighted connected graph containing `n` nodes labeled from `0` to `n - 1`, and an integer array `edges` where `edges[i] = [ai, bi, wi]` indicates that there is an edge between nodes `ai` and `bi` with weight `wi`. Some edges have a weight of `-1` (`wi = -1`), while others have a positive weight (`wi > 0`). Your task is to modify all edges with a weight of `-1` by assigning them positive integer values in the range `[1, 2 * 109]` so that the shortest distance between the nodes `source` and `destination` becomes equal to an integer `target`. If there are multiple modifications that make the shortest distance between `source` and `destination` equal to `target`, any of them will be considered correct. Return an array containing all edges (even unmodified ones) in any order if it is possible to make the shortest distance from `source` to `destination` equal to `target`, or an empty array if it's impossible. Note: You are not allowed to modify the weights of edges with initial positive weights.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def modifiedGraphEdges(self, n: int, edges: List[List[int]], source: int, destination: int, target: int) -> List[List[int]]: kMax = 2_000_000_000 graph = [[] for _ in range(n)] for u, v, w in edges: if w == -1: continue graph[u].append((v, w)) graph[v].append((u, w)) distToDestination = self._dijkstra(graph, source, destination) if distToDestination < target: return [] if distToDestination == target: for edge in edges: if edge[2] == -1: edge[2] = kMax return edges for i, (u, v, w) in enumerate(edges): if w != -1: continue edges[i][2] = 1 graph[u].append((v, 1)) graph[v].append((u, 1)) distToDestination = self._dijkstra(graph, source, destination) if distToDestination <= target: edges[i][2] += target - distToDestination for j in range(i + 1, len(edges)): if edges[j][2] == -1: edges[j][2] = kMax return edges return [] def _dijkstra(self, graph: List[List[int]], src: int, dst: int) -> int: dist = [math.inf] * len(graph) minHeap = [] dist[src] = 0 heapq.heappush(minHeap, (dist[src], src)) while minHeap: d, u = heapq.heappop(minHeap) if d > dist[u]: continue for v, w in graph[u]: if d + w < dist[v]: dist[v] = d + w heapq.heappush(minHeap, (dist[v], v)) return dist[dst]
class Solution { public int[][] modifiedGraphEdges(int n, int[][] edges, int source, int destination, int target) { final int MAX = 2_000_000_000; List<Pair<Integer, Integer>>[] graph = new List[n]; for (int i = 0; i < n; i++) graph[i] = new ArrayList<>(); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; final int w = edge[2]; if (w == -1) continue; graph[u].add(new Pair<>(v, w)); graph[v].add(new Pair<>(u, w)); } int distToDestination = dijkstra(graph, source, destination); if (distToDestination < target) return new int[0][]; if (distToDestination == target) { // Change the weights of negative edges to an impossible value. for (int[] edge : edges) if (edge[2] == -1) edge[2] = MAX; return edges; } for (int i = 0; i < edges.length; ++i) { final int u = edges[i][0]; final int v = edges[i][1]; final int w = edges[i][2]; if (w != -1) continue; edges[i][2] = 1; graph[u].add(new Pair<>(v, 1)); graph[v].add(new Pair<>(u, 1)); distToDestination = dijkstra(graph, source, destination); if (distToDestination <= target) { edges[i][2] += target - distToDestination; // Change the weights of negative edges to an impossible value. for (int j = i + 1; j < edges.length; ++j) if (edges[j][2] == -1) edges[j][2] = MAX; return edges; } } return new int[0][]; } private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst) { int[] dist = new int[graph.length]; Arrays.fill(dist, Integer.MAX_VALUE); dist[src] = 0; Queue<Pair<Integer, Integer>> minHeap = new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)) { { offer(new Pair<>(dist[src], src)); } // (d, u) }; while (!minHeap.isEmpty()) { final int d = minHeap.peek().getKey(); final int u = minHeap.poll().getValue(); if (d > dist[u]) continue; for (Pair<Integer, Integer> pair : graph[u]) { final int v = pair.getKey(); final int w = pair.getValue(); if (d + w < dist[v]) { dist[v] = d + w; minHeap.offer(new Pair<>(dist[v], v)); } } } return dist[dst]; } }
class Solution { public: vector<vector<int>> modifiedGraphEdges(int n, vector<vector<int>>& edges, int source, int destination, int target) { constexpr int kMax = 2'000'000'000; vector<vector<pair<int, int>>> graph(n); for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; const int w = edge[2]; if (w == -1) continue; graph[u].emplace_back(v, w); graph[v].emplace_back(u, w); } int distToDestination = dijkstra(graph, source, destination); if (distToDestination < target) return {}; if (distToDestination == target) { // Change the weights of negative edges to an impossible value. for (vector<int>& edge : edges) if (edge[2] == -1) edge[2] = kMax; return edges; } for (int i = 0; i < edges.size(); ++i) { const int u = edges[i][0]; const int v = edges[i][1]; int& w = edges[i][2]; if (w != -1) continue; w = 1; graph[u].emplace_back(v, 1); graph[v].emplace_back(u, 1); distToDestination = dijkstra(graph, source, destination); if (distToDestination <= target) { w += target - distToDestination; // Change the weights of negative edges to an impossible value. for (int j = i + 1; j < edges.size(); ++j) if (edges[j][2] == -1) edges[j][2] = kMax; return edges; } } return {}; } private: int dijkstra(const vector<vector<pair<int, int>>>& graph, int src, int dst) { vector<int> dist(graph.size(), INT_MAX); dist[src] = 0; using P = pair<int, int>; // (d, u) priority_queue<P, vector<P>, greater<>> minHeap; minHeap.emplace(dist[src], src); while (!minHeap.empty()) { const auto [d, u] = minHeap.top(); minHeap.pop(); if (d > dist[u]) continue; for (const auto& [v, w] : graph[u]) if (d + w < dist[v]) { dist[v] = d + w; minHeap.emplace(dist[v], v); } } return dist[dst]; } };
2,708
Maximum Strength of a Group
2
maxStrength
You are given a 0-indexed integer array `nums` representing the score of students in an exam. The teacher would like to form one non-empty group of students with maximal strength, where the strength of a group of students of indices `i0`, `i1`, `i2`, ... , `ik` is defined as `nums[i0] * nums[i1] * nums[i2] * ... * nums[ik​]`. Return the maximum strength of a group the teacher can create.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def maxStrength(self, nums: List[int]) -> int: posProd = 1 negProd = 1 maxNeg = -math.inf negCount = 0 hasPos = False hasZero = False for num in nums: if num > 0: posProd *= num hasPos = True elif num < 0: negProd *= num maxNeg = max(maxNeg, num) negCount += 1 else: hasZero = True if negCount == 0 and not hasPos: return 0 if negCount % 2 == 0: return negProd * posProd if negCount >= 3: return negProd // maxNeg * posProd if hasPos: return posProd if hasZero: return 0 return maxNeg
class Solution { public long maxStrength(int[] nums) { long posProd = 1; long negProd = 1; int maxNeg = Integer.MIN_VALUE; int negCount = 0; boolean hasPos = false; boolean hasZero = false; for (final int num : nums) if (num > 0) { posProd *= num; hasPos = true; } else if (num < 0) { negProd *= num; maxNeg = Math.max(maxNeg, num); ++negCount; } else { // num == 0 hasZero = true; } if (negCount == 0 && !hasPos) return 0; if (negCount % 2 == 0) return negProd * posProd; if (negCount >= 3) return negProd / maxNeg * posProd; if (hasPos) return posProd; if (hasZero) return 0; return maxNeg; } }
class Solution { public: long long maxStrength(vector<int>& nums) { long posProd = 1; long negProd = 1; int maxNeg = INT_MIN; int negCount = 0; bool hasPos = false; bool hasZero = false; for (const int num : nums) if (num > 0) { posProd *= num; hasPos = true; } else if (num < 0) { negProd *= num; maxNeg = max(maxNeg, num); ++negCount; } else { // num == 0 hasZero = true; } if (negCount == 0 && !hasPos) return 0; if (negCount % 2 == 0) return negProd * posProd; if (negCount >= 3) return negProd / maxNeg * posProd; if (hasPos) return posProd; if (hasZero) return 0; return maxNeg; } };
2,709
Greatest Common Divisor Traversal
3
canTraverseAllPairs
You are given a 0-indexed integer array `nums`, and you are allowed to traverse between its indices. You can traverse between index `i` and index `j`, `i != j`, if and only if `gcd(nums[i], nums[j]) > 1`, where `gcd` is the greatest common divisor. Your task is to determine if for every pair of indices `i` and `j` in nums, where `i < j`, there exists a sequence of traversals that can take us from `i` to `j`. Return `true` if it is possible to traverse between all such pairs of indices, or `false` otherwise.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class UnionFind: def __init__(self, n: int): self.id = list(range(n)) self.sz = [1] * n def unionBySize(self, u: int, v: int) -> None: i = self._find(u) j = self._find(v) if i == j: return if self.sz[i] < self.sz[j]: self.sz[j] += self.sz[i] self.id[i] = j else: self.sz[i] += self.sz[j] self.id[j] = i def getSize(self, i: int) -> int: return self.sz[i] def _find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self._find(self.id[u]) return self.id[u] class Solution: def canTraverseAllPairs(self, nums: List[int]) -> bool: n = len(nums) max_num = max(nums) maxPrimeFactor = self._sieveEratosthenes(max_num + 1) primeToFirstIndex = collections.defaultdict(int) uf = UnionFind(n) for i, num in enumerate(nums): for prime_factor in self._getPrimeFactors(num, maxPrimeFactor): if prime_factor in primeToFirstIndex: uf.unionBySize(primeToFirstIndex[prime_factor], i) else: primeToFirstIndex[prime_factor] = i return any(uf.getSize(i) == n for i in range(n)) def _sieveEratosthenes(self, n: int) -> List[int]: minPrimeFactors = [i for i in range(n + 1)] for i in range(2, int(n**0.5) + 1): if minPrimeFactors[i] == i: for j in range(i * i, n, i): minPrimeFactors[j] = min(minPrimeFactors[j], i) return minPrimeFactors def _getPrimeFactors(self, num: int, minPrimeFactors: List[int]) -> List[int]: primeFactors = [] while num > 1: divisor = minPrimeFactors[num] primeFactors.append(divisor) while num % divisor == 0: num //= divisor return primeFactors
class UnionFind { public UnionFind(int n) { id = new int[n]; sz = new int[n]; for (int i = 0; i < n; ++i) id[i] = i; for (int i = 0; i < n; ++i) sz[i] = 1; } public void unionBySize(int u, int v) { final int i = find(u); final int j = find(v); if (i == j) return; if (sz[i] < sz[j]) { sz[j] += sz[i]; id[i] = j; } else { sz[i] += sz[j]; id[j] = i; } } public int getSize(int i) { return sz[i]; } private int[] id; private int[] sz; private int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } } class Solution { public boolean canTraverseAllPairs(int[] nums) { final int n = nums.length; final int mx = Arrays.stream(nums).max().getAsInt(); final int[] minPrimeFactors = sieveEratosthenes(mx + 1); Map<Integer, Integer> primeToFirstIndex = new HashMap<>(); UnionFind uf = new UnionFind(n); for (int i = 0; i < n; ++i) for (final int primeFactor : getPrimeFactors(nums[i], minPrimeFactors)) // `primeFactor` already appeared in the previous indices. if (primeToFirstIndex.containsKey(primeFactor)) uf.unionBySize(primeToFirstIndex.get(primeFactor), i); else primeToFirstIndex.put(primeFactor, i); for (int i = 0; i < n; ++i) if (uf.getSize(i) == n) return true; return false; } // Gets the minimum prime factor of i, where 1 < i <= n. private int[] sieveEratosthenes(int n) { int[] minPrimeFactors = new int[n + 1]; for (int i = 2; i <= n; ++i) minPrimeFactors[i] = i; for (int i = 2; i * i < n; ++i) if (minPrimeFactors[i] == i) // `i` is prime. for (int j = i * i; j < n; j += i) minPrimeFactors[j] = Math.min(minPrimeFactors[j], i); return minPrimeFactors; } private List<Integer> getPrimeFactors(int num, int[] minPrimeFactors) { List<Integer> primeFactors = new ArrayList<>(); while (num > 1) { final int divisor = minPrimeFactors[num]; primeFactors.add(divisor); while (num % divisor == 0) num /= divisor; } return primeFactors; } }
class UnionFind { public: UnionFind(int n) : id(n), sz(n, 1) { iota(id.begin(), id.end(), 0); } void unionBySize(int u, int v) { const int i = find(u); const int j = find(v); if (i == j) return; if (sz[i] < sz[j]) { sz[j] += sz[i]; id[i] = j; } else { sz[i] += sz[j]; id[j] = i; } } int getSize(int i) { return sz[i]; } private: vector<int> id; vector<int> sz; int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } }; class Solution { public: bool canTraverseAllPairs(vector<int>& nums) { const int n = nums.size(); const int mx = ranges::max(nums); const vector<int> minPrimeFactors = sieveEratosthenes(mx + 1); unordered_map<int, int> primeToFirstIndex; UnionFind uf(n); for (int i = 0; i < n; ++i) for (const int primeFactor : getPrimeFactors(nums[i], minPrimeFactors)) // `primeFactor` already appeared in the previous indices. if (const auto it = primeToFirstIndex.find(primeFactor); it != primeToFirstIndex.cend()) uf.unionBySize(it->second, i); else primeToFirstIndex[primeFactor] = i; for (int i = 0; i < n; ++i) if (uf.getSize(i) == n) return true; return false; } private: // Gets the minimum prime factor of i, where 1 < i <= n. vector<int> sieveEratosthenes(int n) { vector<int> minPrimeFactors(n + 1); iota(minPrimeFactors.begin() + 2, minPrimeFactors.end(), 2); for (int i = 2; i * i < n; ++i) if (minPrimeFactors[i] == i) // `i` is prime. for (int j = i * i; j < n; j += i) minPrimeFactors[j] = min(minPrimeFactors[j], i); return minPrimeFactors; } vector<int> getPrimeFactors(int num, const vector<int>& minPrimeFactors) { vector<int> primeFactors; while (num > 1) { const int divisor = minPrimeFactors[num]; primeFactors.push_back(divisor); while (num % divisor == 0) num /= divisor; } return primeFactors; } };
2,736
Maximum Sum Queries
3
maximumSumQueries
You are given two 0-indexed integer arrays `nums1` and `nums2`, each of length `n`, and a 1-indexed 2D array `queries` where `queries[i] = [xi, yi]`. For the `ith` query, find the maximum value of `nums1[j] + nums2[j]` among all indices `j` `(0 <= j < n)`, where `nums1[j] >= xi` and `nums2[j] >= yi`, or -1 if there is no `j` satisfying the constraints. Return an array `answer` where `answer[i]` is the answer to the `ith` query.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Pair: def __init__(self, x: int, y: int): self.x = x self.y = y def __iter__(self): yield self.x yield self.y class IndexedQuery: def __init__(self, queryIndex: int, minX: int, minY: int): self.queryIndex = queryIndex self.minX = minX self.minY = minY def __iter__(self): yield self.queryIndex yield self.minX yield self.minY class Solution: def maximumSumQueries(self, nums1: List[int], nums2: List[int], queries: List[List[int]]) -> List[int]: pairs = sorted([Pair(nums1[i], nums2[i]) for i in range(len(nums1))], key=lambda p: p.x, reverse=True) ans = [0] * len(queries) stack = [] # [(y, x + y)] pairsIndex = 0 for queryIndex, minX, minY in sorted([IndexedQuery(i, query[0], query[1]) for i, query in enumerate(queries)], key=lambda iq: -iq.minX): while pairsIndex < len(pairs) and pairs[pairsIndex].x >= minX: x, y = pairs[pairsIndex] while stack and x + y >= stack[-1][1]: stack.pop() if not stack or y > stack[-1][0]: stack.append((y, x + y)) pairsIndex += 1 j = self._firstGreaterEqual(stack, minY) if j == len(stack): ans[queryIndex] = -1 else: ans[queryIndex] = stack[j][1] return ans def _firstGreaterEqual(self, A: List[Tuple[int, int]], target: int) -> int: l = 0 r = len(A) while l < r: m = (l + r) // 2 if A[m][0] >= target: r = m else: l = m + 1 return l
class Solution { public int[] maximumSumQueries(int[] nums1, int[] nums2, int[][] queries) { MyPair[] pairs = getPairs(nums1, nums2); IndexedQuery[] indexedQueries = getIndexedQueries(queries); int[] ans = new int[queries.length]; List<Pair<Integer, Integer>> stack = new ArrayList<>(); // [(y, x + y)] int pairsIndex = 0; for (IndexedQuery indexedQuery : indexedQueries) { final int queryIndex = indexedQuery.queryIndex; final int minX = indexedQuery.minX; final int minY = indexedQuery.minY; while (pairsIndex < pairs.length && pairs[pairsIndex].x >= minX) { MyPair pair = pairs[pairsIndex++]; // x + y is a better candidate. Given that x is decreasing, the // condition "x + y >= stack.get(stack.size() - 1).getValue()" suggests // that y is relatively larger, thereby making it a better candidate. final int x = pair.x; final int y = pair.y; while (!stack.isEmpty() && x + y >= stack.get(stack.size() - 1).getValue()) stack.remove(stack.size() - 1); if (stack.isEmpty() || y > stack.get(stack.size() - 1).getKey()) stack.add(new Pair<>(y, x + y)); } final int j = firstGreaterEqual(stack, minY); ans[queryIndex] = j == stack.size() ? -1 : stack.get(j).getValue(); } return ans; } private record MyPair(int x, int y){}; private record IndexedQuery(int queryIndex, int minX, int minY){}; private int firstGreaterEqual(List<Pair<Integer, Integer>> A, int target) { int l = 0; int r = A.size(); while (l < r) { final int m = (l + r) / 2; if (A.get(m).getKey() >= target) r = m; else l = m + 1; } return l; } private MyPair[] getPairs(int[] nums1, int[] nums2) { MyPair[] pairs = new MyPair[nums1.length]; for (int i = 0; i < nums1.length; ++i) pairs[i] = new MyPair(nums1[i], nums2[i]); Arrays.sort(pairs, Comparator.comparing(MyPair::x, Comparator.reverseOrder())); return pairs; } private IndexedQuery[] getIndexedQueries(int[][] queries) { IndexedQuery[] indexedQueries = new IndexedQuery[queries.length]; for (int i = 0; i < queries.length; ++i) indexedQueries[i] = new IndexedQuery(i, queries[i][0], queries[i][1]); Arrays.sort(indexedQueries, Comparator.comparing(IndexedQuery::minX, Comparator.reverseOrder())); return indexedQueries; } }
struct Pair { int x; int y; }; struct IndexedQuery { int queryIndex; int minX; int minY; }; class Solution { public: vector<int> maximumSumQueries(vector<int>& nums1, vector<int>& nums2, vector<vector<int>>& queries) { const vector<Pair> pairs = getPairs(nums1, nums2); vector<int> ans(queries.size()); vector<pair<int, int>> stack; // [(y, x + y)] int pairsIndex = 0; for (const auto& [queryIndex, minX, minY] : getIndexedQueries(queries)) { while (pairsIndex < pairs.size() && pairs[pairsIndex].x >= minX) { const auto [x, y] = pairs[pairsIndex++]; // x + y is a better candidate. Given that x is decreasing, the // condition "x + y >= stack.back().second" suggests that y is // relatively larger, thereby making it a better candidate. while (!stack.empty() && x + y >= stack.back().second) stack.pop_back(); if (stack.empty() || y > stack.back().first) stack.emplace_back(y, x + y); } const auto it = ranges::lower_bound(stack, pair<int, int>{minY, INT_MIN}); ans[queryIndex] = it == stack.end() ? -1 : it->second; } return ans; } private: vector<Pair> getPairs(const vector<int>& nums1, const vector<int>& nums2) { vector<Pair> pairs; for (int i = 0; i < nums1.size(); ++i) pairs.push_back({nums1[i], nums2[i]}); ranges::sort(pairs, ranges::greater{}, [](const Pair& pair) { return pair.x; }); return pairs; } vector<IndexedQuery> getIndexedQueries(const vector<vector<int>>& queries) { vector<IndexedQuery> indexedQueries; for (int i = 0; i < queries.size(); ++i) indexedQueries.push_back({i, queries[i][0], queries[i][1]}); ranges::sort(indexedQueries, [](const IndexedQuery& a, const IndexedQuery& b) { return a.minX > b.minX; }); return indexedQueries; } };
2,747
Count Zero Request Servers
2
countServers
You are given an integer `n` denoting the total number of servers and a 2D 0-indexed integer array `logs`, where `logs[i] = [server_id, time]` denotes that the server with id `server_id` received a request at time `time`. You are also given an integer `x` and a 0-indexed integer array `queries`. Return a 0-indexed integer array `arr` of length `queries.length` where `arr[i]` represents the number of servers that did not receive any requests during the time interval `[queries[i] - x, queries[i]]`. Note that the time intervals are inclusive.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class IndexedQuery: def __init__(self, queryIndex: int, query: int): self.queryIndex = queryIndex self.query = query def __iter__(self): yield self.queryIndex yield self.query class Solution: def countServers(self, n: int, logs: List[List[int]], x: int, queries: List[int]) -> List[int]: ans = [0] * len(queries) count = [0] * (n + 1) logs.sort(key=lambda log: log[1]) i = 0 j = 0 servers = 0 for queryIndex, query in sorted([IndexedQuery(i, query) for i, query in enumerate(queries)], key=lambda iq: iq.query): while j < len(logs) and logs[j][1] <= query: count[logs[j][0]] += 1 if count[logs[j][0]] == 1: servers += 1 j += 1 while i < len(logs) and logs[i][1] < query - x: count[logs[i][0]] -= 1 if count[logs[i][0]] == 0: servers -= 1 i += 1 ans[queryIndex] = n - servers return ans
class Solution { public int[] countServers(int n, int[][] logs, int x, int[] queries) { int[] ans = new int[queries.length]; int[] count = new int[n + 1]; Arrays.sort(logs, Comparator.comparingInt(log -> log[1])); int i = 0; int j = 0; int servers = 0; // For each query, we care about logs[i..j]. for (IndexedQuery indexedQuery : getIndexedQueries(queries)) { final int queryIndex = indexedQuery.queryIndex; final int query = indexedQuery.query; for (; j < logs.length && logs[j][1] <= query; ++j) if (++count[logs[j][0]] == 1) ++servers; for (; i < logs.length && logs[i][1] < query - x; ++i) if (--count[logs[i][0]] == 0) --servers; ans[queryIndex] = n - servers; } return ans; } private record IndexedQuery(int queryIndex, int query){}; private IndexedQuery[] getIndexedQueries(int[] queries) { IndexedQuery[] indexedQueries = new IndexedQuery[queries.length]; for (int i = 0; i < queries.length; ++i) indexedQueries[i] = new IndexedQuery(i, queries[i]); Arrays.sort(indexedQueries, Comparator.comparingInt(IndexedQuery::query)); return indexedQueries; } }
struct IndexedQuery { int queryIndex; int query; }; class Solution { public: vector<int> countServers(int n, vector<vector<int>>& logs, int x, vector<int>& queries) { vector<int> ans(queries.size()); vector<int> count(n + 1); ranges::sort(logs, ranges::less{}, [](const vector<int>& log) { return log[1]; }); int i = 0; int j = 0; int servers = 0; // For each query, we care about logs[i..j]. for (const auto& [queryIndex, query] : getIndexedQueries(queries)) { for (; j < logs.size() && logs[j][1] <= query; ++j) if (++count[logs[j][0]] == 1) ++servers; for (; i < logs.size() && logs[i][1] < query - x; ++i) if (--count[logs[i][0]] == 0) --servers; ans[queryIndex] = n - servers; } return ans; } private: vector<IndexedQuery> getIndexedQueries(const vector<int>& queries) { vector<IndexedQuery> indexedQueries; for (int i = 0; i < queries.size(); ++i) indexedQueries.push_back({i, queries[i]}); ranges::sort(indexedQueries, [](const IndexedQuery& a, const IndexedQuery& b) { return a.query < b.query; }); return indexedQueries; } };
2,751
Robot Collisions
3
survivedRobotsHealths
There are `n` 1-indexed robots, each having a position on a line, health, and movement direction. You are given 0-indexed integer arrays `positions`, `healths`, and a string `directions` (`directions[i]` is either 'L' for left or 'R' for right). All integers in `positions` are unique. All robots start moving on the line simultaneously at the same speed in their given directions. If two robots ever share the same position while moving, they will collide. If two robots collide, the robot with lower health is removed from the line, and the health of the other robot decreases by one. The surviving robot continues in the same direction it was going. If both robots have the same health, they are both removed from the line. Your task is to determine the health of the robots that survive the collisions, in the same order that the robots were given, i.e. final heath of robot 1 (if survived), final health of robot 2 (if survived), and so on. If there are no survivors, return an empty array. Return an array containing the health of the remaining robots (in the order they were given in the input), after no further collisions can occur. Note: The positions may be unsorted.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator from dataclasses import dataclass @dataclass class Robot: index: int position: int health: int direction: str class Solution: def survivedRobotsHealths(self, positions: List[int], healths: List[int], directions: str) -> List[int]: robots = sorted([Robot(index, position, health, direction) for index, (position, health, direction) in enumerate(zip(positions, healths, directions))], key=lambda robot: robot.position) stack: List[Robot] = [] for robot in robots: if robot.direction == 'R': stack.append(robot) continue while stack and stack[-1].direction == 'R' and robot.health > 0: if stack[-1].health == robot.health: stack.pop() robot.health = 0 elif stack[-1].health < robot.health: stack.pop() robot.health -= 1 else: stack[-1].health -= 1 robot.health = 0 if robot.health > 0: stack.append(robot) stack.sort(key=lambda robot: robot.index) return [robot.health for robot in stack]
class Robot { public int index; public int position; public int health; public char direction; public Robot(int index, int position, int health, char direction) { this.index = index; this.position = position; this.health = health; this.direction = direction; } } class Solution { public List<Integer> survivedRobotsHealths(int[] positions, int[] healths, String directions) { List<Integer> ans = new ArrayList<>(); Robot[] robots = new Robot[positions.length]; List<Robot> stack = new ArrayList<>(); // running robots for (int i = 0; i < positions.length; ++i) robots[i] = new Robot(i, positions[i], healths[i], directions.charAt(i)); Arrays.sort(robots, Comparator.comparingInt((Robot robot) -> robot.position)); for (Robot robot : robots) { if (robot.direction == 'R') { stack.add(robot); continue; } // Collide with robots going right if any. while (!stack.isEmpty() && stack.get(stack.size() - 1).direction == 'R' && robot.health > 0) { if (stack.get(stack.size() - 1).health == robot.health) { stack.remove(stack.size() - 1); robot.health = 0; } else if (stack.get(stack.size() - 1).health < robot.health) { stack.remove(stack.size() - 1); robot.health -= 1; } else { // stack[-1].health > robot.health stack.get(stack.size() - 1).health -= 1; robot.health = 0; } } if (robot.health > 0) stack.add(robot); } stack.sort(Comparator.comparingInt((Robot robot) -> robot.index)); for (Robot robot : stack) ans.add(robot.health); return ans; } }
struct Robot { int index; int position; int health; char direction; }; class Solution { public: vector<int> survivedRobotsHealths(vector<int>& positions, vector<int>& healths, string directions) { vector<int> ans; vector<Robot> robots; vector<Robot> stack; // the runnnig robots for (int i = 0; i < positions.size(); ++i) robots.push_back(Robot{i, positions[i], healths[i], directions[i]}); ranges::sort(robots, ranges::less{}, [](const Robot& robot) { return robot.position; }); for (Robot& robot : robots) { if (robot.direction == 'R') { stack.push_back(robot); continue; } // Collide with robots going right if any. while (!stack.empty() && stack.back().direction == 'R' && robot.health > 0) { if (stack.back().health == robot.health) { stack.pop_back(); robot.health = 0; } else if (stack.back().health < robot.health) { stack.pop_back(); robot.health -= 1; } else { // stack.back().health > robot.health stack.back().health -= 1; robot.health = 0; } } if (robot.health > 0) stack.push_back(robot); } ranges::sort(stack, ranges::less{}, [](const Robot& robot) { return robot.index; }); for (const Robot& robot : stack) ans.push_back(robot.health); return ans; } };
2,812
Find the Safest Path in a Grid
2
maximumSafenessFactor
You are given a 0-indexed 2D matrix `grid` of size `n x n`, where `(r, c)` represents: * A cell containing a thief if `grid[r][c] = 1` * An empty cell if `grid[r][c] = 0` You are initially positioned at cell `(0, 0)`. In one move, you can move to any adjacent cell in the grid, including cells containing thieves. The safeness factor of a path on the grid is defined as the minimum manhattan distance from any cell in the path to any thief in the grid. Return the maximum safeness factor of all paths leading to cell `(n - 1, n - 1)`. An adjacent cell of cell `(r, c)`, is one of the cells `(r, c + 1)`, `(r, c - 1)`, `(r + 1, c)` and `(r - 1, c)` if it exists. The Manhattan distance between two cells `(a, b)` and `(x, y)` is equal to `|a - x| + |b - y|`, where `|val|` denotes the absolute value of val.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def maximumSafenessFactor(self, grid: List[List[int]]) -> int: self.dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) n = len(grid) distToThief = self._getDistToThief(grid) def hasValidPath(safeness: int) -> bool: if distToThief[0][0] < safeness: return False q = collections.deque([(0, 0)]) seen = {(0, 0)} while q: i, j = q.popleft() if distToThief[i][j] < safeness: continue if i == n - 1 and j == n - 1: return True for dx, dy in self.dirs: x = i + dx y = j + dy if x < 0 or x == n or y < 0 or y == n: continue if (x, y) in seen: continue q.append((x, y)) seen.add((x, y)) return False return bisect.bisect_left(range(n * 2), True, key=lambda m: not hasValidPath(m)) - 1 def _getDistToThief(self, grid: List[List[int]]) -> List[List[int]]: n = len(grid) distToThief = [[0] * n for _ in range(n)] q = collections.deque() seen = set() for i in range(n): for j in range(n): if grid[i][j] == 1: q.append((i, j)) seen.add((i, j)) dist = 0 while q: for _ in range(len(q)): i, j = q.popleft() distToThief[i][j] = dist for dx, dy in self.dirs: x = i + dx y = j + dy if x < 0 or x == n or y < 0 or y == n: continue if (x, y) in seen: continue q.append((x, y)) seen.add((x, y)) dist += 1 return distToThief
class Solution { public int maximumSafenessFactor(List<List<Integer>> grid) { int[][] distToThief = getDistToThief(grid); int l = 0; int r = grid.size() * 2; while (l < r) { final int m = (l + r) / 2; if (hasValidPath(distToThief, m)) l = m + 1; else r = m; } return l - 1; } private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; private boolean hasValidPath(int[][] distToThief, int safeness) { if (distToThief[0][0] < safeness) return false; final int n = distToThief.length; Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(0, 0))); boolean[][] seen = new boolean[n][n]; seen[0][0] = true; while (!q.isEmpty()) { final int i = q.peek().getKey(); final int j = q.poll().getValue(); if (distToThief[i][j] < safeness) continue; if (i == n - 1 && j == n - 1) return true; for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == n || y < 0 || y == n) continue; if (seen[x][y]) continue; q.offer(new Pair<>(x, y)); seen[x][y] = true; } } return false; } private int[][] getDistToThief(List<List<Integer>> grid) { final int n = grid.size(); int[][] distToThief = new int[n][n]; Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(); boolean[][] seen = new boolean[n][n]; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) if (grid.get(i).get(j) == 1) { q.offer(new Pair<>(i, j)); seen[i][j] = true; } for (int dist = 0; !q.isEmpty(); ++dist) { for (int sz = q.size(); sz > 0; --sz) { final int i = q.peek().getKey(); final int j = q.poll().getValue(); distToThief[i][j] = dist; for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == n || y < 0 || y == n) continue; if (seen[x][y]) continue; q.offer(new Pair<>(x, y)); seen[x][y] = true; } } } return distToThief; } }
class Solution { public: int maximumSafenessFactor(vector<vector<int>>& grid) { const vector<vector<int>> distToThief = getDistToThief(grid); int l = 0; int r = grid.size() * 2; while (l < r) { const int m = (l + r) / 2; if (hasValidPath(distToThief, m)) l = m + 1; else r = m; } return l - 1; } private: static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; bool hasValidPath(const vector<vector<int>>& distToThief, int safeness) { if (distToThief[0][0] < safeness) return false; const int n = distToThief.size(); queue<pair<int, int>> q{{{0, 0}}}; vector<vector<bool>> seen(n, vector<bool>(n)); seen[0][0] = true; while (!q.empty()) { const auto [i, j] = q.front(); q.pop(); if (distToThief[i][j] < safeness) continue; if (i == n - 1 && j == n - 1) return true; for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == n || y < 0 || y == n) continue; if (seen[x][y]) continue; q.emplace(x, y); seen[x][y] = true; } } return false; } vector<vector<int>> getDistToThief(const vector<vector<int>>& grid) { const int n = grid.size(); vector<vector<int>> distToThief(n, vector<int>(n)); queue<pair<int, int>> q; vector<vector<bool>> seen(n, vector<bool>(n)); for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 1) { q.emplace(i, j); seen[i][j] = true; } for (int dist = 0; !q.empty(); ++dist) { for (int sz = q.size(); sz > 0; --sz) { const auto [i, j] = q.front(); q.pop(); distToThief[i][j] = dist; for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == n || y < 0 || y == n) continue; if (seen[x][y]) continue; q.emplace(x, y); seen[x][y] = true; } } } return distToThief; } };
2,818
Apply Operations to Maximize Score
3
maximumScore
You are given an array `nums` of `n` positive integers and an integer `k`. Initially, you start with a score of `1`. You have to maximize your score by applying the following operation at most `k` times: * Choose any non-empty subarray `nums[l, ..., r]` that you haven't chosen previously. * Choose an element `x` of `nums[l, ..., r]` with the highest prime score. If multiple such elements exist, choose the one with the smallest index. * Multiply your score by `x`. Here, `nums[l, ..., r]` denotes the subarray of `nums` starting at index `l` and ending at the index `r`, both ends being inclusive. The prime score of an integer `x` is equal to the number of distinct prime factors of `x`. For example, the prime score of `300` is `3` since `300 = 2 * 2 * 3 * 5 * 5`. Return the maximum possible score after applying at most `k` operations. Since the answer may be large, return it modulo `109 + 7`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def maximumScore(self, nums: List[int], k: int) -> int: kMod = 1_000_000_007 n = len(nums) ans = 1 minPrimeFactors = self._sieveEratosthenes(max(nums) + 1) primeScores = [self._getPrimeScore(num, minPrimeFactors) for num in nums] left = [-1] * n right = [n] * n stack = [] for i in reversed(range(n)): while stack and primeScores[stack[-1]] <= primeScores[i]: left[stack.pop()] = i stack.append(i) stack = [] for i in range(n): while stack and primeScores[stack[-1]] < primeScores[i]: right[stack.pop()] = i stack.append(i) numAndIndexes = [(num, i) for i, num in enumerate(nums)] def modPow(x: int, n: int) -> int: if n == 0: return 1 if n & 1: return x * modPow(x, n - 1) % kMod return modPow(x * x % kMod, n // 2) for num, i in sorted(numAndIndexes, key=lambda x: (-x[0], x[1])): rangeCount = (i - left[i]) * (right[i] - i) actualCount = min(rangeCount, k) k -= actualCount ans *= modPow(num, actualCount) ans %= kMod return ans def _sieveEratosthenes(self, n: int) -> List[int]: minPrimeFactors = [i for i in range(n + 1)] for i in range(2, int(n**0.5) + 1): if minPrimeFactors[i] == i: for j in range(i * i, n, i): minPrimeFactors[j] = min(minPrimeFactors[j], i) return minPrimeFactors def _getPrimeScore(self, num: int, minPrimeFactors: List[int]) -> int: primeFactors = set() while num > 1: divisor = minPrimeFactors[num] primeFactors.add(divisor) while num % divisor == 0: num //= divisor return len(primeFactors)
class Solution { public int maximumScore(List<Integer> nums, int k) { final int n = nums.size(); final int mx = Collections.max(nums); final int[] minPrimeFactors = sieveEratosthenes(mx + 1); final int[] primeScores = getPrimeScores(nums, minPrimeFactors); int ans = 1; // left[i] := the next index on the left (if any) // s.t. primeScores[left[i]] >= primeScores[i] int[] left = new int[n]; Arrays.fill(left, -1); // right[i] := the next index on the right (if any) // s.t. primeScores[right[i]] > primeScores[i] int[] right = new int[n]; Arrays.fill(right, n); Deque<Integer> stack = new ArrayDeque<>(); // Find the next indices on the left where `primeScores` are greater or equal. for (int i = n - 1; i >= 0; --i) { while (!stack.isEmpty() && primeScores[stack.peek()] <= primeScores[i]) left[stack.pop()] = i; stack.push(i); } stack.clear(); // Find the next indices on the right where `primeScores` are greater. for (int i = 0; i < n; ++i) { while (!stack.isEmpty() && primeScores[stack.peek()] < primeScores[i]) right[stack.pop()] = i; stack.push(i); } Pair<Integer, Integer>[] numAndIndexes = new Pair[n]; for (int i = 0; i < n; ++i) numAndIndexes[i] = new Pair<>(nums.get(i), i); Arrays.sort(numAndIndexes, Comparator.comparing(Pair<Integer, Integer>::getKey, Comparator.reverseOrder()) .thenComparingInt(Pair<Integer, Integer>::getValue)); for (Pair<Integer, Integer> numAndIndex : numAndIndexes) { final int num = numAndIndex.getKey(); final int i = numAndIndex.getValue(); // nums[i] is the maximum value in the range [left[i] + 1, right[i] - 1] // So, there are (i - left[i]) * (right[i] - 1) ranges where nums[i] will // be chosen. final long rangeCount = (long) (i - left[i]) * (right[i] - i); final long actualCount = Math.min(rangeCount, (long) k); k -= actualCount; ans = (int) ((1L * ans * modPow(num, actualCount)) % MOD); } return ans; } private static final int MOD = 1_000_000_007; private long modPow(long x, long n) { if (n == 0) return 1; if (n % 2 == 1) return x * modPow(x, n - 1) % MOD; return modPow(x * x % MOD, n / 2); } // Gets the minimum prime factor of i, where 1 < i <= n. private int[] sieveEratosthenes(int n) { int[] minPrimeFactors = new int[n + 1]; for (int i = 2; i <= n; ++i) minPrimeFactors[i] = i; for (int i = 2; i * i < n; ++i) if (minPrimeFactors[i] == i) // `i` is prime. for (int j = i * i; j < n; j += i) minPrimeFactors[j] = Math.min(minPrimeFactors[j], i); return minPrimeFactors; } private int[] getPrimeScores(List<Integer> nums, int[] minPrimeFactors) { int[] primeScores = new int[nums.size()]; for (int i = 0; i < nums.size(); ++i) primeScores[i] = getPrimeScore(nums.get(i), minPrimeFactors); return primeScores; } private int getPrimeScore(int num, int[] minPrimeFactors) { Set<Integer> primeFactors = new HashSet<>(); while (num > 1) { final int divisor = minPrimeFactors[num]; primeFactors.add(divisor); while (num % divisor == 0) num /= divisor; } return primeFactors.size(); } }
class Solution { public: int maximumScore(vector<int>& nums, int k) { const int n = nums.size(); const int mx = ranges::max(nums); const vector<int> minPrimeFactors = sieveEratosthenes(mx + 1); const vector<int> primeScores = getPrimeScores(nums, minPrimeFactors); int ans = 1; // left[i] := the next index on the left (if any) s.t. // primeScores[left[i]] >= primeScores[i] vector<int> left(n, -1); // right[i] := the next index on the right (if any) s.t. // primeScores[right[i]] > primeScores[i] vector<int> right(n, n); stack<int> stack; // Find the next indices on the left where `primeScores` are greater or // equal. for (int i = n - 1; i >= 0; --i) { while (!stack.empty() && primeScores[stack.top()] <= primeScores[i]) left[stack.top()] = i, stack.pop(); stack.push(i); } stack = std::stack<int>(); // Find the next indices on the right where `primeScores` are greater. for (int i = 0; i < n; ++i) { while (!stack.empty() && primeScores[stack.top()] < primeScores[i]) right[stack.top()] = i, stack.pop(); stack.push(i); } vector<pair<int, int>> numAndIndexes; for (int i = 0; i < n; ++i) numAndIndexes.emplace_back(nums[i], i); ranges::sort(numAndIndexes, [&](const pair<int, int>& a, const pair<int, int>& b) { return a.first == b.first ? a.second < b.second : a.first > b.first; }); for (const auto& [num, i] : numAndIndexes) { // nums[i] is the maximum value in the range [left[i] + 1, right[i] - 1] // So, there are (i - left[i]) * (right[i] - 1) ranges where nums[i] will // be chosen. const long rangeCount = static_cast<long>(i - left[i]) * (right[i] - i); const long actualCount = min(rangeCount, static_cast<long>(k)); k -= actualCount; ans = static_cast<long>(ans) * modPow(num, actualCount) % kMod; } return ans; } private: static constexpr int kMod = 1'000'000'007; long modPow(long x, long n) { if (n == 0) return 1; if (n % 2 == 1) return x * modPow(x % kMod, (n - 1)) % kMod; return modPow(x * x % kMod, (n / 2)) % kMod; } // Gets the minimum prime factor of i, where 1 < i <= n. vector<int> sieveEratosthenes(int n) { vector<int> minPrimeFactors(n + 1); iota(minPrimeFactors.begin() + 2, minPrimeFactors.end(), 2); for (int i = 2; i * i < n; ++i) if (minPrimeFactors[i] == i) // `i` is prime. for (int j = i * i; j < n; j += i) minPrimeFactors[j] = min(minPrimeFactors[j], i); return minPrimeFactors; } vector<int> getPrimeScores(const vector<int>& nums, const vector<int>& minPrimeFactors) { vector<int> primeScores; for (const int num : nums) primeScores.push_back(getPrimeScore(num, minPrimeFactors)); return primeScores; } int getPrimeScore(int num, const vector<int>& minPrimeFactors) { unordered_set<int> primeFactors; while (num > 1) { const int divisor = minPrimeFactors[num]; primeFactors.insert(divisor); while (num % divisor == 0) num /= divisor; } return primeFactors.size(); } };
2,836
Maximize Value of Function in a Ball Passing Game
3
getMaxFunctionValue
You are given an integer array `receiver` of length `n` and an integer `k`. `n` players are playing a ball-passing game. You choose the starting player, `i`. The game proceeds as follows: player `i` passes the ball to player `receiver[i]`, who then passes it to `receiver[receiver[i]]`, and so on, for `k` passes in total. The game's score is the sum of the indices of the players who touched the ball, including repetitions, i.e. `i + receiver[i] + receiver[receiver[i]] + ... + receiver(k)[i]`. Return the maximum possible score. Notes: * `receiver` may contain duplicates. * `receiver[i]` may be equal to `i`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def getMaxFunctionValue(self, receiver: List[int], k: int) -> int: n = len(receiver) m = int(math.log2(k)) + 1 ans = 0 jump = [[0] * m for _ in range(n)] summ = [[0] * m for _ in range(n)] for i in range(n): jump[i][0] = receiver[i] summ[i][0] = receiver[i] for j in range(1, m): for i in range(n): midNode = jump[i][j - 1] jump[i][j] = jump[midNode][j - 1] summ[i][j] = summ[i][j - 1] + summ[midNode][j - 1] for i in range(n): currSum = i currPos = i for j in range(m): if (k >> j) & 1 == 1: currSum += summ[currPos][j] currPos = jump[currPos][j] ans = max(ans, currSum) return ans
class Solution { public long getMaxFunctionValue(List<Integer> receiver, long k) { final int n = receiver.size(); final int m = (int) (Math.log(k) / Math.log(2)) + 1; long ans = 0; // jump[i][j] := the the node you reach after jumping 2^j steps from i int[][] jump = new int[n][m]; // sum[i][j] := the sum of the first 2^j nodes you reach when jumping from i long[][] sum = new long[n][m]; for (int i = 0; i < n; ++i) { jump[i][0] = receiver.get(i); sum[i][0] = receiver.get(i); } // Calculate binary lifting. for (int j = 1; j < m; ++j) for (int i = 0; i < n; ++i) { final int midNode = jump[i][j - 1]; // the the node you reach after jumping 2^j steps from i // = the node you reach after jumping 2^(j - 1) steps from i // + the node you reach after jumping another 2^(j - 1) steps jump[i][j] = jump[midNode][j - 1]; // the sum of the first 2^j nodes you reach when jumping from i // = the sum of the first 2^(j - 1) nodes you reach when jumping from i // + the sum of another 2^(j - 1) nodes you reach sum[i][j] = sum[i][j - 1] + sum[midNode][j - 1]; } for (int i = 0; i < n; ++i) { long currSum = i; int currPos = i; for (int j = 0; j < m; ++j) if ((k >> j & 1) == 1) { currSum += sum[currPos][j]; currPos = jump[currPos][j]; } ans = Math.max(ans, currSum); } return ans; } }
class Solution { public: long long getMaxFunctionValue(vector<int>& receiver, long long k) { const int n = receiver.size(); const int m = log2(k) + 1; long ans = 0; // jump[i][j] := the the node you reach after jumping 2^j steps from i vector<vector<int>> jump(n, vector<int>(m)); // sum[i][j] := the sum of the first 2^j nodes you reach when jumping from i vector<vector<long>> sum(n, vector<long>(m)); for (int i = 0; i < n; ++i) { jump[i][0] = receiver[i]; sum[i][0] = receiver[i]; } // Calculate binary lifting. for (int j = 1; j < m; ++j) for (int i = 0; i < n; ++i) { const int midNode = jump[i][j - 1]; // the the node you reach after jumping 2^j steps from i // = the node you reach after jumping 2^(j - 1) steps from i // + the node you reach after jumping another 2^(j - 1) steps jump[i][j] = jump[midNode][j - 1]; // the sum of the first 2^j nodes you reach when jumping from i // = the sum of the first 2^(j - 1) nodes you reach when jumping from i // + the sum of another 2^(j - 1) nodes you reach sum[i][j] = sum[i][j - 1] + sum[midNode][j - 1]; } for (int i = 0; i < n; ++i) { long currSum = i; int currPos = i; for (int j = 0; j < m; ++j) if (k >> j & 1) { currSum += sum[currPos][j]; currPos = jump[currPos][j]; } ans = max(ans, currSum); } return ans; } };
2,844
Minimum Operations to Make a Special Number
2
minimumOperations
You are given a 0-indexed string `num` representing a non-negative integer. In one operation, you can pick any digit of `num` and delete it. Note that if you delete all the digits of `num`, `num` becomes `0`. Return the minimum number of operations required to make `num` special. An integer `x` is considered special if it is divisible by `25`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minimumOperations(self, num: str) -> int: n = len(num) seenFive = False seenZero = False for i in range(n - 1, -1, -1): if seenZero and num[i] == '0': return n - i - 2 if seenZero and num[i] == '5': return n - i - 2 if seenFive and num[i] == '2': return n - i - 2 if seenFive and num[i] == '7': return n - i - 2 seenZero = seenZero or num[i] == '0' seenFive = seenFive or num[i] == '5' if seenZero: return n - 1 else: return n
class Solution { public int minimumOperations(String num) { final int n = num.length(); boolean seenFive = false; boolean seenZero = false; for (int i = n - 1; i >= 0; --i) { if (seenZero && num.charAt(i) == '0') // '00' return n - i - 2; if (seenZero && num.charAt(i) == '5') // '50' return n - i - 2; if (seenFive && num.charAt(i) == '2') // '25' return n - i - 2; if (seenFive && num.charAt(i) == '7') // '75' return n - i - 2; seenZero = seenZero || num.charAt(i) == '0'; seenFive = seenFive || num.charAt(i) == '5'; } return seenZero ? n - 1 : n; } }
class Solution { public: int minimumOperations(string num) { const int n = num.length(); bool seenFive = false; bool seenZero = false; for (int i = n - 1; i >= 0; --i) { if (seenZero && num[i] == '0') // '00' return n - i - 2; if (seenZero && num[i] == '5') // '50' return n - i - 2; if (seenFive && num[i] == '2') // '25' return n - i - 2; if (seenFive && num[i] == '7') // '75' return n - i - 2; seenZero = seenZero || num[i] == '0'; seenFive = seenFive || num[i] == '5'; } return seenZero ? n - 1 : n; } };
2,846
Minimum Edge Weight Equilibrium Queries in a Tree
3
minOperationsQueries
There is an undirected tree with `n` nodes labeled from `0` to `n - 1`. You are given the integer `n` and a 2D integer array `edges` of length `n - 1`, where `edges[i] = [ui, vi, wi]` indicates that there is an edge between nodes `ui` and `vi` with weight `wi` in the tree. You are also given a 2D integer array `queries` of length `m`, where `queries[i] = [ai, bi]`. For each query, find the minimum number of operations required to make the weight of every edge on the path from `ai` to `bi` equal. In one operation, you can choose any edge of the tree and change its weight to any value. Note that: * Queries are independent of each other, meaning that the tree returns to its initial state on each new query. * The path from `ai` to `bi` is a sequence of distinct nodes starting with node `ai` and ending with node `bi` such that every two adjacent nodes in the sequence share an edge in the tree. Return an array `answer` of length `m` where `answer[i]` is the answer to the `ith` query.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minOperationsQueries(self, n: int, edges: List[List[int]], queries: List[List[int]]) -> List[int]: kMax = 26 m = int(math.log2(n)) + 1 ans = [] graph = [[] for _ in range(n)] jump = [[0] * m for _ in range(n)] count = [[] for _ in range(n)] depth = [0] * n for u, v, w in edges: graph[u].append((v, w)) graph[v].append((u, w)) def dfs(u: int, prev: int, d: int): if prev != -1: jump[u][0] = prev depth[u] = d for v, w in graph[u]: if v == prev: continue count[v] = count[u][:] count[v][w] += 1 dfs(v, u, d + 1) count[0] = [0] * (kMax + 1) dfs(0, -1, 0) for j in range(1, m): for i in range(n): jump[i][j] = jump[jump[i][j - 1]][j - 1] def getLCA(u: int, v: int) -> int: if depth[u] > depth[v]: return getLCA(v, u) for j in range(m): if depth[v] - depth[u] >> j & 1: v = jump[v][j] if u == v: return u for j in range(m - 1, -1, -1): if jump[u][j] != jump[v][j]: u = jump[u][j] v = jump[v][j] return jump[v][0] for u, v in queries: lca = getLCA(u, v) numEdges = depth[u] + depth[v] - 2 * depth[lca] maxFreq = max(count[u][j] + count[v][j] - 2 * count[lca][j] for j in range(1, kMax + 1)) ans.append(numEdges - maxFreq) return ans
class Solution { public int[] minOperationsQueries(int n, int[][] edges, int[][] queries) { final int MAX = 26; final int m = (int) Math.ceil(Math.log(n) / Math.log(2)); int[] ans = new int[queries.length]; List<Pair<Integer, Integer>>[] graph = new List[n]; // jump[i][j] := the 2^j-th ancestor of i int[][] jump = new int[n][m]; // depth[i] := the depth of i int[] depth = new int[n]; // count[i][j] := the count of j from root to i, where 1 <= j <= 26 int[][] count = new int[n][MAX + 1]; Arrays.setAll(graph, i -> new ArrayList<>()); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; final int w = edge[2]; graph[u].add(new Pair<>(v, w)); graph[v].add(new Pair<>(u, w)); } count[0] = new int[MAX + 1]; dfs(graph, 0, /*prev=*/-1, jump, depth, count); for (int j = 1; j < m; ++j) for (int i = 0; i < n; ++i) jump[i][j] = jump[jump[i][j - 1]][j - 1]; for (int i = 0; i < queries.length; ++i) { final int u = queries[i][0]; final int v = queries[i][1]; final int lca = getLCA(u, v, jump, depth); // the number of edges between (u, v). final int numEdges = depth[u] + depth[v] - 2 * depth[lca]; // the maximum frequency of edges between (u, v) int maxFreq = 0; for (int j = 1; j <= MAX; ++j) maxFreq = Math.max(maxFreq, count[u][j] + count[v][j] - 2 * count[lca][j]); ans[i] = numEdges - maxFreq; } return ans; } private void dfs(List<Pair<Integer, Integer>>[] graph, int u, int prev, int[][] jump, int[] depth, int[][] count) { for (Pair<Integer, Integer> pair : graph[u]) { final int v = pair.getKey(); final int w = pair.getValue(); if (v == prev) continue; jump[v][0] = u; depth[v] = depth[u] + 1; count[v] = count[u].clone(); ++count[v][w]; dfs(graph, v, u, jump, depth, count); } } // Returns the lca(u, v) by binary jump. private int getLCA(int u, int v, int[][] jump, int[] depth) { // v is always deeper than u. if (depth[u] > depth[v]) return getLCA(v, u, jump, depth); // Jump v to the same height of u. for (int j = 0; j < jump[0].length; ++j) if ((depth[v] - depth[u] >> j & 1) == 1) v = jump[v][j]; if (u == v) return u; // Jump u and v to the node right below the lca. for (int j = jump[0].length - 1; j >= 0; --j) if (jump[u][j] != jump[v][j]) { u = jump[u][j]; v = jump[v][j]; } return jump[v][0]; } }
class Solution { public: vector<int> minOperationsQueries(int n, vector<vector<int>>& edges, vector<vector<int>>& queries) { constexpr int kMax = 26; const int m = ceil(log2(n)); vector<int> ans; vector<vector<pair<int, int>>> graph(n); // jump[i][j] := the 2^j-th ancestor of i vector<vector<int>> jump(n, vector<int>(m)); // depth[i] := the depth of i vector<int> depth(n); // count[i][j] := the count of j from root to i, where 1 <= j <= 26 vector<vector<int>> count(n); for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; const int w = edge[2]; graph[u].emplace_back(v, w); graph[v].emplace_back(u, w); } count[0] = vector<int>(kMax + 1); dfs(graph, 0, /*prev=*/-1, jump, depth, count); for (int j = 1; j < m; ++j) for (int i = 0; i < n; ++i) jump[i][j] = jump[jump[i][j - 1]][j - 1]; for (const vector<int>& query : queries) { const int u = query[0]; const int v = query[1]; const int lca = getLCA(u, v, jump, depth); // the number of edges between (u, v). const int numEdges = depth[u] + depth[v] - 2 * depth[lca]; // the maximum frequency of edges between (u, v) int maxFreq = 0; for (int j = 1; j <= kMax; ++j) maxFreq = max(maxFreq, count[u][j] + count[v][j] - 2 * count[lca][j]); ans.push_back(numEdges - maxFreq); } return ans; } private: void dfs(const vector<vector<pair<int, int>>>& graph, int u, int prev, vector<vector<int>>& jump, vector<int>& depth, vector<vector<int>>& count) { for (const auto& [v, w] : graph[u]) { if (v == prev) continue; jump[v][0] = u; depth[v] = depth[u] + 1; count[v] = count[u]; ++count[v][w]; dfs(graph, v, u, jump, depth, count); } } // Returns the lca(u, v) by binary jump. int getLCA(int u, int v, const vector<vector<int>>& jump, const vector<int>& depth) { // v is always deeper than u. if (depth[u] > depth[v]) return getLCA(v, u, jump, depth); // Jump v to the same height of u. for (int j = 0; j < jump[0].size(); ++j) if (depth[v] - depth[u] >> j & 1) v = jump[v][j]; if (u == v) return u; // Jump u and v to the node right below the lca. for (int j = jump[0].size() - 1; j >= 0; --j) if (jump[u][j] != jump[v][j]) { u = jump[u][j]; v = jump[v][j]; } return jump[v][0]; } };
2,850
Minimum Moves to Spread Stones Over Grid
2
minimumMoves
You are given a 0-indexed 2D integer matrix `grid` of size `3 * 3`, representing the number of stones in each cell. The grid contains exactly `9` stones, and there can be multiple stones in a single cell. In one move, you can move a single stone from its current cell to any other cell if the two cells share a side. Return the minimum number of moves required to place one stone in each cell.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minimumMoves(self, grid: List[List[int]]) -> int: if sum(row.count(0) for row in grid) == 0: return 0 ans = math.inf for i in range(3): for j in range(3): if grid[i][j] == 0: for x in range(3): for y in range(3): if grid[x][y] > 1: grid[x][y] -= 1 grid[i][j] += 1 ans = min(ans, abs(x - i) + abs(y - j) + self.minimumMoves(grid)) grid[x][y] += 1 grid[i][j] -= 1 return ans
class Solution { public int minimumMoves(int[][] grid) { int zeroCount = 0; for (int[] row : grid) for (int cell : row) if (cell == 0) ++zeroCount; if (zeroCount == 0) return 0; int ans = Integer.MAX_VALUE; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) if (grid[i][j] == 0) for (int x = 0; x < 3; ++x) for (int y = 0; y < 3; ++y) if (grid[x][y] > 1) { --grid[x][y]; ++grid[i][j]; ans = Math.min(ans, Math.abs(x - i) + Math.abs(y - j) + minimumMoves(grid)); ++grid[x][y]; --grid[i][j]; } return ans; } }
class Solution { public: int minimumMoves(vector<vector<int>>& grid) { const int zeroCount = accumulate(grid.begin(), grid.end(), 0, [](int acc, const vector<int>& row) { return acc + ranges::count(row, 0); }); if (zeroCount == 0) return 0; int ans = INT_MAX; for (int i = 0; i < 3; ++i) for (int j = 0; j < 3; ++j) if (grid[i][j] == 0) for (int x = 0; x < 3; ++x) for (int y = 0; y < 3; ++y) // Move a stone at (x, y) to (i, j). if (grid[x][y] > 1) { --grid[x][y]; ++grid[i][j]; ans = min(ans, abs(x - i) + abs(y - j) + minimumMoves(grid)); ++grid[x][y]; --grid[i][j]; } return ans; } };
2,851
String Transformation
3
numberOfWays
You are given two strings `s` and `t` of equal length `n`. You can perform the following operation on the string `s`: * Remove a suffix of `s` of length `l` where `0 < l < n` and append it at the start of `s`. For example, let `s = 'abcd'` then in one operation you can remove the suffix `'cd'` and append it in front of `s` making `s = 'cdab'`. You are also given an integer `k`. Return the number of ways in which `s` can be transformed into `t` in exactly `k` operations. Since the answer can be large, return it modulo `109 + 7`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def numberOfWays(self, s: str, t: str, k: int) -> int: kMod = 1_000_000_007 n = len(s) negOnePowK = 1 if k % 2 == 0 else -1 # (-1)^k z = self._zFunction(s + t + t) indices = [i - n for i in range(n, n + n) if z[i] >= n] dp = [0] * 2 dp[1] = (pow(n - 1, k, kMod) - negOnePowK) * pow(n, kMod - 2, kMod) dp[0] = dp[1] + negOnePowK res = 0 for index in indices: if index == 0: res += dp[0] else: res += dp[1] return res % kMod def _zFunction(self, s: str) -> List[int]: n = len(s) z = [0] * n l = 0 r = 0 for i in range(1, n): if i < r: z[i] = min(r - i, z[i - l]) while i + z[i] < n and s[z[i]] == s[i + z[i]]: z[i] += 1 if i + z[i] > r: l = i r = i + z[i] return z
class Solution { // This dynamic programming table dp[k][i] represents the number of ways to // rearrange the String s after k steps such that it starts with s[i]. // A String can be rotated from 1 to n - 1 times. The transition rule is // dp[k][i] = sum(dp[k - 1][j]) for all j != i. For example, when n = 4 and // k = 3, the table looks like this: // // ----------------------------------------------------------- // | | i = 0 | i = 1 | i = 2 | i = 3 | sum = (n - 1)^k | // ----------------------------------------------------------- // | k = 0 | 1 | 0 | 0 | 0 | 1 | // | k = 1 | 0 | 1 | 1 | 1 | 3 | // | k = 2 | 3 | 2 | 2 | 2 | 9 | // | k = 3 | 6 | 7 | 7 | 7 | 27 | // ----------------------------------------------------------- // // By observation, we have // * dp[k][!0] = ((n - 1)^k - (-1)^k) / n // * dp[k][0] = dp[k][!0] + (-1)^k public int numberOfWays(String s, String t, long k) { final int n = s.length(); final int negOnePowK = (k % 2 == 0 ? 1 : -1); // (-1)^k final int[] z = zFunction(s + t + t); final List<Integer> indices = getIndices(z, n); int[] dp = new int[2]; // dp[0] := dp[k][0]; dp[1] := dp[k][!0] dp[1] = (int) ((modPow(n - 1, k) - negOnePowK + MOD) % MOD * modPow(n, MOD - 2) % MOD); dp[0] = (int) ((dp[1] + negOnePowK + MOD) % MOD); int ans = 0; for (final int index : getIndices(z, n)) { ans += dp[index == 0 ? 0 : 1]; ans %= MOD; } return ans; } private static final int MOD = 1_000_000_007; private long modPow(long x, long n) { if (n == 0) return 1; if (n % 2 == 1) return x * modPow(x, n - 1) % MOD; return modPow(x * x % MOD, n / 2); } // Returns the z array, where z[i] is the length of the longest prefix of // s[i..n) which is also a prefix of s. // // https://cp-algorithms.com/string/z-function.html#implementation private int[] zFunction(final String s) { final int n = s.length(); int[] z = new int[n]; int l = 0; int r = 0; for (int i = 1; i < n; ++i) { if (i < r) z[i] = Math.min(r - i, z[i - l]); while (i + z[i] < n && s.charAt(z[i]) == s.charAt(i + z[i])) ++z[i]; if (i + z[i] > r) { l = i; r = i + z[i]; } } return z; } // Returns the indices in `s` s.t. for each `i` in the returned indices, // `s[i..n) + s[0..i) = t`. private List<Integer> getIndices(int[] z, int n) { List<Integer> indices = new ArrayList<>(); for (int i = n; i < n + n; ++i) if (z[i] >= n) indices.add(i - n); return indices; } }
class Solution { public: // This dynamic programming table dp[k][i] represents the number of ways to // rearrange the string s after k steps such that it starts with s[i]. // A string can be rotated from 1 to n - 1 times. The transition rule is // dp[k][i] = sum(dp[k - 1][j]) for all j != i. For example, when n = 4 and // k = 3, the table looks like this: // // ----------------------------------------------------------- // | | i = 0 | i = 1 | i = 2 | i = 3 | sum = (n - 1)^k | // ----------------------------------------------------------- // | k = 0 | 1 | 0 | 0 | 0 | 1 | // | k = 1 | 0 | 1 | 1 | 1 | 3 | // | k = 2 | 3 | 2 | 2 | 2 | 9 | // | k = 3 | 6 | 7 | 7 | 7 | 27 | // ----------------------------------------------------------- // // By observation, we have // * dp[k][!0] = ((n - 1)^k - (-1)^k) / n // * dp[k][0] = dp[k][!0] + (-1)^k int numberOfWays(string s, string t, long long k) { const int n = s.length(); const int negOnePowK = (k % 2 == 0 ? 1 : -1); // (-1)^k const vector<int> z = zFunction(s + t + t); const vector<int> indices = getIndices(z, n); vector<int> dp(2); // dp[0] := dp[k][0]; dp[1] := dp[k][!0] dp[1] = (modPow(n - 1, k) - negOnePowK + kMod) % kMod * modPow(n, kMod - 2) % kMod; dp[0] = (dp[1] + negOnePowK + kMod) % kMod; return accumulate(indices.begin(), indices.end(), 0L, [&](long acc, int index) { return (acc + dp[index == 0 ? 0 : 1]) % kMod; }); } private: static constexpr int kMod = 1'000'000'007; long modPow(long x, long n) { if (n == 0) return 1; if (n % 2 == 1) return x * modPow(x, n - 1) % kMod; return modPow(x * x % kMod, n / 2); } // Returns the z array, where z[i] is the length of the longest prefix of // s[i..n) which is also a prefix of s. // // https://cp-algorithms.com/string/z-function.html#implementation vector<int> zFunction(const string& s) { const int n = s.length(); vector<int> z(n); int l = 0; int r = 0; for (int i = 1; i < n; ++i) { if (i < r) z[i] = min(r - i, z[i - l]); while (i + z[i] < n && s[z[i]] == s[i + z[i]]) ++z[i]; if (i + z[i] > r) { l = i; r = i + z[i]; } } return z; } // Returns the indices in `s` s.t. for each `i` in the returned indices, // `s[i..n) + s[0..i) = t`. vector<int> getIndices(const vector<int>& z, int n) { vector<int> indices; for (int i = n; i < n + n; ++i) if (z[i] >= n) indices.push_back(i - n); return indices; } };
2,876
Count Visited Nodes in a Directed Graph
3
countVisitedNodes
There is a directed graph consisting of `n` nodes numbered from `0` to `n - 1` and `n` directed edges. You are given a 0-indexed array `edges` where `edges[i]` indicates that there is an edge from node `i` to node `edges[i]`. Consider the following process on the graph: * You start from a node `x` and keep visiting other nodes through edges until you reach a node that you have already visited before on this same process. Return an array `answer` where `answer[i]` is the number of different nodes that you will visit if you perform the process starting from node `i`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def countVisitedNodes(self, edges: List[int]) -> List[int]: n = len(edges) ans = [0] * n inDegrees = [0] * n seen = [False] * n stack = [] for v in edges: inDegrees[v] += 1 q = collections.deque([i for i, d in enumerate(inDegrees) if d == 0]) while q: u = q.popleft() inDegrees[edges[u]] -= 1 if inDegrees[edges[u]] == 0: q.append(edges[u]) stack.append(u) seen[u] = True for i in range(n): if not seen[i]: self._fillCycle(edges, i, seen, ans) while stack: u = stack.pop() ans[u] = ans[edges[u]] + 1 return ans def _fillCycle(self, edges: List[int], start: int, seen: List[bool], ans: List[int]) -> None: cycleLength = 0 u = start while not seen[u]: cycleLength += 1 seen[u] = True u = edges[u] ans[start] = cycleLength u = edges[start] while u != start: ans[u] = cycleLength u = edges[u]
class Solution { public int[] countVisitedNodes(List<Integer> edges) { final int n = edges.size(); int[] ans = new int[n]; int[] inDegrees = new int[n]; boolean[] seen = new boolean[n]; Queue<Integer> q = new ArrayDeque<>(); Stack<Integer> stack = new Stack<>(); for (int v : edges) ++inDegrees[v]; // Perform topological sorting. for (int i = 0; i < n; ++i) if (inDegrees[i] == 0) q.add(i); // Push non-cyclic nodes to stack. while (!q.isEmpty()) { final int u = q.poll(); if (--inDegrees[edges.get(u)] == 0) q.add(edges.get(u)); stack.push(u); seen[u] = true; } // Fill the length of cyclic nodes. for (int i = 0; i < n; ++i) if (!seen[i]) fillCycle(edges, i, seen, ans); // Fill the length of non-cyclic nodes. while (!stack.isEmpty()) { final int u = stack.pop(); ans[u] = ans[edges.get(u)] + 1; } return ans; } private void fillCycle(List<Integer> edges, int start, boolean[] seen, int[] ans) { int cycleLength = 0; for (int u = start; !seen[u]; u = edges.get(u)) { ++cycleLength; seen[u] = true; } ans[start] = cycleLength; for (int u = edges.get(start); u != start; u = edges.get(u)) ans[u] = cycleLength; } }
class Solution { public: vector<int> countVisitedNodes(vector<int>& edges) { const int n = edges.size(); vector<int> ans(n); vector<int> inDegrees(n); vector<bool> seen(n); queue<int> q; stack<int> stack; for (const int v : edges) ++inDegrees[v]; // Perform topological sorting. for (int i = 0; i < n; ++i) if (inDegrees[i] == 0) q.push(i); // Push non-cyclic nodes to stack. while (!q.empty()) { const int u = q.front(); q.pop(); if (--inDegrees[edges[u]] == 0) q.push(edges[u]); stack.push(u); seen[u] = true; } // Fill the length of cyclic nodes. for (int i = 0; i < n; ++i) if (!seen[i]) fillCycle(edges, i, seen, ans); // Fill the length of non-cyclic nodes. while (!stack.empty()) { const int u = stack.top(); stack.pop(); ans[u] = ans[edges[u]] + 1; } return ans; } private: void fillCycle(const vector<int>& edges, int start, vector<bool>& seen, vector<int>& ans) { int cycleLength = 0; for (int u = start; !seen[u]; u = edges[u]) { ++cycleLength; seen[u] = true; } ans[start] = cycleLength; for (int u = edges[start]; u != start; u = edges[u]) ans[u] = cycleLength; } };
2,901
Longest Unequal Adjacent Groups Subsequence II
2
getWordsInLongestSubsequence
You are given a string array `words`, and an array `groups`, both arrays having length `n`. The hamming distance between two strings of equal length is the number of positions at which the corresponding characters are different. You need to select the longest subsequence from an array of indices `[0, 1, ..., n - 1]`, such that for the subsequence denoted as `[i0, i1, ..., ik-1]` having length `k`, the following holds: * For adjacent indices in the subsequence, their corresponding groups are unequal, i.e., `groups[ij] != groups[ij+1]`, for each `j` where `0 < j + 1 < k`. * `words[ij]` and `words[ij+1]` are equal in length, and the hamming distance between them is `1`, where `0 < j + 1 < k`, for all indices in the subsequence. Return a string array containing the words corresponding to the indices (in order) in the selected subsequence. If there are multiple answers, return any of them. Note: strings in `words` may be unequal in length.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def getWordsInLongestSubsequence(self, words: List[str], groups: List[int]) -> List[str]: ans = [] n=len(words) dp = [1] * n prev = [-1] * n for i in range(1, n): for j in range(i): if groups[i] == groups[j]: continue if len(words[i]) != len(words[j]): continue if sum(a != b for a, b in zip(words[i], words[j])) != 1: continue if dp[i] < dp[j] + 1: dp[i] = dp[j] + 1 prev[i] = j index = dp.index(max(dp)) while index != -1: ans.append(words[index]) index = prev[index] return ans[::-1]
class Solution { public List<String> getWordsInLongestSubsequence(int n, String[] words, int[] groups) { List<String> ans = new ArrayList<>(); // dp[i] := the length of the longest subsequence ending in `words[i]` int[] dp = new int[n]; Arrays.fill(dp, 1); // prev[i] := the best index of words[i] int[] prev = new int[n]; Arrays.fill(prev, -1); for (int i = 1; i < n; ++i) for (int j = 0; j < i; ++j) { if (groups[i] == groups[j]) continue; if (words[i].length() != words[j].length()) continue; if (hammingDist(words[i], words[j]) != 1) continue; if (dp[i] < dp[j] + 1) { dp[i] = dp[j] + 1; prev[i] = j; } } // Find the last index of the subsequence. int index = getMaxIndex(dp); while (index != -1) { ans.add(words[index]); index = prev[index]; } Collections.reverse(ans); return ans; } private int hammingDist(final String s1, final String s2) { int dist = 0; for (int i = 0; i < s1.length(); ++i) if (s1.charAt(i) != s2.charAt(i)) ++dist; return dist; } private int getMaxIndex(int[] dp) { int maxIndex = 0; for (int i = 0; i < dp.length; ++i) if (dp[i] > dp[maxIndex]) maxIndex = i; return maxIndex; } }
class Solution { public: vector<string> getWordsInLongestSubsequence(int n, vector<string>& words, vector<int>& groups) { vector<string> ans; // dp[i] := the length of the longest subsequence ending in `words[i]` vector<int> dp(n, 1); // prev[i] := the best index of words[i] vector<int> prev(n, -1); for (int i = 1; i < n; ++i) for (int j = 0; j < i; ++j) { if (groups[i] == groups[j]) continue; if (words[i].length() != words[j].length()) continue; if (hammingDist(words[i], words[j]) != 1) continue; if (dp[i] < dp[j] + 1) { dp[i] = dp[j] + 1; prev[i] = j; } } // Find the last index of the subsequence. int index = ranges::max_element(dp) - dp.begin(); while (index != -1) { ans.push_back(words[index]); index = prev[index]; } ranges::reverse(ans); return ans; } private: int hammingDist(const string& s1, const string& s2) { int dist = 0; for (int i = 0; i < s1.length(); ++i) if (s1[i] != s2[i]) ++dist; return dist; } };
2,904
Shortest and Lexicographically Smallest Beautiful String
2
shortestBeautifulSubstring
You are given a binary string `s` and a positive integer `k`. A substring of `s` is beautiful if the number of `1`'s in it is exactly `k`. Let `len` be the length of the shortest beautiful substring. Return the lexicographically smallest beautiful substring of string `s` with length equal to `len`. If `s` doesn't contain a beautiful substring, return an empty string. A string `a` is lexicographically larger than a string `b` (of the same length) if in the first position where `a` and `b` differ, `a` has a character strictly larger than the corresponding character in `b`. * For example, `"abcd"` is lexicographically larger than `"abcc"` because the first position they differ is at the fourth character, and `d` is greater than `c`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def shortestBeautifulSubstring(self, s: str, k: int) -> str: bestLeft = -1 minLength = len(s) + 1 ones = 0 l = 0 for r, c in enumerate(s): if c == '1': ones += 1 while ones == k: if r - l + 1 < minLength: bestLeft = l minLength = r - l + 1 elif r - l + 1 == minLength and s[l:l + minLength] < s[bestLeft:bestLeft + minLength]: bestLeft = l if s[l] == '1': ones -= 1 l += 1 if bestLeft == -1: return "" else: return s[bestLeft:bestLeft + minLength]
class Solution { // Same as 76. Minimum Window Substring public String shortestBeautifulSubstring(String s, int k) { int bestLeft = -1; int minLength = s.length() + 1; int ones = 0; for (int l = 0, r = 0; r < s.length(); ++r) { if (s.charAt(r) == '1') ++ones; while (ones == k) { if (r - l + 1 < minLength) { bestLeft = l; minLength = r - l + 1; } else if (r - l + 1 == minLength && s.substring(l, l + minLength) .compareTo(s.substring(bestLeft, bestLeft + minLength)) < 0) { bestLeft = l; } if (s.charAt(l++) == '1') --ones; } } return bestLeft == -1 ? "" : s.substring(bestLeft, bestLeft + minLength); } }
class Solution { public: // Same as 76. Minimum Window Substring string shortestBeautifulSubstring(string s, int k) { int bestLeft = -1; int minLength = s.length() + 1; int ones = 0; for (int l = 0, r = 0; r < s.length(); ++r) { if (s[r] == '1') ++ones; while (ones == k) { if (r - l + 1 < minLength) { bestLeft = l; minLength = r - l + 1; } else if (r - l + 1 == minLength && s.compare(l, minLength, s, bestLeft, minLength) < 0) { bestLeft = l; } if (s[l++] == '1') --ones; } } return bestLeft == -1 ? "" : s.substr(bestLeft, minLength); } };
2,911
Minimum Changes to Make K Semi-palindromes
3
minimumChanges
Given a string `s` and an integer `k`, partition `s` into `k` substrings such that the letter changes needed to make each substring a semi-palindrome are minimized. Return the minimum number of letter changes required. A semi-palindrome is a special type of string that can be divided into palindromes based on a repeating pattern. To check if a string is a semi- palindrome:​ 1. Choose a positive divisor `d` of the string's length. `d` can range from `1` up to, but not including, the string's length. For a string of length `1`, it does not have a valid divisor as per this definition, since the only divisor is its length, which is not allowed. 2. For a given divisor `d`, divide the string into groups where each group contains characters from the string that follow a repeating pattern of length `d`. Specifically, the first group consists of characters at positions `1`, `1 + d`, `1 + 2d`, and so on; the second group includes characters at positions `2`, `2 + d`, `2 + 2d`, etc. 3. The string is considered a semi-palindrome if each of these groups forms a palindrome. Consider the string `"abcabc"`: * The length of `"abcabc"` is `6`. Valid divisors are `1`, `2`, and `3`. * For `d = 1`: The entire string `"abcabc"` forms one group. Not a palindrome. * For `d = 2`: * Group 1 (positions `1, 3, 5`): `"acb"` * Group 2 (positions `2, 4, 6`): `"bac"` * Neither group forms a palindrome. * For `d = 3`: * Group 1 (positions `1, 4`): `"aa"` * Group 2 (positions `2, 5`): `"bb"` * Group 3 (positions `3, 6`): `"cc"` * All groups form palindromes. Therefore, `"abcabc"` is a semi-palindrome.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minimumChanges(self, s: str, k: int) -> int: n = len(s) factors = self._getFactors(n) cost = self._getCost(s, n, factors) dp = [[n] * (k + 1) for _ in range(n + 1)] dp[n][0] = 0 for i in range(n - 1, -1, -1): for j in range(1, k + 1): for l in range(i + 1, n): dp[i][j] = min(dp[i][j], dp[l + 1][j - 1] + cost[i][l]) return dp[0][k] def _getFactors(self, n: int) -> List[List[int]]: factors = [[1] for _ in range(n + 1)] for d in range(2, n): for i in range(d * 2, n + 1, d): factors[i].append(d) return factors def _getCost(self, s: str, n: int, factors: List[List[int]]) -> List[List[int]]: cost = [[0] * n for _ in range(n)] for i in range(n): for j in range(i + 1, n): length = j - i + 1 minCost = length for d in factors[length]: minCost = min(minCost, self._getCostD(s, i, j, d)) cost[i][j] = minCost return cost def _getCostD(self, s: str, i: int, j: int, d: int) -> int: cost = 0 for offset in range(d): l = i + offset r = j - d + 1 + offset while l < r: if s[l] != s[r]: cost += 1 l += d r -= d return cost
class Solution { public int minimumChanges(String s, int k) { final int n = s.length(); // factors[i] := factors of i List<Integer>[] factors = getFactors(n); // cost[i][j] := changes to make s[i..j] a semi-palindrome int[][] cost = getCost(s, n, factors); // dp[i][j] := the minimum changes to split s[i:] into j valid parts int[][] dp = new int[n + 1][k + 1]; Arrays.stream(dp).forEach(A -> Arrays.fill(A, n)); dp[n][0] = 0; for (int i = n - 1; i >= 0; --i) for (int j = 1; j <= k; ++j) for (int l = i + 1; l < n; ++l) dp[i][j] = Math.min(dp[i][j], dp[l + 1][j - 1] + cost[i][l]); return dp[0][k]; } private List<Integer>[] getFactors(int n) { List<Integer>[] factors = new List[n + 1]; for (int i = 1; i <= n; ++i) factors[i] = new ArrayList<>(List.of(1)); for (int d = 2; d < n; ++d) for (int i = d * 2; i <= n; i += d) factors[i].add(d); return factors; } private int[][] getCost(final String s, int n, List<Integer>[] factors) { int[][] cost = new int[n][n]; for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) { final int length = j - i + 1; int minCost = length; for (final int d : factors[length]) minCost = Math.min(minCost, getCost(s, i, j, d)); cost[i][j] = minCost; } return cost; } // Returns the cost to make s[i..j] a semi-palindrome of `d`. private int getCost(final String s, int i, int j, int d) { int cost = 0; for (int offset = 0; offset < d; ++offset) { int l = i + offset; int r = j - d + 1 + offset; while (l < r) { if (s.charAt(l) != s.charAt(r)) ++cost; l += d; r -= d; } } return cost; } }
class Solution { public: int minimumChanges(string s, int k) { const int n = s.length(); // factors[i] := factors of i const vector<vector<int>> factors = getFactors(n); // cost[i][j] := changes to make s[i..j] a semi-palindrome const vector<vector<int>> cost = getCost(s, n, factors); // dp[i][j] := the minimum changes to split s[i:] into j valid parts vector<vector<int>> dp(n + 1, vector<int>(k + 1, n)); dp[n][0] = 0; for (int i = n - 1; i >= 0; --i) for (int j = 1; j <= k; ++j) for (int l = i + 1; l < n; ++l) dp[i][j] = min(dp[i][j], dp[l + 1][j - 1] + cost[i][l]); return dp[0][k]; } private: vector<vector<int>> getFactors(int n) { vector<vector<int>> factors(n + 1); for (int i = 1; i <= n; ++i) factors[i].push_back(1); for (int d = 2; d < n; ++d) for (int i = d * 2; i <= n; i += d) factors[i].push_back(d); return factors; } vector<vector<int>> getCost(const string& s, int n, const vector<vector<int>>& factors) { vector<vector<int>> cost(n, vector<int>(n)); for (int i = 0; i < n; ++i) for (int j = i + 1; j < n; ++j) { const int length = j - i + 1; int minCost = length; for (const int d : factors[length]) minCost = min(minCost, getCost(s, i, j, d)); cost[i][j] = minCost; } return cost; } // Returns the cost to make s[i..j] a semi-palindrome of `d`. int getCost(const string& s, int i, int j, int d) { int cost = 0; for (int offset = 0; offset < d; ++offset) { int l = i + offset; int r = j - d + 1 + offset; while (l < r) { if (s[l] != s[r]) ++cost; l += d; r -= d; } } return cost; } };
2,932
Maximum Strong Pair XOR I
1
maximumStrongPairXor
You are given a 0-indexed integer array `nums`. A pair of integers `x` and `y` is called a strong pair if it satisfies the condition: * `|x - y| <= min(x, y)` You need to select two integers from `nums` such that they form a strong pair and their bitwise `XOR` is the maximum among all strong pairs in the array. Return the maximum `XOR` value out of all possible strong pairs in the array `nums`. Note that you can pick the same integer twice to form a pair.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator, Optional class TrieNode: def __init__(self): self.children: List[Optional[TrieNode]] = [None] * 2 self.min = math.inf self.max = -math.inf class BitTrie: def __init__(self, maxBit: int): self.maxBit = maxBit self.root = TrieNode() def insert(self, num: int) -> None: node = self.root for i in range(self.maxBit, -1, -1): bit = num >> i & 1 if not node.children[bit]: node.children[bit] = TrieNode() node = node.children[bit] node.min = min(node.min, num) node.max = max(node.max, num) def getMaxXor(self, x: int) -> int: maxXor = 0 node = self.root for i in range(self.maxBit, -1, -1): bit = x >> i & 1 toggleBit = bit ^ 1 if node.children[toggleBit] and node.children[toggleBit].max > x and node.children[toggleBit].min <= 2 * x: maxXor = maxXor | 1 << i node = node.children[toggleBit] elif node.children[bit]: node = node.children[bit] else: return 0 return maxXor class Solution: def maximumStrongPairXor(self, nums: List[int]) -> int: maxNum = max(nums) maxBit = int(math.log2(maxNum)) bitTrie = BitTrie(maxBit) for num in nums: bitTrie.insert(num) return max(bitTrie.getMaxXor(num) for num in nums)
class TrieNode { public TrieNode[] children = new TrieNode[2]; public int mn = Integer.MAX_VALUE; public int mx = Integer.MIN_VALUE; } class BitTrie { public BitTrie(int maxBit) { this.maxBit = maxBit; } public void insert(int num) { TrieNode node = root; for (int i = maxBit; i >= 0; --i) { final int bit = (int) (num >> i & 1); if (node.children[bit] == null) node.children[bit] = new TrieNode(); node = node.children[bit]; node.mn = Math.min(node.mn, num); node.mx = Math.max(node.mx, num); } } // Returns max(x ^ y), where |x - y| <= min(x, y). // // If x <= y, |x - y| <= min(x, y) can be written as y - x <= x. // So, y <= 2 * x. public int getMaxXor(int x) { int maxXor = 0; TrieNode node = root; for (int i = maxBit; i >= 0; --i) { final int bit = (int) (x >> i & 1); final int toggleBit = bit ^ 1; // If `node.children[toggleBit].mx > x`, it means there's a number in the // node that satisfies the condition to ensure that x <= y among x and y. // If `node.children[toggleBit].mn <= 2 * x`, it means there's a number // in the node that satisfies the condition for a valid y. if (node.children[toggleBit] != null && node.children[toggleBit].mx > x && node.children[toggleBit].mn <= 2 * x) { maxXor = maxXor | 1 << i; node = node.children[toggleBit]; } else if (node.children[bit] != null) { node = node.children[bit]; } else { // There's nothing in the Bit Trie. return 0; } } return maxXor; } private int maxBit; private TrieNode root = new TrieNode(); } class Solution { // Similar to 421. Maximum XOR of Two Numbers in an Array public int maximumStrongPairXor(int[] nums) { final int maxNum = Arrays.stream(nums).max().getAsInt(); final int maxBit = (int) (Math.log(maxNum) / Math.log(2)); int ans = 0; BitTrie bitTrie = new BitTrie(maxBit); for (final int num : nums) bitTrie.insert(num); for (final int num : nums) ans = Math.max(ans, bitTrie.getMaxXor(num)); return ans; } }
struct TrieNode { vector<shared_ptr<TrieNode>> children; TrieNode() : children(2) {} int mn = INT_MAX; int mx = INT_MIN; }; class BitTrie { public: BitTrie(int maxBit) : maxBit(maxBit) {} void insert(int num) { shared_ptr<TrieNode> node = root; for (int i = maxBit; i >= 0; --i) { const int bit = num >> i & 1; if (node->children[bit] == nullptr) node->children[bit] = make_shared<TrieNode>(); node = node->children[bit]; node->mn = min(node->mn, num); node->mx = max(node->mx, num); } } // Returns max(x ^ y), where |x - y| <= min(x, y). // // If x <= y, |x - y| <= min(x, y) can be written as y - x <= x. // So, y <= 2 * x. int getMaxXor(int x) { int maxXor = 0; shared_ptr<TrieNode> node = root; for (int i = maxBit; i >= 0; --i) { const int bit = x >> i & 1; const int toggleBit = bit ^ 1; // If `node.children[toggleBit].mx > x`, it means there's a number in the // node that satisfies the condition to ensure that x <= y among x and y. // If `node.children[toggleBit].mn <= 2 * x`, it means there's a number // in the node that satisfies the condition for a valid y. if (node->children[toggleBit] != nullptr && node->children[toggleBit]->mx > x && node->children[toggleBit]->mn <= 2 * x) { maxXor = maxXor | 1 << i; node = node->children[toggleBit]; } else if (node->children[bit] != nullptr) { node = node->children[bit]; } else { // There's nothing in the Bit Trie. return 0; } } return maxXor; } private: const int maxBit; shared_ptr<TrieNode> root = make_shared<TrieNode>(); }; class Solution { public: // Similar to 421. Maximum XOR of Two Numbers in an Array int maximumStrongPairXor(vector<int>& nums) { const int maxNum = ranges::max(nums); const int maxBit = static_cast<int>(log2(maxNum)); int ans = 0; BitTrie bitTrie(maxBit); for (const int num : nums) bitTrie.insert(num); for (const int num : nums) ans = max(ans, bitTrie.getMaxXor(num)); return ans; } };
2,940
Find Building Where Alice and Bob Can Meet
3
leftmostBuildingQueries
You are given a 0-indexed array `heights` of positive integers, where `heights[i]` represents the height of the `ith` building. If a person is in building `i`, they can move to any other building `j` if and only if `i < j` and `heights[i] < heights[j]`. You are also given another array `queries` where `queries[i] = [ai, bi]`. On the `ith` query, Alice is in building `ai` while Bob is in building `bi`. Return an array `ans` where `ans[i]` is the index of the leftmost building where Alice and Bob can meet on the `ith` query. If Alice and Bob cannot move to a common building on query `i`, set `ans[i]` to `-1`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class IndexedQuery: def __init__(self, queryIndex: int, a: int, b: int): self.queryIndex = queryIndex self.a = a self.b = b def __iter__(self): yield self.queryIndex yield self.a yield self.b class Solution: def leftmostBuildingQueries(self, heights: List[int], queries: List[List[int]]) -> List[int]: ans = [-1] * len(queries) stack = [] heightsIndex = len(heights) - 1 for queryIndex, a, b in sorted([IndexedQuery(i, min(a, b), max(a, b)) for i, (a, b) in enumerate(queries)], key=lambda iq: -iq.b): if a == b or heights[a] < heights[b]: ans[queryIndex] = b else: while heightsIndex > b: while stack and heights[stack[-1]] <= heights[heightsIndex]: stack.pop() stack.append(heightsIndex) heightsIndex -= 1 j = self._lastGreater(stack, a, heights) if j != -1: ans[queryIndex] = stack[j] return ans def _lastGreater(self, A: List[int], target: int, heights: List[int]): l = -1 r = len(A) - 1 while l < r: m = (l + r + 1) // 2 if heights[A[m]] > heights[target]: l = m else: r = m - 1 return l
class Solution { // Similar to 2736. Maximum Sum Queries public int[] leftmostBuildingQueries(int[] heights, int[][] queries) { IndexedQuery[] indexedQueries = getIndexedQueries(queries); int[] ans = new int[queries.length]; Arrays.fill(ans, -1); // Store indices (heightsIndex) of heights with heights[heightsIndex] in // descending order. List<Integer> stack = new ArrayList<>(); // Iterate through queries and heights simultaneously. int heightsIndex = heights.length - 1; for (IndexedQuery indexedQuery : indexedQueries) { final int queryIndex = indexedQuery.queryIndex; final int a = indexedQuery.a; final int b = indexedQuery.b; if (a == b || heights[a] < heights[b]) { // 1. Alice and Bob are already in the same index (a == b) or // 2. Alice can jump from a -> b (heights[a] < heights[b]). ans[queryIndex] = b; } else { // Now, a < b and heights[a] >= heights[b]. // Gradually add heights with an index > b to the monotonic stack. while (heightsIndex > b) { // heights[heightsIndex] is a better candidate, given that // heightsIndex is smaller than the indices in the stack and // heights[heightsIndex] is larger or equal to the heights mapped in // the stack. while (!stack.isEmpty() && heights[stack.get(stack.size() - 1)] <= heights[heightsIndex]) stack.remove(stack.size() - 1); stack.add(heightsIndex--); } // Binary search to find the smallest index j such that j > b and // heights[j] > heights[a], thereby ensuring heights[t] > heights[b]. final int j = lastGreater(stack, a, heights); if (j != -1) ans[queryIndex] = stack.get(j); } } return ans; } private record IndexedQuery(int queryIndex, int a, int b){}; // Returns the last index i in A s.t. heights[A.get(i)] is > heights[target]. private int lastGreater(List<Integer> A, int target, int[] heights) { int l = -1; int r = A.size() - 1; while (l < r) { final int m = (l + r + 1) / 2; if (heights[A.get(m)] > heights[target]) l = m; else r = m - 1; } return l; } private IndexedQuery[] getIndexedQueries(int[][] queries) { IndexedQuery[] indexedQueries = new IndexedQuery[queries.length]; for (int i = 0; i < queries.length; ++i) { // Make sure that a <= b. final int a = Math.min(queries[i][0], queries[i][1]); final int b = Math.max(queries[i][0], queries[i][1]); indexedQueries[i] = new IndexedQuery(i, a, b); } Arrays.sort(indexedQueries, Comparator.comparing(IndexedQuery::b, Comparator.reverseOrder())); return indexedQueries; } }
struct IndexedQuery { int queryIndex; int a; // Alice's index int b; // Bob's index }; class Solution { public: // Similar to 2736. Maximum Sum Queries vector<int> leftmostBuildingQueries(vector<int>& heights, vector<vector<int>>& queries) { vector<int> ans(queries.size(), -1); // Store indices (heightsIndex) of heights with heights[heightsIndex] in // descending order. vector<int> stack; // Iterate through queries and heights simultaneously. int heightsIndex = heights.size() - 1; for (const auto& [queryIndex, a, b] : getIndexedQueries(queries)) { if (a == b || heights[a] < heights[b]) { // 1. Alice and Bob are already in the same index (a == b) or // 2. Alice can jump from a -> b (heights[a] < heights[b]). ans[queryIndex] = b; } else { // Now, a < b and heights[a] >= heights[b]. // Gradually add heights with an index > b to the monotonic stack. while (heightsIndex > b) { // heights[heightsIndex] is a better candidate, given that // heightsIndex is smaller than the indices in the stack and // heights[heightsIndex] is larger or equal to the heights mapped in // the stack. while (!stack.empty() && heights[stack.back()] <= heights[heightsIndex]) stack.pop_back(); stack.push_back(heightsIndex--); } // Binary search to find the smallest index j such that j > b and // heights[j] > heights[a], thereby ensuring heights[j] > heights[b]. if (const auto it = upper_bound( stack.rbegin(), stack.rend(), a, [&](int a, int b) { return heights[a] < heights[b]; }); it != stack.rend()) ans[queryIndex] = *it; } } return ans; } private: vector<IndexedQuery> getIndexedQueries(const vector<vector<int>>& queries) { vector<IndexedQuery> indexedQueries; for (int i = 0; i < queries.size(); ++i) { // Make sure that a <= b. const int a = min(queries[i][0], queries[i][1]); const int b = max(queries[i][0], queries[i][1]); indexedQueries.push_back({i, a, b}); } ranges::sort( indexedQueries, [](const IndexedQuery& a, const IndexedQuery& b) { return a.b > b.b; }); return indexedQueries; } };
2,948
Make Lexicographically Smallest Array by Swapping Elements
2
lexicographicallySmallestArray
You are given a 0-indexed array of positive integers `nums` and a positive integer `limit`. In one operation, you can choose any two indices `i` and `j` and swap `nums[i]` and `nums[j]` if `|nums[i] - nums[j]| <= limit`. Return the lexicographically smallest array that can be obtained by performing the operation any number of times. An array `a` is lexicographically smaller than an array `b` if in the first position where `a` and `b` differ, array `a` has an element that is less than the corresponding element in `b`. For example, the array `[2,10,3]` is lexicographically smaller than the array `[10,2,3]` because they differ at index `0` and `2 < 10`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def lexicographicallySmallestArray(self, nums: List[int], limit: int) -> List[int]: ans = [0] * len(nums) numAndIndexes = sorted([(num, i) for i, num in enumerate(nums)]) numAndIndexesGroups: List[List[Tuple[int, int]]] = [] for numAndIndex in numAndIndexes: if not numAndIndexesGroups or numAndIndex[0] - numAndIndexesGroups[-1][-1][0] > limit: numAndIndexesGroups.append([numAndIndex]) else: numAndIndexesGroups[-1].append(numAndIndex) for numAndIndexesGroup in numAndIndexesGroups: sortedNums = [num for num, _ in numAndIndexesGroup] sortedIndices = sorted([index for _, index in numAndIndexesGroup]) for num, index in zip(sortedNums, sortedIndices): ans[index] = num return ans
class Solution { public int[] lexicographicallySmallestArray(int[] nums, int limit) { int[] ans = new int[nums.length]; List<List<Pair<Integer, Integer>>> numAndIndexesGroups = new ArrayList<>(); for (Pair<Integer, Integer> numAndIndex : getNumAndIndexes(nums)) if (numAndIndexesGroups.isEmpty() || numAndIndex.getKey() - numAndIndexesGroups.get(numAndIndexesGroups.size() - 1) .get(numAndIndexesGroups.get(numAndIndexesGroups.size() - 1).size() - 1) .getKey() > limit) { // Start a new group. numAndIndexesGroups.add(new ArrayList<>(List.of(numAndIndex))); } else { // Append to the existing group. numAndIndexesGroups.get(numAndIndexesGroups.size() - 1).add(numAndIndex); } for (List<Pair<Integer, Integer>> numAndIndexesGroup : numAndIndexesGroups) { List<Integer> sortedNums = new ArrayList<>(); List<Integer> sortedIndices = new ArrayList<>(); for (Pair<Integer, Integer> pair : numAndIndexesGroup) { sortedNums.add(pair.getKey()); sortedIndices.add(pair.getValue()); } sortedIndices.sort(null); for (int i = 0; i < sortedNums.size(); ++i) { ans[sortedIndices.get(i)] = sortedNums.get(i); } } return ans; } private Pair<Integer, Integer>[] getNumAndIndexes(int[] nums) { Pair<Integer, Integer>[] numAndIndexes = new Pair[nums.length]; for (int i = 0; i < nums.length; ++i) numAndIndexes[i] = new Pair<>(nums[i], i); Arrays.sort(numAndIndexes, Comparator.comparingInt(Pair::getKey)); return numAndIndexes; } }
class Solution { public: vector<int> lexicographicallySmallestArray(vector<int>& nums, int limit) { vector<int> ans(nums.size()); // [[(num, index)]], where the difference between in each pair in each // `[(num, index)]` group <= `limit` vector<vector<pair<int, int>>> numAndIndexesGroups; for (const pair<int, int>& numAndIndex : getNumAndIndexes(nums)) if (numAndIndexesGroups.empty() || numAndIndex.first - numAndIndexesGroups.back().back().first > limit) { // Start a new group. numAndIndexesGroups.push_back({numAndIndex}); } else { // Append to the existing group. numAndIndexesGroups.back().push_back(numAndIndex); } for (const vector<pair<int, int>>& numAndIndexesGroup : numAndIndexesGroups) { vector<int> sortedNums; vector<int> sortedIndices; for (const auto& [num, index] : numAndIndexesGroup) { sortedNums.push_back(num); sortedIndices.push_back(index); } ranges::sort(sortedIndices); for (int i = 0; i < sortedNums.size(); ++i) ans[sortedIndices[i]] = sortedNums[i]; } return ans; } private: vector<pair<int, int>> getNumAndIndexes(const vector<int>& nums) { vector<pair<int, int>> numAndIndexes; for (int i = 0; i < nums.size(); ++i) numAndIndexes.emplace_back(nums[i], i); ranges::sort(numAndIndexes); return numAndIndexes; } };
2,953
Count Complete Substrings
3
countCompleteSubstrings
You are given a string `word` and an integer `k`. A substring `s` of `word` is complete if: * Each character in `s` occurs exactly `k` times. * The difference between two adjacent characters is at most `2`. That is, for any two adjacent characters `c1` and `c2` in `s`, the absolute difference in their positions in the alphabet is at most `2`. Return the number of complete substrings of `word`. A substring is a non-empty contiguous sequence of characters in a string.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def countCompleteSubstrings(self, word: str, k: int) -> int: uniqueLetters = len(set(word)) return sum(self._countCompleteStrings(word, k, windowSize) for windowSize in range(k, k * uniqueLetters + 1, k)) def _countCompleteStrings(self, word: str, k: int, windowSize: int) -> int: res = 0 countLetters = 0 count = collections.Counter() for i, c in enumerate(word): count[c] += 1 countLetters += 1 if i > 0 and abs(ord(c) - ord(word[i - 1])) > 2: count = collections.Counter() count[c] += 1 countLetters = 1 if countLetters == windowSize + 1: count[word[i - windowSize]] -= 1 countLetters -= 1 if countLetters == windowSize: res += all(freq == 0 or freq == k for freq in count.values()) return res
class Solution { public int countCompleteSubstrings(String word, int k) { final int uniqueLetters = word.chars().boxed().collect(Collectors.toSet()).size(); int ans = 0; for (int windowSize = k; windowSize <= k * uniqueLetters && windowSize <= word.length(); windowSize += k) { ans += countCompleteStrings(word, k, windowSize); } return ans; } // Returns the number of complete substrings of `windowSize` of `word`. private int countCompleteStrings(final String word, int k, int windowSize) { int res = 0; int countLetters = 0; // the number of letters in the running substring int[] count = new int[26]; for (int i = 0; i < word.length(); ++i) { ++count[word.charAt(i) - 'a']; ++countLetters; if (i > 0 && Math.abs(word.charAt(i) - word.charAt(i - 1)) > 2) { count = new int[26]; // Start a new substring starting at word[i]. ++count[word.charAt(i) - 'a']; countLetters = 1; } if (countLetters == windowSize + 1) { --count[word.charAt(i - windowSize) - 'a']; --countLetters; } if (countLetters == windowSize) res += Arrays.stream(count).allMatch(freq -> freq == 0 || freq == k) ? 1 : 0; } return res; } }
class Solution { public: int countCompleteSubstrings(string word, int k) { const int uniqueLetters = unordered_set<char>{word.begin(), word.end()}.size(); int ans = 0; for (int windowSize = k; windowSize <= k * uniqueLetters && windowSize <= word.length(); windowSize += k) ans += countCompleteStrings(word, k, windowSize); return ans; } private: // Returns the number of complete substrings of `windowSize` of `word`. int countCompleteStrings(const string& word, int k, int windowSize) { int res = 0; int countLetters = 0; // the number of letters in the running substring vector<int> count(26); for (int i = 0; i < word.length(); ++i) { ++count[word[i] - 'a']; ++countLetters; if (i > 0 && abs(word[i] - word[i - 1]) > 2) { count = vector<int>(26); // Start a new substring starting at word[i]. ++count[word[i] - 'a']; countLetters = 1; } if (countLetters == windowSize + 1) { --count[word[i - windowSize] - 'a']; --countLetters; } if (countLetters == windowSize) res += ranges::all_of(count, [k](int freq) { return freq == 0 || freq == k; }) ? 1 : 0; } return res; } };
2,959
Number of Possible Sets of Closing Branches
3
numberOfSets
There is a company with `n` branches across the country, some of which are connected by roads. Initially, all branches are reachable from each other by traveling some roads. The company has realized that they are spending an excessive amount of time traveling between their branches. As a result, they have decided to close down some of these branches (possibly none). However, they want to ensure that the remaining branches have a distance of at most `maxDistance` from each other. The distance between two branches is the minimum total traveled length needed to reach one branch from another. You are given integers `n`, `maxDistance`, and a 0-indexed 2D array `roads`, where `roads[i] = [ui, vi, wi]` represents the undirected road between branches `ui` and `vi` with length `wi`. Return the number of possible sets of closing branches, so that any branch has a distance of at most `maxDistance` from any other. Note that, after closing a branch, the company will no longer have access to any roads connected to it. Note that, multiple roads are allowed.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def numberOfSets(self, n: int, maxDistance: int, roads: List[List[int]]) -> int: return sum(self._floydWarshall(n, maxDistance, roads, mask) <= maxDistance for mask in range(1 << n)) def _floydWarshall(self, n: int, maxDistanceThreshold: int, roads: List[List[int]], mask: int) -> List[List[int]]: maxDistance = 0 dist = [[maxDistanceThreshold + 1] * n for _ in range(n)] for i in range(n): if mask >> i & 1: dist[i][i] = 0 for u, v, w in roads: if mask >> u & 1 and mask >> v & 1: dist[u][v] = min(dist[u][v], w) dist[v][u] = min(dist[v][u], w) for k in range(n): if mask >> k & 1: for i in range(n): if mask >> i & 1: for j in range(n): if mask >> j & 1: dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) for i in range(n): if mask >> i & 1: for j in range(i + 1, n): if mask >> j & 1: maxDistance = max(maxDistance, dist[i][j]) return maxDistance
class Solution { public int numberOfSets(int n, int maxDistance, int[][] roads) { final int maxMask = 1 << n; int ans = 0; for (int mask = 0; mask < maxMask; ++mask) if (floydWarshall(n, maxDistance, roads, mask) <= maxDistance) ++ans; return ans; } private int floydWarshall(int n, int maxDistanceThreshold, int[][] roads, int mask) { int maxDistance = 0; int[][] dist = new int[n][n]; Arrays.stream(dist).forEach(A -> Arrays.fill(A, maxDistanceThreshold + 1)); for (int i = 0; i < n; ++i) if ((mask >> i & 1) == 1) dist[i][i] = 0; for (int[] road : roads) { final int u = road[0]; final int v = road[1]; final int w = road[2]; if ((mask >> u & 1) == 1 && (mask >> v & 1) == 1) { dist[u][v] = Math.min(dist[u][v], w); dist[v][u] = Math.min(dist[v][u], w); } } for (int k = 0; k < n; ++k) if ((mask >> k & 1) == 1) for (int i = 0; i < n; ++i) if ((mask >> i & 1) == 1) for (int j = 0; j < n; ++j) if ((mask >> j & 1) == 1) dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); for (int i = 0; i < n; ++i) if ((mask >> i & 1) == 1) for (int j = i + 1; j < n; ++j) if ((mask >> j & 1) == 1) maxDistance = Math.max(maxDistance, dist[i][j]); return maxDistance; } }
class Solution { public: int numberOfSets(int n, int maxDistance, vector<vector<int>>& roads) { const int maxMask = 1 << n; int ans = 0; for (int mask = 0; mask < maxMask; ++mask) if (floydWarshall(n, maxDistance, roads, mask) <= maxDistance) ++ans; return ans; } private: // Returns the maximum distance between any two branches, where the mask // represents the selected branches. int floydWarshall(int n, int maxDistanceThreshold, vector<vector<int>>& roads, int mask) { int maxDistance = 0; vector<vector<int>> dist(n, vector<int>(n, maxDistanceThreshold + 1)); for (int i = 0; i < n; ++i) if (mask >> i & 1) dist[i][i] = 0; for (const vector<int>& road : roads) { const int u = road[0]; const int v = road[1]; const int w = road[2]; if (mask >> u & 1 && mask >> v & 1) { dist[u][v] = min(dist[u][v], w); dist[v][u] = min(dist[v][u], w); } } for (int k = 0; k < n; ++k) if (mask >> k & 1) for (int i = 0; i < n; ++i) if (mask >> i & 1) for (int j = 0; j < n; ++j) if (mask >> j & 1) dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); for (int i = 0; i < n; ++i) if (mask >> i & 1) for (int j = i + 1; j < n; ++j) if (mask >> j & 1) maxDistance = max(maxDistance, dist[i][j]); return maxDistance; } };
2,973
Find Number of Coins to Place in Tree Nodes
3
placedCoins
You are given an undirected tree with `n` nodes labeled from `0` to `n - 1`, and rooted at node `0`. You are given a 2D integer array `edges` of length `n - 1`, where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the tree. You are also given a 0-indexed integer array `cost` of length `n`, where `cost[i]` is the cost assigned to the `ith` node. You need to place some coins on every node of the tree. The number of coins to be placed at node `i` can be calculated as: * If size of the subtree of node `i` is less than `3`, place `1` coin. * Otherwise, place an amount of coins equal to the maximum product of cost values assigned to `3` distinct nodes in the subtree of node `i`. If this product is negative, place `0` coins. Return an array `coin` of size `n` such that `coin[i]` is the number of coins placed at node `i`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class ChildCost: def __init__(self, cost: int): self.numNodes = 1 self.maxPosCosts = [cost] if cost > 0 else [] self.minNegCosts = [cost] if cost < 0 else [] def update(self, childCost: 'ChildCost') -> None: self.numNodes += childCost.numNodes self.maxPosCosts.extend(childCost.maxPosCosts) self.minNegCosts.extend(childCost.minNegCosts) self.maxPosCosts.sort(reverse=True) self.minNegCosts.sort() self.maxPosCosts = self.maxPosCosts[:3] self.minNegCosts = self.minNegCosts[:2] def maxProduct(self) -> int: if self.numNodes < 3: return 1 if not self.maxPosCosts: return 0 res = 0 if len(self.maxPosCosts) == 3: res = self.maxPosCosts[0] * self.maxPosCosts[1] * self.maxPosCosts[2] if len(self.minNegCosts) == 2: res = max(res, self.minNegCosts[0] * self.minNegCosts[1] * self.maxPosCosts[0]) return res class Solution: def placedCoins(self, edges: List[List[int]], cost: List[int]) -> List[int]: n = len(cost) ans = [0] * n tree = [[] for _ in range(n)] for u, v in edges: tree[u].append(v) tree[v].append(u) def dfs(u: int, prev: int) -> None: res = ChildCost(cost[u]) for v in tree[u]: if v != prev: res.update(dfs(v, u)) ans[u] = res.maxProduct() return res dfs(0, -1) return ans
class ChildCost { public ChildCost(int cost) { if (cost > 0) maxPosCosts.add(cost); else minNegCosts.add(cost); } public void update(ChildCost childCost) { numNodes += childCost.numNodes; maxPosCosts.addAll(childCost.maxPosCosts); minNegCosts.addAll(childCost.minNegCosts); maxPosCosts.sort(Comparator.reverseOrder()); minNegCosts.sort(Comparator.naturalOrder()); if (maxPosCosts.size() > 3) maxPosCosts = maxPosCosts.subList(0, 3); if (minNegCosts.size() > 2) minNegCosts = minNegCosts.subList(0, 2); } public long maxProduct() { if (numNodes < 3) return 1; if (maxPosCosts.isEmpty()) return 0; long res = 0; if (maxPosCosts.size() == 3) res = (long) maxPosCosts.get(0) * maxPosCosts.get(1) * maxPosCosts.get(2); if (minNegCosts.size() == 2) res = Math.max(res, (long) minNegCosts.get(0) * minNegCosts.get(1) * maxPosCosts.get(0)); return res; } private int numNodes = 1; private List<Integer> maxPosCosts = new ArrayList<>(); private List<Integer> minNegCosts = new ArrayList<>(); } class Solution { public long[] placedCoins(int[][] edges, int[] cost) { final int n = cost.length; long[] ans = new long[n]; List<Integer>[] tree = new List[n]; for (int i = 0; i < n; i++) tree[i] = new ArrayList<>(); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; tree[u].add(v); tree[v].add(u); } dfs(tree, 0, /*prev=*/-1, cost, ans); return ans; } private ChildCost dfs(List<Integer>[] tree, int u, int prev, int[] cost, long[] ans) { ChildCost res = new ChildCost(cost[u]); for (final int v : tree[u]) if (v != prev) res.update(dfs(tree, v, u, cost, ans)); ans[u] = res.maxProduct(); return res; } }
class ChildCost { public: ChildCost(int cost) { numNodes = 1; if (cost > 0) maxPosCosts.push_back(cost); else minNegCosts.push_back(cost); } void update(ChildCost childCost) { numNodes += childCost.numNodes; ranges::copy(childCost.maxPosCosts, back_inserter(maxPosCosts)); ranges::copy(childCost.minNegCosts, back_inserter(minNegCosts)); ranges::sort(maxPosCosts, greater<int>()); ranges::sort(minNegCosts); maxPosCosts.resize(min(static_cast<int>(maxPosCosts.size()), 3)); minNegCosts.resize(min(static_cast<int>(minNegCosts.size()), 2)); } long maxProduct() { if (numNodes < 3) return 1; if (maxPosCosts.empty()) return 0; long res = 0; if (maxPosCosts.size() == 3) res = static_cast<long>(maxPosCosts[0]) * maxPosCosts[1] * maxPosCosts[2]; if (minNegCosts.size() == 2) res = max(res, static_cast<long>(minNegCosts[0]) * minNegCosts[1] * maxPosCosts[0]); return res; } private: int numNodes; vector<int> maxPosCosts; vector<int> minNegCosts; }; class Solution { public: vector<long long> placedCoins(vector<vector<int>>& edges, vector<int>& cost) { const int n = cost.size(); vector<long long> ans(n); vector<vector<int>> tree(n); for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; tree[u].push_back(v); tree[v].push_back(u); } dfs(tree, 0, /*prev=*/-1, cost, ans); return ans; } private: ChildCost dfs(const vector<vector<int>>& tree, int u, int prev, const vector<int>& cost, vector<long long>& ans) { ChildCost res(cost[u]); for (const int v : tree[u]) if (v != prev) res.update(dfs(tree, v, u, cost, ans)); ans[u] = res.maxProduct(); return res; } };
2,976
Minimum Cost to Convert String I
2
minimumCost
You are given two 0-indexed strings `source` and `target`, both of length `n` and consisting of lowercase English letters. You are also given two 0-indexed character arrays `original` and `changed`, and an integer array `cost`, where `cost[i]` represents the cost of changing the character `original[i]` to the character `changed[i]`. You start with the string `source`. In one operation, you can pick a character `x` from the string and change it to the character `y` at a cost of `z` if there exists any index `j` such that `cost[j] == z`, `original[j] == x`, and `changed[j] == y`. Return the minimum cost to convert the string `source` to the string `target` using any number of operations. If it is impossible to convert `source` to `target`, return `-1`. Note that there may exist indices `i`, `j` such that `original[j] == original[i]` and `changed[j] == changed[i]`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minimumCost(self, source: str, target: str, original: List[str], changed: List[str], cost: List[int]) -> int: ans = 0 dist = [[math.inf] * 26 for _ in range(26)] for a, b, c in zip(original, changed, cost): u = ord(a) - ord('a') v = ord(b) - ord('a') dist[u][v] = min(dist[u][v], c) for k in range(26): for i in range(26): if dist[i][k] < math.inf: for j in range(26): if dist[k][j] < math.inf: dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) for s, t in zip(source, target): if s == t: continue u = ord(s) - ord('a') v = ord(t) - ord('a') if dist[u][v] == math.inf: return -1 ans += dist[u][v] return ans
class Solution { public long minimumCost(String source, String target, char[] original, char[] changed, int[] cost) { long ans = 0; // dist[u][v] := the minimum distance to change ('a' + u) to ('a' + v) long[][] dist = new long[26][26]; Arrays.stream(dist).forEach(A -> Arrays.fill(A, Long.MAX_VALUE)); for (int i = 0; i < cost.length; ++i) { final int u = original[i] - 'a'; final int v = changed[i] - 'a'; dist[u][v] = Math.min(dist[u][v], cost[i]); } for (int k = 0; k < 26; ++k) for (int i = 0; i < 26; ++i) if (dist[i][k] < Long.MAX_VALUE) for (int j = 0; j < 26; ++j) if (dist[k][j] < Long.MAX_VALUE) dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); for (int i = 0; i < source.length(); ++i) { if (source.charAt(i) == target.charAt(i)) continue; final int u = source.charAt(i) - 'a'; final int v = target.charAt(i) - 'a'; if (dist[u][v] == Long.MAX_VALUE) return -1; ans += dist[u][v]; } return ans; } }
class Solution { public: long long minimumCost(string source, string target, vector<char>& original, vector<char>& changed, vector<int>& cost) { long ans = 0; // dist[u][v] := the minimum distance to change ('a' + u) to ('a' + v) vector<vector<long>> dist(26, vector<long>(26, LONG_MAX)); for (int i = 0; i < cost.size(); ++i) { const int u = original[i] - 'a'; const int v = changed[i] - 'a'; dist[u][v] = min(dist[u][v], static_cast<long>(cost[i])); } for (int k = 0; k < 26; ++k) for (int i = 0; i < 26; ++i) if (dist[i][k] < LONG_MAX) for (int j = 0; j < 26; ++j) if (dist[k][j] < LONG_MAX) dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); for (int i = 0; i < source.length(); ++i) { if (source[i] == target[i]) continue; const int u = source[i] - 'a'; const int v = target[i] - 'a'; if (dist[u][v] == LONG_MAX) return -1; ans += dist[u][v]; } return ans; } };
2,977
Minimum Cost to Convert String II
3
minimumCost
You are given two 0-indexed strings `source` and `target`, both of length `n` and consisting of lowercase English characters. You are also given two 0-indexed string arrays `original` and `changed`, and an integer array `cost`, where `cost[i]` represents the cost of converting the string `original[i]` to the string `changed[i]`. You start with the string `source`. In one operation, you can pick a substring `x` from the string, and change it to `y` at a cost of `z` if there exists any index `j` such that `cost[j] == z`, `original[j] == x`, and `changed[j] == y`. You are allowed to do any number of operations, but any pair of operations must satisfy either of these two conditions: * The substrings picked in the operations are `source[a..b]` and `source[c..d]` with either `b < c` or `d < a`. In other words, the indices picked in both operations are disjoint. * The substrings picked in the operations are `source[a..b]` and `source[c..d]` with `a == c` and `b == d`. In other words, the indices picked in both operations are identical. Return the minimum cost to convert the string `source` to the string `target` using any number of operations. If it is impossible to convert `source` to `target`, return `-1`. Note that there may exist indices `i`, `j` such that `original[j] == original[i]` and `changed[j] == changed[i]`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minimumCost(self, source: str, target: str, original: List[str], changed: List[str], cost: List[int]) -> int: subLengths = set(len(s) for s in original) subToId = self._getSubToId(original, changed) subCount = len(subToId) dist = [[math.inf for _ in range(subCount)] for _ in range(subCount)] dp = [math.inf for _ in range(len(source) + 1)] for a, b, c in zip(original, changed, cost): u = subToId[a] v = subToId[b] dist[u][v] = min(dist[u][v], c) for k in range(subCount): for i in range(subCount): if dist[i][k] < math.inf: for j in range(subCount): if dist[k][j] < math.inf: dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) dp[0] = 0 for i, (s, t) in enumerate(zip(source, target)): if dp[i] == math.inf: continue if s == t: dp[i + 1] = min(dp[i + 1], dp[i]) for subLength in subLengths: if i + subLength > len(source): continue subSource = source[i:i + subLength] subTarget = target[i:i + subLength] if subSource not in subToId or subTarget not in subToId: continue u = subToId[subSource] v = subToId[subTarget] if dist[u][v] != math.inf: dp[i + subLength] = min(dp[i + subLength], dp[i] + dist[u][v]) if dp[len(source)] == math.inf: return -1 else: return dp[len(source)] def _getSubToId(self, original: str, changed: str) -> Dict[str, int]: subToId = {} for s in original + changed: if s not in subToId: subToId[s] = len(subToId) return subToId
class Solution { public long minimumCost(String source, String target, String[] original, String[] changed, int[] cost) { Set<Integer> subLengths = getSubLengths(original); Map<String, Integer> subToId = getSubToId(original, changed); final int subCount = subToId.size(); // dist[u][v] := the minimum distance to change the substring with id u to // the substring with id v long[][] dist = new long[subCount][subCount]; Arrays.stream(dist).forEach(A -> Arrays.fill(A, Long.MAX_VALUE)); // dp[i] := the minimum cost to change the first i letters of `source` into // `target`, leaving the suffix untouched long[] dp = new long[source.length() + 1]; Arrays.fill(dp, Long.MAX_VALUE); for (int i = 0; i < cost.length; ++i) { final int u = subToId.get(original[i]); final int v = subToId.get(changed[i]); dist[u][v] = Math.min(dist[u][v], (long) cost[i]); } for (int k = 0; k < subCount; ++k) for (int i = 0; i < subCount; ++i) if (dist[i][k] < Long.MAX_VALUE) for (int j = 0; j < subCount; ++j) if (dist[k][j] < Long.MAX_VALUE) dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); dp[0] = 0; for (int i = 0; i < source.length(); ++i) { if (dp[i] == Long.MAX_VALUE) continue; if (target.charAt(i) == source.charAt(i)) dp[i + 1] = Math.min(dp[i + 1], dp[i]); for (int subLength : subLengths) { if (i + subLength > source.length()) continue; String subSource = source.substring(i, i + subLength); String subTarget = target.substring(i, i + subLength); if (!subToId.containsKey(subSource) || !subToId.containsKey(subTarget)) continue; final int u = subToId.get(subSource); final int v = subToId.get(subTarget); if (dist[u][v] < Long.MAX_VALUE) dp[i + subLength] = Math.min(dp[i + subLength], dp[i] + dist[u][v]); } } return dp[source.length()] == Long.MAX_VALUE ? -1 : dp[source.length()]; } private Map<String, Integer> getSubToId(String[] original, String[] changed) { Map<String, Integer> subToId = new HashMap<>(); for (final String s : original) subToId.putIfAbsent(s, subToId.size()); for (final String s : changed) subToId.putIfAbsent(s, subToId.size()); return subToId; } private Set<Integer> getSubLengths(String[] original) { Set<Integer> subLengths = new HashSet<>(); for (final String s : original) subLengths.add(s.length()); return subLengths; } }
class Solution { public: long long minimumCost(string source, string target, vector<string>& original, vector<string>& changed, vector<int>& cost) { const unordered_set<int> subLengths = getSubLengths(original); const unordered_map<string, int> subToId = getSubToId(original, changed); const int subCount = subToId.size(); // dist[u][v] := the minimum distance to change the substring with id u to // the substring with id v vector<vector<long>> dist(subCount, vector<long>(subCount, LONG_MAX)); // dp[i] := the minimum cost to change the first i letters of `source` into // `target`, leaving the suffix untouched vector<long> dp(source.length() + 1, LONG_MAX); for (int i = 0; i < cost.size(); ++i) { const int u = subToId.at(original[i]); const int v = subToId.at(changed[i]); dist[u][v] = min(dist[u][v], static_cast<long>(cost[i])); } for (int k = 0; k < subCount; ++k) for (int i = 0; i < subCount; ++i) if (dist[i][k] < LONG_MAX) for (int j = 0; j < subCount; ++j) if (dist[k][j] < LONG_MAX) dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); dp[0] = 0; for (int i = 0; i < source.length(); ++i) { if (dp[i] == LONG_MAX) continue; if (target[i] == source[i]) dp[i + 1] = min(dp[i + 1], dp[i]); for (const int subLength : subLengths) { if (i + subLength > source.length()) continue; const string subSource = source.substr(i, subLength); const string subTarget = target.substr(i, subLength); if (!subToId.contains(subSource) || !subToId.contains(subTarget)) continue; const int u = subToId.at(subSource); const int v = subToId.at(subTarget); if (dist[u][v] < LONG_MAX) dp[i + subLength] = min(dp[i + subLength], dp[i] + dist[u][v]); } } return dp[source.length()] == LONG_MAX ? -1 : dp[source.length()]; } private: unordered_map<string, int> getSubToId(const vector<string>& original, const vector<string>& changed) { unordered_map<string, int> subToId; for (const string& s : original) if (!subToId.contains(s)) subToId[s] = subToId.size(); for (const string& s : changed) if (!subToId.contains(s)) subToId[s] = subToId.size(); return subToId; } unordered_set<int> getSubLengths(const vector<string>& original) { unordered_set<int> subLengths; for (const string& s : original) subLengths.insert(s.length()); return subLengths; } };
2,983
Palindrome Rearrangement Queries
3
canMakePalindromeQueries
You are given a 0-indexed string `s` having an even length `n`. You are also given a 0-indexed 2D integer array, `queries`, where `queries[i] = [ai, bi, ci, di]`. For each query `i`, you are allowed to perform the following operations: * Rearrange the characters within the substring `s[ai:bi]`, where `0 <= ai <= bi < n / 2`. * Rearrange the characters within the substring `s[ci:di]`, where `n / 2 <= ci <= di < n`. For each query, your task is to determine whether it is possible to make `s` a palindrome by performing the operations. Each query is answered independently of the others. Return a 0-indexed array `answer`, where `answer[i] == true` if it is possible to make `s` a palindrome by performing operations specified by the `ith` query, and `false` otherwise. * A substring is a contiguous sequence of characters within a string. * `s[x:y]` represents the substring consisting of characters from the index `x` to index `y` in `s`, both inclusive.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def canMakePalindromeQueries(self, s: str, queries: List[List[int]]) -> List[bool]: n = len(s) mirroredDiffs = self._getMirroredDiffs(s) counts = self._getCounts(s) ans = [] def subtractArrays(a: List[int], b: List[int]): return [x - y for x, y in zip(a, b)] for a, b, c, d in queries: b += 1 d += 1 ra = n - a rb = n - b rc = n - c rd = n - d if (min(a, rd) > 0 and mirroredDiffs[min(a, rd)] > 0) or (n // 2 > max(b, rc) and mirroredDiffs[n // 2] - mirroredDiffs[max(b, rc)] > 0) or (rd > b and mirroredDiffs[rd] - mirroredDiffs[b] > 0) or (a > rc and mirroredDiffs[a] - mirroredDiffs[rc] > 0): ans.append(False) else: leftRangeCount = subtractArrays(counts[b], counts[a]) rightRangeCount = subtractArrays(counts[d], counts[c]) if a > rd: rightRangeCount = subtractArrays( rightRangeCount, subtractArrays(counts[min(a, rc)], counts[rd])) if rc > b: rightRangeCount = subtractArrays( rightRangeCount, subtractArrays(counts[rc], counts[max(b, rd)])) if c > rb: leftRangeCount = subtractArrays( leftRangeCount, subtractArrays(counts[min(c, ra)], counts[rb])) if ra > d: leftRangeCount = subtractArrays( leftRangeCount, subtractArrays(counts[ra], counts[max(d, rb)])) ans.append(min(leftRangeCount) >= 0 and min(rightRangeCount) >= 0 and leftRangeCount == rightRangeCount) return ans def _getMirroredDiffs(self, s: str) -> List[int]: diffs = [0] for i, j in zip(range(len(s)), reversed(range(len(s)))): if i >= j: break diffs.append(diffs[-1] + (s[i] != s[j])) return diffs def _getCounts(self, s: str) -> List[List[int]]: count = [0] * 26 counts = [count.copy()] for c in s: count[ord(c) - ord('a')] += 1 counts.append(count.copy()) return counts
class Solution { public boolean[] canMakePalindromeQueries(String s, int[][] queries) { final int n = s.length(); // mirroredDiffs[i] := the number of different letters between the first i // letters of s[0..n / 2) and the first i letters of s[n / 2..n)[::-1] final int[] mirroredDiffs = getMirroredDiffs(s); // counts[i] := the count of s[0..i) final int[][] counts = getCounts(s); boolean[] ans = new boolean[queries.length]; for (int i = 0; i < queries.length; i++) { // Use left-closed, right-open intervals to facilitate the calculation. // ...... [a, b) ...|... [rb, ra) ...... // .... [rd, rc) .....|..... [c, d) .... int[] query = queries[i]; final int a = query[0]; final int b = query[1] + 1; final int c = query[2]; final int d = query[3] + 1; final int ra = n - a; // the reflected index of a in s[n / 2..n) final int rb = n - b; // the reflected index of b in s[n / 2..n) final int rc = n - c; // the reflected index of c in s[n / 2..n) final int rd = n - d; // the reflected index of d in s[n / 2..n) // No difference is allowed outside the query ranges. if ((Math.min(a, rd) > 0 && mirroredDiffs[Math.min(a, rd)] > 0) || (n / 2 > Math.max(b, rc) && mirroredDiffs[n / 2] - mirroredDiffs[Math.max(b, rc)] > 0) || (rd > b && mirroredDiffs[rd] - mirroredDiffs[b] > 0) || (a > rc && mirroredDiffs[a] - mirroredDiffs[rc] > 0)) { ans[i] = false; } else { // The `count` map of the intersection of [a, b) and [rd, rc) in // s[0..n / 2) must equate to the `count` map of the intersection of // [c, d) and [rb, ra) in s[n / 2..n). int[] leftRangeCount = subtractArrays(counts[b], counts[a]); int[] rightRangeCount = subtractArrays(counts[d], counts[c]); if (a > rd) rightRangeCount = subtractArrays(rightRangeCount, subtractArrays(counts[Math.min(a, rc)], counts[rd])); if (rc > b) rightRangeCount = subtractArrays(rightRangeCount, subtractArrays(counts[rc], counts[Math.max(b, rd)])); if (c > rb) leftRangeCount = subtractArrays(leftRangeCount, subtractArrays(counts[Math.min(c, ra)], counts[rb])); if (ra > d) leftRangeCount = subtractArrays(leftRangeCount, subtractArrays(counts[ra], counts[Math.max(d, rb)])); ans[i] = Arrays.stream(leftRangeCount).allMatch(freq -> freq >= 0) && Arrays.stream(rightRangeCount).allMatch(freq -> freq >= 0) && Arrays.equals(leftRangeCount, rightRangeCount); } } return ans; } private int[] getMirroredDiffs(final String s) { int[] diffs = new int[s.length() / 2 + 1]; for (int i = 0, j = s.length() - 1; i < j; i++, j--) { diffs[i + 1] = diffs[i] + (s.charAt(i) != s.charAt(j) ? 1 : 0); } return diffs; } private int[][] getCounts(final String s) { int[][] counts = new int[s.length() + 1][26]; int[] count = new int[26]; for (int i = 0; i < s.length(); ++i) { ++count[s.charAt(i) - 'a']; System.arraycopy(count, 0, counts[i + 1], 0, 26); } return counts; } private int[] subtractArrays(int[] a, int[] b) { int[] res = new int[a.length]; for (int i = 0; i < a.length; ++i) res[i] = a[i] - b[i]; return res; } }
class Solution { public: vector<bool> canMakePalindromeQueries(string s, vector<vector<int>>& queries) { const int n = s.length(); // mirroredDiffs[i] := the number of different letters between the first i // letters of s[0..n / 2) and the first i letters of s[n / 2..n)[::-1] const vector<int> mirroredDiffs = getMirroredDiffs(s); // counts[i] := the count of s[0..i) const vector<vector<int>> counts = getCounts(s); vector<bool> ans; for (const vector<int>& query : queries) { // Use left-closed, right-open intervals to facilitate the calculation. // ...... [a, b) ...|... [rb, ra) ...... // .... [rd, rc) .....|..... [c, d) .... const int a = query[0]; const int b = query[1] + 1; const int c = query[2]; const int d = query[3] + 1; const int ra = n - a; // the reflected index of a in s[n / 2..n) const int rb = n - b; // the reflected index of b in s[n / 2..n) const int rc = n - c; // the reflected index of c in s[n / 2..n) const int rd = n - d; // the reflected index of d in s[n / 2..n) // No difference is allowed outside the query ranges. if (min(a, rd) > 0 && mirroredDiffs[min(a, rd)] > 0 || n / 2 > max(b, rc) && mirroredDiffs[n / 2] - mirroredDiffs[max(b, rc)] > 0 || rd > b && mirroredDiffs[rd] - mirroredDiffs[b] > 0 || a > rc && mirroredDiffs[a] - mirroredDiffs[rc] > 0) { ans.push_back(false); } else { // The `count` map of the intersection of [a, b) and [rd, rc) in // s[0..n / 2) must equate to the `count` map of the intersection of // [c, d) and [rb, ra) in s[n / 2..n). vector<int> leftRangeCount = subtractArrays(counts[b], counts[a]); vector<int> rightRangeCount = subtractArrays(counts[d], counts[c]); if (a > rd) rightRangeCount = subtractArrays( rightRangeCount, subtractArrays(counts[min(a, rc)], counts[rd])); if (rc > b) rightRangeCount = subtractArrays( rightRangeCount, subtractArrays(counts[rc], counts[max(b, rd)])); if (c > rb) leftRangeCount = subtractArrays( leftRangeCount, subtractArrays(counts[min(c, ra)], counts[rb])); if (ra > d) leftRangeCount = subtractArrays( leftRangeCount, subtractArrays(counts[ra], counts[max(d, rb)])); ans.push_back(ranges::all_of(leftRangeCount, [](int freq) { return freq >= 0; }) && ranges::all_of(rightRangeCount, [](int freq) { return freq >= 0; }) && leftRangeCount == rightRangeCount); } } return ans; } private: vector<int> getMirroredDiffs(const string& s) { vector<int> diffs(1); for (int i = 0, j = s.length() - 1; i < j; ++i, --j) diffs.push_back(diffs.back() + (s[i] != s[j] ? 1 : 0)); return diffs; } vector<vector<int>> getCounts(const string& s) { vector<int> count(26); vector<vector<int>> counts{count}; for (const char c : s) { ++count[c - 'a']; counts.push_back(count); } return counts; } vector<int> subtractArrays(const vector<int>& a, const vector<int>& b) { vector<int> res; for (int i = 0; i < a.size(); ++i) res.push_back(a[i] - b[i]); return res; } };
3,001
Minimum Moves to Capture The Queen
2
minMovesToCaptureTheQueen
There is a 1-indexed `8 x 8` chessboard containing `3` pieces. You are given `6` integers `a`, `b`, `c`, `d`, `e`, and `f` where: * `(a, b)` denotes the position of the white rook. * `(c, d)` denotes the position of the white bishop. * `(e, f)` denotes the position of the black queen. Given that you can only move the white pieces, return the minimum number of moves required to capture the black queen. Note that: * Rooks can move any number of squares either vertically or horizontally, but cannot jump over other pieces. * Bishops can move any number of squares diagonally, but cannot jump over other pieces. * A rook or a bishop can capture the queen if it is located in a square that they can move to. * The queen does not move.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minMovesToCaptureTheQueen(self, a: int, b: int, c: int, d: int, e: int, f: int) -> int: if a == e: if c == a and (b < d < f or b > d > f): return 2 else: return 1 if b == f: if d == f and (a < c < e or a > c > e): return 2 else: return 1 if c + d == e + f: if a + b == c + d and (c < a < e or c > a > e): return 2 else: return 1 if c - d == e - f: if a - b == c - d and (c < a < e or c > a > e): return 2 else: return 1 return 2
class Solution { public int minMovesToCaptureTheQueen(int a, int b, int c, int d, int e, int f) { // The rook is in the same row as the queen. if (a == e) // The bishop blocks the rook or not. return (c == a && (b < d && d < f || b > d && d > f)) ? 2 : 1; // The rook is in the same column as the queen. if (b == f) // The bishop blocks the rook or not. return (d == f && (a < c && c < e || a > c && c > e)) ? 2 : 1; // The bishop is in the same up-diagonal as the queen. if (c + d == e + f) // The rook blocks the bishop or not. return (a + b == c + d && (c < a && a < e || c > a && a > e)) ? 2 : 1; // The bishop is in the same down-diagonal as the queen. if (c - d == e - f) // The rook blocks the bishop or not. return (a - b == c - d && (c < a && a < e || c > a && a > e)) ? 2 : 1; // The rook can always get the green in two steps. return 2; } }
class Solution { public: int minMovesToCaptureTheQueen(int a, int b, int c, int d, int e, int f) { // The rook is in the same row as the queen. if (a == e) // The bishop blocks the rook or not. return (c == a && (b < d && d < f || b > d && d > f)) ? 2 : 1; // The rook is in the same column as the queen. if (b == f) // The bishop blocks the rook or not. return (d == f && (a < c && c < e || a > c && c > e)) ? 2 : 1; // The bishop is in the same up-diagonal as the queen. if (c + d == e + f) // The rook blocks the bishop or not. return (a + b == c + d && (c < a && a < e || c > a && a > e)) ? 2 : 1; // The bishop is in the same down-diagonal as the queen. if (c - d == e - f) // The rook blocks the bishop or not. return (a - b == c - d && (c < a && a < e || c > a && a > e)) ? 2 : 1; // The rook can always get the green in two steps. return 2; } };
3,006
Find Beautiful Indices in the Given Array I
2
beautifulIndices
You are given a 0-indexed string `s`, a string `a`, a string `b`, and an integer `k`. An index `i` is beautiful if: * `0 <= i <= s.length - a.length` * `s[i..(i + a.length - 1)] == a` * There exists an index `j` such that: * `0 <= j <= s.length - b.length` * `s[j..(j + b.length - 1)] == b` * `|j - i| <= k` Return the array that contains beautiful indices in sorted order from smallest to largest.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def beautifulIndices(self, s: str, a: str, b: str, k: int) -> List[int]: ans = [] indicesA = self._kmp(s, a) indicesB = self._kmp(s, b) indicesBIndex = 0 for i in indicesA: while indicesBIndex < len(indicesB) and indicesB[indicesBIndex] - i < -k: indicesBIndex += 1 if indicesBIndex < len(indicesB) and indicesB[indicesBIndex] - i <= k: ans.append(i) return ans def _kmp(self, s: str, pattern: str) -> List[int]: def getLPS(pattern: str) -> List[int]: lps = [0] * len(pattern) j = 0 for i in range(1, len(pattern)): while j > 0 and pattern[j] != pattern[i]: j = lps[j - 1] if pattern[i] == pattern[j]: lps[i] = j + 1 j += 1 return lps res = [] lps = getLPS(pattern) i = 0 j = 0 while i < len(s): if s[i] == pattern[j]: i += 1 j += 1 if j == len(pattern): res.append(i - j) j = lps[j - 1] elif j != 0: j = lps[j - 1] else: i += 1 return res
class Solution { public List<Integer> beautifulIndices(String s, String a, String b, int k) { List<Integer> ans = new ArrayList<>(); List<Integer> indicesA = kmp(s, a); List<Integer> indicesB = kmp(s, b); int indicesBIndex = 0; // indicesB' index for (final int i : indicesA) { // The constraint is: |j - i| <= k. So, -k <= j - i <= k. So, move // `indicesBIndex` s.t. j - i >= -k, where j := indicesB[indicesBIndex]. while (indicesBIndex < indicesB.size() && indicesB.get(indicesBIndex) - i < -k) ++indicesBIndex; if (indicesBIndex < indicesB.size() && indicesB.get(indicesBIndex) - i <= k) ans.add(i); } return ans; } // Returns the starting indices of all occurrences of the pattern in `s`. private List<Integer> kmp(final String s, final String pattern) { List<Integer> res = new ArrayList<>(); int[] lps = getLPS(pattern); int i = 0; // s' index int j = 0; // pattern's index while (i < s.length()) { if (s.charAt(i) == pattern.charAt(j)) { ++i; ++j; if (j == pattern.length()) { res.add(i - j); j = lps[j - 1]; } } else if (j != 0) { // Mismatch after j matches. // Don't match lps[0..lps[j - 1]] since they will match anyway. j = lps[j - 1]; } else { ++i; } } return res; } // Returns the lps array, where lps[i] is the length of the longest prefix of // pattern[0..i] which is also a suffix of this substring. private int[] getLPS(final String pattern) { int[] lps = new int[pattern.length()]; for (int i = 1, j = 0; i < pattern.length(); ++i) { while (j > 0 && pattern.charAt(j) != pattern.charAt(i)) j = lps[j - 1]; if (pattern.charAt(i) == pattern.charAt(j)) lps[i] = ++j; } return lps; } }
class Solution { public: vector<int> beautifulIndices(string s, string a, string b, int k) { vector<int> ans; const vector<int> indicesA = kmp(s, a); const vector<int> indicesB = kmp(s, b); int indicesBIndex = 0; // indicesB's index for (const int i : indicesA) { // The constraint is: |j - i| <= k. So, -k <= j - i <= k. So, move // `indicesBIndex` s.t. j - i >= -k, where j := indicesB[indicesBIndex]. while (indicesBIndex < indicesB.size() && indicesB[indicesBIndex] - i < -k) ++indicesBIndex; if (indicesBIndex < indicesB.size() && indicesB[indicesBIndex] - i <= k) ans.push_back(i); } return ans; } private: // Returns the starting indices of all occurrences of the pattern in `s`. vector<int> kmp(const string& s, const string& pattern) { vector<int> res; const vector<int> lps = getLPS(pattern); int i = 0; // s' index int j = 0; // pattern's index while (i < s.length()) { if (s[i] == pattern[j]) { ++i; ++j; if (j == pattern.length()) { res.push_back(i - j); j = lps[j - 1]; } } else if (j > 0) { // Mismatch after j matches. // Don't match lps[0..lps[j - 1]] since they will match anyway. j = lps[j - 1]; } else { ++i; } } return res; } // Returns the lps array, where lps[i] is the length of the longest prefix of // pattern[0..i] which is also a suffix of this substring. vector<int> getLPS(const string& pattern) { vector<int> lps(pattern.length()); for (int i = 1, j = 0; i < pattern.length(); ++i) { while (j > 0 && pattern[j] != pattern[i]) j = lps[j - 1]; if (pattern[i] == pattern[j]) lps[i] = ++j; } return lps; } };