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
3,029
Minimum Time to Revert Word to Initial State I
2
minimumTimeToInitialState
You are given a 0-indexed string `word` and an integer `k`. At every second, you must perform the following operations: * Remove the first `k` characters of `word`. * Add any `k` characters to the end of `word`. Note that you do not necessarily need to add the same characters that you removed. However, you must perf...
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 minimumTimeToInitialState(self, word: str, k: int) -> int: n = len(word) maxOps = (n - 1) // k + 1 z = self....
class Solution { // Same as 3029. Minimum Time to Revert Word to Initial State I public int minimumTimeToInitialState(String word, int k) { final int n = word.length(); final int maxOps = (n - 1) / k + 1; final int[] z = zFunction(word); for (int ans = 1; ans < maxOps; ++ans) if (z[ans * k] >=...
class Solution { public: // Same as 3029. Minimum Time to Revert Word to Initial State I int minimumTimeToInitialState(string word, int k) { const int n = word.length(); const int maxOps = (n - 1) / k + 1; const vector<int> z = zFunction(word); for (int ans = 1; ans < maxOps; ++ans) if (z[ans...
3,030
Find the Grid of Region Average
2
resultGrid
You are given a 0-indexed `m x n` grid `image` which represents a grayscale image, where `image[i][j]` represents a pixel with intensity in the range`[0..255]`. You are also given a non-negative integer `threshold`. Two pixels `image[a][b]` and `image[c][d]` are said to be adjacent if `|a - c| + |b - d| == 1`. A regi...
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 resultGrid(self, image: List[List[int]], threshold: int) -> List[List[int]]: m = len(image) n = len(image[0]) ...
class Solution { public int[][] resultGrid(int[][] image, int threshold) { final int m = image.length; final int n = image[0].length; int[][] sums = new int[m][n]; int[][] counts = new int[m][n]; for (int i = 0; i < m - 2; ++i) for (int j = 0; j < n - 2; ++j) if (isRegion(image, i, ...
class Solution { public: vector<vector<int>> resultGrid(vector<vector<int>>& image, int threshold) { const int m = image.size(); const int n = image[0].size(); vector<vector<int>> sums(m, vector<int>(n)); vector<vector<int>> counts(m, vector<int>(n)); for (int i = 0; i < m - 2; ++i) for (i...
3,043
Find the Length of the Longest Common Prefix
2
longestCommonPrefix
You are given two arrays with positive integers `arr1` and `arr2`. A prefix of a positive integer is an integer formed by one or more of its digits, starting from its leftmost digit. For example, `123` is a prefix of the integer `12345`, while `234` is not. A common prefix of two integers `a` and `b` is an integer `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 TrieNode: def __init__(self): self.children: Dict[str, TrieNode] = {} class Trie: def __init__(self): self.root = TrieNode...
class TrieNode { public TrieNode[] children = new TrieNode[10]; } class Trie { public void insert(final String word) { TrieNode node = root; for (final char c : word.toCharArray()) { final int i = c - '0'; if (node.children[i] == null) node.children[i] = new TrieNode(); node = nod...
struct TrieNode { vector<shared_ptr<TrieNode>> children; TrieNode() : children(10) {} }; class Trie { public: void insert(const string& word) { shared_ptr<TrieNode> node = root; for (const char c : word) { const int i = c - '0'; if (node->children[i] == nullptr) node->children[i] = m...
3,044
Most Frequent Prime
2
mostFrequentPrime
You are given a `m x n` 0-indexed 2D matrix `mat`. From every cell, you can create numbers in the following way: * There could be at most `8` paths from the cells namely: east, south-east, south, south-west, west, north-west, north, and north-east. * Select a path from them and append digits in this path to 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 mostFrequentPrime(self, mat: List[List[int]]) -> int: dirs = ((1, 0), (1, -1), (0, -1), (-1, -1), (-1, 0...
class Solution { public int mostFrequentPrime(int[][] mat) { final int[][] DIRS = {{1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}}; final int m = mat.length; final int n = mat[0].length; int ans = -1; int maxFreq = 0; Map<Integer, Integer> count = new HashMap<>(); fo...
class Solution { public: int mostFrequentPrime(vector<vector<int>>& mat) { constexpr int kDirs[8][2] = {{1, 0}, {1, -1}, {0, -1}, {-1, -1}, {-1, 0}, {-1, 1}, {0, 1}, {1, 1}}; const int m = mat.size(); const int n = mat[0].size(); int ans = -1; int maxFreq = 0; ...
3,072
Distribute Elements Into Two Arrays II
3
resultArray
You are given a 1-indexed array of integers `nums` of length `n`. We define a function `greaterCount` such that `greaterCount(arr, val)` returns the number of elements in `arr` that are strictly greater than `val`. You need to distribute all the elements of `nums` between two arrays `arr1` and `arr2` using `n` operat...
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class FenwickTree: def __init__(self, n: int): self.sums = [0] * (n + 1) def update(self, i: int, delta: int) -> None: while i < ...
class FenwickTree { public FenwickTree(int n) { sums = new int[n + 1]; } public void add(int i, int delta) { while (i < sums.length) { sums[i] += delta; i += lowbit(i); } } public int get(int i) { int sum = 0; while (i > 0) { sum += sums[i]; i -= lowbit(i); } ...
class FenwickTree { public: FenwickTree(int n) : sums(n + 1) {} void add(int i, int delta) { while (i < sums.size()) { sums[i] += delta; i += lowbit(i); } } int get(int i) const { int sum = 0; while (i > 0) { sum += sums[i]; i -= lowbit(i); } return sum; } ...
3,095
Shortest Subarray With OR at Least K I
1
minimumSubarrayLength
You are given an array `nums` of non-negative integers and an integer `k`. An array is called special if the bitwise `OR` of all of its elements is at least `k`. Return the length of the shortest special non-empty subarray of `nums`, or return `-1` if no special subarray exists.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minimumSubarrayLength(self, nums: List[int], k: int) -> int: ans = len(nums) + 1 ors = 0 count = collections...
class Solution { public int minimumSubarrayLength(int[] nums, int k) { final int MAX = 50; final int n = nums.length; int ans = n + 1; int ors = 0; int[] count = new int[MAX + 1]; for (int l = 0, r = 0; r < n; ++r) { ors = orNum(ors, nums[r], count); while (ors >= k && l <= r) { ...
class Solution { public: int minimumSubarrayLength(vector<int>& nums, int k) { constexpr int kMax = 50; const int n = nums.size(); int ans = n + 1; int ors = 0; vector<int> count(kMax + 1); for (int l = 0, r = 0; r < n; r++) { ors = orNum(ors, nums[r], count); while (ors >= k && ...
3,102
Minimize Manhattan Distances
3
minimumDistance
You are given a array `points` representing integer coordinates of some points on a 2D plane, where `points[i] = [xi, yi]`. The distance between two points is defined as their Manhattan distance. Return the minimum possible value for maximum distance between any two points by removing exactly one point.
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 minimumDistance(self, points: List[List[int]]) -> int: i, j = self._maxManhattanDistance(points, -1) xi, yi = se...
class Solution { public int minimumDistance(int[][] points) { final int[] maxIndices = maxManhattanDistance(points, -1); final int[] xiyi = maxManhattanDistance(points, maxIndices[0]); final int[] xjyj = maxManhattanDistance(points, maxIndices[1]); return Math.min(manhattan(points, xiyi[0], xiyi[1]), ...
class Solution { public: int minimumDistance(vector<vector<int>>& points) { const auto [i, j] = maxManhattanDistance(points, -1); const auto [xi, yi] = maxManhattanDistance(points, i); const auto [xj, yj] = maxManhattanDistance(points, j); return min(manhattan(points, xi, yi), manhattan(points, xj, y...
3,108
Minimum Cost Walk in Weighted Graph
3
minimumCost
There is an undirected weighted graph with `n` vertices labeled from `0` to `n - 1`. You are given the integer `n` and an array `edges`, where `edges[i] = [ui, vi, wi]` indicates that there is an edge between vertices `ui` and `vi` with a weight of `wi`. A walk on a graph is a sequence of vertices and edges. The walk...
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.weight = [(1 << 17) - 1] * n d...
class UnionFind { public UnionFind(int n) { id = new int[n]; rank = new int[n]; weight = new int[n]; for (int i = 0; i < n; ++i) id[i] = i; // 2^17 - 1 is the minimum number in the form 2^x - 1 > 10^5. Arrays.fill(weight, (1 << 17) - 1); } public void unionByRank(int u, int v, int w...
class UnionFind { public: // 2^17 - 1 is the minimum number in the form 2^x - 1 > 10^5. UnionFind(int n) : id(n), rank(n), weight(n, (1 << 17) - 1) { iota(id.begin(), id.end(), 0); } void unionByRank(int u, int v, int w) { const int i = find(u); const int j = find(v); const int newWeight = wei...
3,112
Minimum Time to Visit Disappearing Nodes
2
minimumTime
There is an undirected graph of `n` nodes. You are given a 2D array `edges`, where `edges[i] = [ui, vi, lengthi]` describes an edge between node `ui` and node `vi` with a traversal time of `lengthi` units. Additionally, you are given an array `disappear`, where `disappear[i]` denotes the time when the node `i` disappe...
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, n: int, edges: List[List[int]], disappear: List[int]) -> List[int]: graph = [[] for _ in range(n)]...
class Solution { public int[] minimumTime(int n, int[][] edges, int[] disappear) { List<Pair<Integer, Integer>>[] graph = new List[n]; for (int i = 0; i < n; i++) graph[i] = new ArrayList<>(); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; final int w = ...
class Solution { public: vector<int> minimumTime(int n, vector<vector<int>>& edges, vector<int>& disappear) { vector<vector<pair<int, int>>> graph(n); for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; const int w = edge[2]; ...
3,123
Find Edges in Shortest Paths
3
findAnswer
You are given an undirected weighted graph of `n` nodes numbered from 0 to `n - 1`. The graph consists of `m` edges represented by a 2D array `edges`, where `edges[i] = [ai, bi, wi]` indicates that there is an edge between nodes `ai` and `bi` with weight `wi`. Consider all the shortest paths from node 0 to node `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 findAnswer(self, n: int, edges: List[List[int]]) -> List[bool]: graph = [[] for _ in range(n)] for u, v, w in e...
class Solution { // Similar to 2203. Minimum Weighted Subgraph With the Required Paths public boolean[] findAnswer(int n, int[][] edges) { boolean[] ans = new boolean[edges.length]; List<Pair<Integer, Integer>>[] graph = new List[n]; Arrays.setAll(graph, i -> new ArrayList<>()); for (int[] edge : e...
class Solution { public: // Similar to 2203. Minimum Weighted Subgraph With the Required Paths vector<bool> findAnswer(int n, vector<vector<int>>& edges) { vector<bool> ans; vector<vector<pair<int, int>>> graph(n); for (const vector<int>& edge : edges) { const int u = edge[0]; const int v ...