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 ...
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()) ...
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 = getValidDistributi...
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>> validD...
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 possi...
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: kMaxCompa...
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] := th...
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, subs...
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`...
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) ...
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...
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 wei...
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 ...
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 = ...
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.isE...
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) { //...
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-l...
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)...
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....
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,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 a...
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,...
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] == ...
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->chil...
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 `...
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: ...
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", ...
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"...
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 ances...
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 = [...
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]; ...
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]; co...
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 pa...
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) -...
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; ...
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] = ...
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 numb...
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 minPrimeFac...
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...
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); ...
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 m...
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 = le...
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>>...
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...
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 n...
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) cou...
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 = ...
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, wher...
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 ...
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 i...
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[...
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); grap...
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): ...
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])) { ...
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 ...
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 `...
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(): ...
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(removeLeadin...
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.len...
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]`...
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 ...
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<>()); ...
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 ...
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 ...
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) ...
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) { ...
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) { ...
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 ...
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 '(&|': ...
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 =...
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, ...
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`....
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]: numToInd...
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]].ad...
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....
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 ...
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...
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 ...
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 cons...
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 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 nearestExit(self, maze: List[List[str]], entrance: List[int]) -> int: dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) ...
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]))); bool...
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...
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 roa...
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 =...
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];...
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...
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 `pare...
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 = Tr...
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...
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] == null...
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 ...
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) -...
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; ...
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] = ...
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 intege...
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: ...
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...
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(...
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 wri...
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(...
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[][...
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<ve...
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. * `...
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...
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 (...
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 : ...
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 ...
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) -...
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; ...
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] = ...
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 expressio...
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 =...
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<>(...
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<i...
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` time...
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...
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...
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() &&...
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]...
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); fi...
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() *...
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 pai...
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...
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...
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 ...
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...
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]) ...
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....
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(); ...
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 o...
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) -...
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; ...
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] = ...
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 ...
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': ...
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 i...
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) bec...
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. Finall...
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) -...
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; ...
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] = ...
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,...
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 = [] ...
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...
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()); unorder...
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 ...
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, favorit...
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 = ne...
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> maxC...
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 occupie...
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(g...
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...
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][...
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 repr...
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]]: d...
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 in...
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...
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 follow...
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, ...
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) ...
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...
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 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 repeatLimitedString(self, s: str, repeatLimit: int) -> str: ans = '' count = collections.Counter(s) while T...
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); ...
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); ...
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 ...
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 ra...
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 A...
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]; ...
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 no...
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 = [[] f...
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) { fi...
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...
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...
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 ...
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] // top...
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...
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 cardi...
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...
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) ...
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)); vect...
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 sa...
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) *...
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 =...
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; i...
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 ...
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) ...
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}); }...
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; ve...
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 characte...
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.islo...
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().anyMat...
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 = range...
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. Retu...
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 rang...
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) ...
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 (...
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 ...
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(l...
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<>(...
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 = ...
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 passe...
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() passeng...
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; ...
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; /...
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 t...
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: ...
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) == '_') ...
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...
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...
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]]: rowOrd...
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()) ...
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 = ...
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 ...
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 *=...
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 * ...
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] == '?') ...
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 creat...
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 ...
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; ...
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, ...
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...
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 minH...
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.siz...
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) { ...
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 ...
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 = [[]...
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 ArrayLis...
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 ...
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] != n...
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 ma...
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 ...
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] ...
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...
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__...
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<...
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(); ...
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 gr...
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: ...
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(...
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> oddNod...
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...
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=[] ...
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}...
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 minD...
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 wa...
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 -...
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<Intege...
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>, gre...
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...
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 = (...
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 -> ...
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) ...
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 incre...
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) prevNu...
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 ...
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_boun...
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...
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 ra...
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...
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]...
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...
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...
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 && n...
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] < ...
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 po...
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(s...
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] := t...
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, ...
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...
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))): ...
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) //...
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 t...
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...
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 ...
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...
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] ...
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 t...
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)...
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) { ...
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) fo...
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 grap...
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.edge...
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 = f...
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;...
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 we...
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]]...
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) { fina...
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...
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...
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 h...
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; ...
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; ...
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 ...
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) -> ...
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; ...
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[...
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...
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 cla...
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)]...
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);...
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 in...
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__...
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 l...
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{}, ...
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 l...
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 ...
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 Li...
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; //...
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...
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 = le...
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; } ...
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 ...
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 `...
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 minPrimeF...
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 i...
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] := t...
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 tot...
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 a...
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]...
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]...
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...
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...
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') // '...
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' retu...
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 `querie...
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 =...
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...
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-...
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. R...
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...
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; ++...
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 = ...
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...
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 =...
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...
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 ...
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 ...
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 ...
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) ...
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...
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]`,...
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) ...
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] ...
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 be...
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 co...
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 ...
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) {...
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) { ...
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 repea...
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...
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...
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...
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. Retu...
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 ...
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) { ...
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 ...
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] = [...
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 d...
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 heigh...
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(querie...
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 ...
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) numAndInde...
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() || ...
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 (c...
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 th...
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._countCo...
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 += count...
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) ...
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 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 numberOfSets(self, n: int, maxDistance: int, roads: List[List[int]]) -> int: return sum(self._floydWarshall(n, maxDi...
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...
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: // Ret...
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 le...
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...
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); max...
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)); ran...
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...
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 = ...
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...
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...
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 `ch...
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: subLen...
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(); // d...
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);...
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 ...
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....
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 = getMirroredDif...
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 / ...
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 th...
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 a...
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 t...
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...
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 t...
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) ind...
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 constr...
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 ...