Dataset Viewer
Auto-converted to Parquet Duplicate
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
4
Median of Two Sorted Arrays
3
findMedianSortedArrays
Given two sorted arrays `nums1` and `nums2` of size `m` and `n` respectively, return the median of the two sorted arrays. The overall run time complexity should be `O(log (m+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 findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float: n1 = len(nums1) n2 = len(nums2) i...
class Solution { public double findMedianSortedArrays(int[] nums1, int[] nums2) { final int n1 = nums1.length; final int n2 = nums2.length; if (n1 > n2) return findMedianSortedArrays(nums2, nums1); int l = 0; int r = n1; while (l <= r) { final int partition1 = (l + r) / 2; ...
class Solution { public: double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { const int n1 = nums1.size(); const int n2 = nums2.size(); if (n1 > n2) return findMedianSortedArrays(nums2, nums1); int l = 0; int r = n1; while (l <= r) { const int partition1 = (l ...
10
Regular Expression Matching
3
isMatch
Given an input string `s` and a pattern `p`, implement regular expression matching with support for `'.'` and `'*'` where: * `'.'` Matches any single character.​​​​ * `'*'` Matches zero or more of the preceding element. The matching should cover the entire input string (not partial).
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 isMatch(self, s: str, p: str) -> bool: m = len(s) n = len(p) dp = [[False] * (n + 1) for _ in range(m + 1)] ...
class Solution { public boolean isMatch(String s, String p) { final int m = s.length(); final int n = p.length(); // dp[i][j] := true if s[0..i) matches p[0..j) boolean[][] dp = new boolean[m + 1][n + 1]; dp[0][0] = true; for (int j = 0; j < p.length(); ++j) if (p.charAt(j) == '*' && dp...
class Solution { public: bool isMatch(string s, string p) { const int m = s.length(); const int n = p.length(); // dp[i][j] := true if s[0..i) matches p[0..j) vector<vector<bool>> dp(m + 1, vector<bool>(n + 1)); dp[0][0] = true; auto isMatch = [&](int i, int j) -> bool { return j >= 0 ...
15
3Sum
2
threeSum
Given an integer array nums, return all the triplets `[nums[i], nums[j], nums[k]]` such that `i != j`, `i != k`, and `j != k`, and `nums[i] + nums[j] + nums[k] == 0`. Notice that the solution set must not contain duplicate triplets.
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 threeSum(self, nums: List[int]) -> List[List[int]]: if len(nums) < 3: return [] ans = [] nums.sort()...
class Solution { public List<List<Integer>> threeSum(int[] nums) { if (nums.length < 3) return new ArrayList<>(); List<List<Integer>> ans = new ArrayList<>(); Arrays.sort(nums); for (int i = 0; i + 2 < nums.length; ++i) { if (i > 0 && nums[i] == nums[i - 1]) continue; // C...
class Solution { public: vector<vector<int>> threeSum(vector<int>& nums) { if (nums.size() < 3) return {}; vector<vector<int>> ans; ranges::sort(nums); for (int i = 0; i + 2 < nums.size(); ++i) { if (i > 0 && nums[i] == nums[i - 1]) continue; // Choose nums[i] as the firs...
44
Wildcard Matching
3
isMatch
Given an input string (`s`) and a pattern (`p`), implement wildcard pattern matching with support for `'?'` and `'*'` where: * `'?'` Matches any single character. * `'*'` Matches any sequence of characters (including the empty sequence). The matching should cover the entire input string (not partial).
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 isMatch(self, s: str, p: str) -> bool: m = len(s) n = len(p) dp = [[False] * (n + 1) for _ in range(m + 1)] ...
class Solution { public boolean isMatch(String s, String p) { final int m = s.length(); final int n = p.length(); // dp[i][j] := true if s[0..i) matches p[0..j) boolean[][] dp = new boolean[m + 1][n + 1]; dp[0][0] = true; for (int j = 0; j < p.length(); ++j) if (p.charAt(j) == '*') ...
class Solution { public: bool isMatch(string s, string p) { const int m = s.length(); const int n = p.length(); // dp[i][j] := true if s[0..i) matches p[0..j) vector<vector<bool>> dp(m + 1, vector<bool>(n + 1)); dp[0][0] = true; auto isMatch = [&](int i, int j) -> bool { return j >= 0 ...
54
Spiral Matrix
2
spiralOrder
Given an `m x n` `matrix`, return all elements of the `matrix` in spiral order.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def spiralOrder(self, matrix: List[List[int]]) -> List[int]: if not matrix: return [] m = len(matrix) n =...
class Solution { public List<Integer> spiralOrder(int[][] matrix) { if (matrix.length == 0) return new ArrayList<>(); final int m = matrix.length; final int n = matrix[0].length; List<Integer> ans = new ArrayList<>(); int r1 = 0; int c1 = 0; int r2 = m - 1; int c2 = n - 1; ...
class Solution { public: vector<int> spiralOrder(vector<vector<int>>& matrix) { if (matrix.empty()) return {}; const int m = matrix.size(); const int n = matrix[0].size(); vector<int> ans; int r1 = 0; int c1 = 0; int r2 = m - 1; int c2 = n - 1; // Repeatedly add matrix[r1....
65
Valid Number
3
isNumber
A valid number can be split up into these components (in order): 1. A decimal number or an integer. 2. (Optional) An `'e'` or `'E'`, followed by an integer. A decimal number can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One of the following formats: 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 isNumber(self, s: str) -> bool: s = s.strip() if not s: return False seenNum = False seenDot = Fa...
class Solution { public boolean isNumber(String s) { s = s.trim(); if (s.isEmpty()) return false; boolean seenNum = false; boolean seenDot = false; boolean seenE = false; for (int i = 0; i < s.length(); ++i) { switch (s.charAt(i)) { case '.': if (seenDot || seen...
class Solution { public: bool isNumber(string s) { trim(s); if (s.empty()) return false; bool seenNum = false; bool seenDot = false; bool seenE = false; for (int i = 0; i < s.length(); ++i) { switch (s[i]) { case '.': if (seenDot || seenE) return fa...
73
Set Matrix Zeroes
2
setZeroes
Given an `m x n` integer matrix `matrix`, if an element is `0`, set its entire row and column to `0`'s. You must do it in place.
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 setZeroes(self, matrix: List[List[int]]) -> None: m = len(matrix) n = len(matrix[0]) shouldFillFirstRow = 0 ...
class Solution { public void setZeroes(int[][] matrix) { final int m = matrix.length; final int n = matrix[0].length; boolean shouldFillFirstRow = false; boolean shouldFillFirstCol = false; for (int j = 0; j < n; ++j) if (matrix[0][j] == 0) { shouldFillFirstRow = true; break...
class Solution { public: void setZeroes(vector<vector<int>>& matrix) { const int m = matrix.size(); const int n = matrix[0].size(); bool shouldFillFirstRow = false; bool shouldFillFirstCol = false; for (int j = 0; j < n; ++j) if (matrix[0][j] == 0) { shouldFillFirstRow = true; ...
97
Interleaving String
2
isInterleave
Given strings `s1`, `s2`, and `s3`, find whether `s3` is formed by an interleaving of `s1` and `s2`. An interleaving of two strings `s` and `t` is a configuration where `s` and `t` are divided into `n` and `m` substrings respectively, such that: * `s = s1 + s2 + ... + sn` * `t = t1 + t2 + ... + tm` * `|n - m| <= 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 isInterleave(self, s1: str, s2: str, s3: str) -> bool: m = len(s1) n = len(s2) if m + n != len(s3): re...
class Solution { public boolean isInterleave(String s1, String s2, String s3) { final int m = s1.length(); final int n = s2.length(); if (m + n != s3.length()) return false; // dp[i][j] := true if s3[0..i + j) is formed by the interleaving of // s1[0..i) and s2[0..j) boolean[][] dp = ne...
class Solution { public: bool isInterleave(string s1, string s2, string s3) { const int m = s1.length(); const int n = s2.length(); if (m + n != s3.length()) return false; // dp[i][j] := true if s3[0..i + j) is formed by the interleaving of // s1[0..i) and s2[0..j) vector<vector<bool>>...
126
Word Ladder II
3
findLadders
A transformation sequence from word `beginWord` to word `endWord` using a dictionary `wordList` is a sequence of words `beginWord -> s1 -> s2 -> ... -> sk` such that: * Every adjacent pair of words differs by a single letter. * Every `si` for `1 <= i <= k` is in `wordList`. Note that `beginWord` does not need to be in...
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 findLadders(self, beginWord: str, endWord: str, wordList: List[str]) -> List[List[str]]: from collections impor...
class Solution { public List<List<String>> findLadders(String beginWord, String endWord, List<String> wordList) { Set<String> wordSet = new HashSet<>(wordList); if (!wordSet.contains(endWord)) return new ArrayList<>(); // {"hit": ["hot"], "hot": ["dot", "lot"], ...} Map<String, List<String>> gr...
class Solution { public: vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) { unordered_set<string> wordSet{wordList.begin(), wordList.end()}; if (!wordSet.contains(endWord)) return {}; // {"hit": ["hot"], "hot": ["do...
130
Surrounded Regions
2
solve
Given an `m x n` matrix `board` containing `'X'` and `'O'`, capture all regions that are 4-directionally surrounded by `'X'`. A region is captured by flipping all `'O'`s into `'X'`s in that surrounded region.
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 solve(self, board: List[List[str]]) -> None: if not board: return dirs = ((0, 1), (1, 0), (0, -1), (-1, 0...
class Solution { public void solve(char[][] board) { if (board.length == 0) return; final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; final int m = board.length; final int n = board[0].length; Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(); for (int i = 0; i < m; ++i) ...
class Solution { public: void solve(vector<vector<char>>& board) { if (board.empty()) return; constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; const int m = board.size(); const int n = board[0].size(); queue<pair<int, int>> q; for (int i = 0; i < m; ++i) for (int...
132
Palindrome Partitioning II
3
minCut
Given a string `s`, partition `s` such that every substring of the partition is a palindrome. Return the minimum cuts needed for a palindrome partitioning of `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 minCut(self, s: str) -> int: n = len(s) isPalindrome=[] for _ in range(n): isPalindrome.append([True] ...
class Solution { public int minCut(String s) { final int n = s.length(); // isPalindrome[i][j] := true if s[i..j] is a palindrome boolean[][] isPalindrome = new boolean[n][n]; for (boolean[] row : isPalindrome) Arrays.fill(row, true); // dp[i] := the minimum cuts needed for a palindrome part...
class Solution { public: int minCut(string s) { const int n = s.length(); // isPalindrome[i][j] := true if s[i..j] is a palindrome vector<vector<bool>> isPalindrome(n, vector<bool>(n, true)); // dp[i] := the minimum cuts needed for a palindrome partitioning of s[0..i] vector<int> dp(n, n); f...
218
The Skyline Problem
3
getSkyline
A city's skyline is the outer contour of the silhouette formed by all the buildings in that city when viewed from a distance. Given the locations and heights of all the buildings, return the skyline formed by these buildings collectively. The geometric information of each building is given in the array `buildings` whe...
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 getSkyline(self, buildings: List[List[int]]) -> List[List[int]]: n = len(buildings) if n == 0: return [] ...
class Solution { public List<List<Integer>> getSkyline(int[][] buildings) { final int n = buildings.length; if (n == 0) return new ArrayList<>(); if (n == 1) { final int left = buildings[0][0]; final int right = buildings[0][1]; final int height = buildings[0][2]; List<List<I...
class Solution { public: vector<vector<int>> getSkyline(const vector<vector<int>>& buildings) { const int n = buildings.size(); if (n == 0) return {}; if (n == 1) { const int left = buildings[0][0]; const int right = buildings[0][1]; const int height = buildings[0][2]; retur...
227
Basic Calculator II
2
calculate
Given a string `s` which represents an expression, evaluate this expression and return its value. The integer division should truncate toward zero. You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 1]`. Note: You are not allowed to use any built-...
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 calculate(self, s: str) -> int: ans = 0 prevNum = 0 currNum = 0 op = '+' for i, c in enumerate(s): ...
class Solution { public int calculate(String s) { Deque<Integer> nums = new ArrayDeque<>(); Deque<Character> ops = new ArrayDeque<>(); for (int i = 0; i < s.length(); ++i) { final char c = s.charAt(i); if (Character.isDigit(c)) { int num = c - '0'; while (i + 1 < s.length() &&...
class Solution { public: int calculate(string s) { stack<int> nums; stack<char> ops; for (int i = 0; i < s.length(); ++i) { const char c = s[i]; if (isdigit(c)) { int num = c - '0'; while (i + 1 < s.length() && isdigit(s[i + 1])) { num = num * 10 + (s[i + 1] - '0');...
289
Game of Life
2
gameOfLife
According to Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." The board is made up of an `m x n` grid of cells, where each cell has an initial state: live (represented by a `1`) or dead (represented by a `0`). E...
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 gameOfLife(self, board: List[List[int]]) -> None: m = len(board) n = len(board[0]) for i in range(m): ...
class Solution { public void gameOfLife(int[][] board) { final int m = board.length; final int n = board[0].length; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { int ones = 0; for (int x = Math.max(0, i - 1); x < Math.min(m, i + 2); ++x) for (int y = Math.max(0...
class Solution { public: void gameOfLife(vector<vector<int>>& board) { const int m = board.size(); const int n = board[0].size(); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { int ones = 0; for (int x = max(0, i - 1); x < min(m, i + 2); ++x) for (int y = max(0...
310
Minimum Height Trees
2
findMinHeightTrees
A tree is an undirected graph in which any two vertices are connected by exactly one path. In other words, any connected graph without simple cycles is a tree. Given a tree of `n` nodes labelled from `0` to `n - 1`, and an array of `n - 1` `edges` where `edges[i] = [ai, bi]` indicates that there is an undirected edge ...
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 findMinHeightTrees(self, n: int, edges: List[List[int]]) -> List[int]: if n == 1 or not edges: return [0] ...
class Solution { public List<Integer> findMinHeightTrees(int n, int[][] edges) { if (n == 0 || edges.length == 0) return List.of(0); List<Integer> ans = new ArrayList<>(); Map<Integer, Set<Integer>> graph = new HashMap<>(); for (int i = 0; i < n; ++i) graph.put(i, new HashSet<>()); ...
class Solution { public: vector<int> findMinHeightTrees(int n, vector<vector<int>>& edges) { if (n == 1 || edges.empty()) return {0}; vector<int> ans; unordered_map<int, unordered_set<int>> graph; for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]...
327
Count of Range Sum
3
countRangeSum
Given an integer array `nums` and two integers `lower` and `upper`, return the number of range sums that lie in `[lower, upper]` inclusive. Range sum `S(i, j)` is defined as the sum of the elements in `nums` between indices `i` and `j` inclusive, where `i <= j`.
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 countRangeSum(self, nums: List[int], lower: int, upper: int) -> int: n = len(nums) self.ans = 0 prefix = [0]...
class Solution { public int countRangeSum(int[] nums, int lower, int upper) { final int n = nums.length; long[] prefix = new long[n + 1]; for (int i = 0; i < n; ++i) prefix[i + 1] = (long) nums[i] + prefix[i]; mergeSort(prefix, 0, n, lower, upper); return ans; } private int ans = 0; ...
class Solution { public: int countRangeSum(vector<int>& nums, int lower, int upper) { const int n = nums.size(); int ans = 0; vector<long> prefix{0}; for (int i = 0; i < n; ++i) prefix.push_back(prefix.back() + nums[i]); mergeSort(prefix, 0, n, lower, upper, ans); return ans; } pr...
335
Self Crossing
3
isSelfCrossing
You are given an array of integers `distance`. You start at the point `(0, 0)` on an X-Y plane, and you move `distance[0]` meters to the north, then `distance[1]` meters to the west, `distance[2]` meters to the south, `distance[3]` meters to the east, and so on. In other words, after each move, your direction changes ...
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 isSelfCrossing(self, x: List[int]) -> bool: if len(x) <= 3: return False for i in range(3, len(x)): ...
class Solution { public boolean isSelfCrossing(int[] x) { if (x.length <= 3) return false; for (int i = 3; i < x.length; ++i) { if (x[i - 2] <= x[i] && x[i - 1] <= x[i - 3]) return true; if (i >= 4 && x[i - 1] == x[i - 3] && x[i - 2] <= x[i] + x[i - 4]) return true; if...
class Solution { public: bool isSelfCrossing(vector<int>& x) { if (x.size() <= 3) return false; for (int i = 3; i < x.size(); ++i) { if (x[i - 2] <= x[i] && x[i - 1] <= x[i - 3]) return true; if (i >= 4 && x[i - 1] == x[i - 3] && x[i - 2] <= x[i] + x[i - 4]) return true; ...
336
Palindrome Pairs
3
palindromePairs
You are given a 0-indexed array of unique strings `words`. A palindrome pair is a pair of integers `(i, j)` such that: * `0 <= i, j < words.length`, * `i != j`, and * `words[i] + words[j]` (the concatenation of the two strings) is a palindrome. Return an array of all the palindrome pairs of `words`. You must write ...
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 palindromePairs(self, words: List[str]) -> List[List[int]]: ans = [] dict = {word[::-1]: i for i, word in enumer...
class Solution { public List<List<Integer>> palindromePairs(String[] words) { List<List<Integer>> ans = new ArrayList<>(); Map<String, Integer> map = new HashMap<>(); // {reversed word: its index} for (int i = 0; i < words.length; ++i) map.put(new StringBuilder(words[i]).reverse().toString(), i); ...
class Solution { public: vector<vector<int>> palindromePairs(vector<string>& words) { vector<vector<int>> ans; unordered_map<string, int> map; // {reversed word: its index} for (int i = 0; i < words.size(); ++i) { string word = words[i]; ranges::reverse(word); map[word] = i; } ...
391
Perfect Rectangle
3
isRectangleCover
Given an array `rectangles` where `rectangles[i] = [xi, yi, ai, bi]` represents an axis-aligned rectangle. The bottom-left point of the rectangle is `(xi, yi)` and the top-right point of it is `(ai, bi)`. Return `true` if all the rectangles together form an exact cover of a rectangular region.
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 isRectangleCover(self, rectangles: List[List[int]]) -> bool: area = 0 x1 = math.inf y1 = math.inf x...
class Solution { public boolean isRectangleCover(int[][] rectangles) { int area = 0; int x1 = Integer.MAX_VALUE; int y1 = Integer.MAX_VALUE; int x2 = Integer.MIN_VALUE; int y2 = Integer.MIN_VALUE; Set<String> corners = new HashSet<>(); for (int[] r : rectangles) { area += (r[2] - r[...
class Solution { public: bool isRectangleCover(vector<vector<int>>& rectangles) { int area = 0; int x1 = INT_MAX; int y1 = INT_MAX; int x2 = INT_MIN; int y2 = INT_MIN; unordered_set<string> corners; for (const vector<int>& r : rectangles) { area += (r[2] - r[0]) * (r[3] - r[1]); ...
402
Remove K Digits
2
removeKdigits
Given string num representing a non-negative integer `num`, and an integer `k`, return the smallest possible integer after removing `k` digits from `num`.
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 removeKdigits(self, num: str, k: int) -> str: if len(num) == k: return '0' ans = [] stack = [] f...
class Solution { public String removeKdigits(String num, int k) { if (num.length() == k) return "0"; StringBuilder sb = new StringBuilder(); LinkedList<Character> stack = new LinkedList<>(); for (int i = 0; i < num.length(); ++i) { while (k > 0 && !stack.isEmpty() && stack.getLast() > nu...
class Solution { public: string removeKdigits(string num, int k) { if (num.length() == k) return "0"; string ans; vector<char> stack; for (int i = 0; i < num.length(); ++i) { while (k > 0 && !stack.empty() && stack.back() > num[i]) { stack.pop_back(); --k; } ...
407
Trapping Rain Water II
3
trapRainWater
Given an `m x n` integer matrix `heightMap` representing the height of each unit cell in a 2D elevation map, return the volume of water it can trap after raining.
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 trapRainWater(self, heightMap: List[List[int]]) -> int: dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) m = len(height...
class Solution { public int trapRainWater(int[][] heightMap) { // h := heightMap[i][j] or the height after filling water record T(int i, int j, int h) {} final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; final int m = heightMap.length; final int n = heightMap[0].length; int ans = 0; ...
struct T { int i; int j; int h; // heightMap[i][j] or the height after filling water T(int i_, int j_, int h_) : i(i_), j(j_), h(h_) {} }; class Solution { public: int trapRainWater(vector<vector<int>>& heightMap) { constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; const int m = heigh...
417
Pacific Atlantic Water Flow
2
pacificAtlantic
There is an `m x n` rectangular island that borders both the Pacific Ocean and Atlantic Ocean. The Pacific Ocean touches the island's left and top edges, and the Atlantic Ocean touches the island's right and bottom edges. The island is partitioned into a grid of square cells. You are given an `m x n` integer matrix `h...
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 pacificAtlantic(self, heights: List[List[int]]) -> List[List[int]]: dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) m ...
class Solution { public List<List<Integer>> pacificAtlantic(int[][] heights) { final int m = heights.length; final int n = heights[0].length; List<List<Integer>> ans = new ArrayList<>(); Queue<Pair<Integer, Integer>> qP = new ArrayDeque<>(); Queue<Pair<Integer, Integer>> qA = new ArrayDeque<>(); ...
class Solution { public: vector<vector<int>> pacificAtlantic(vector<vector<int>>& heights) { constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; const int m = heights.size(); const int n = heights[0].size(); vector<vector<int>> ans; queue<pair<int, int>> qP; queue<pair<int, int>> ...
420
Strong Password Checker
3
strongPasswordChecker
A password is considered strong if the below conditions are all met: * It has at least `6` characters and at most `20` characters. * It contains at least one lowercase letter, at least one uppercase letter, and at least one digit. * It does not contain three repeating characters in a row (i.e., `"Baaabb0"` is weak, bu...
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 strongPasswordChecker(self, password: str) -> int: n = len(password) missing = self._getMissing(password) re...
class Solution { public int strongPasswordChecker(String password) { final int n = password.length(); final int missing = getMissing(password); // the number of replacements to deal with 3 repeating characters int replaces = 0; // the number of sequences that can be substituted with 1 deletions, (...
class Solution { public: int strongPasswordChecker(string password) { const int n = password.length(); const int missing = getMissing(password); // the number of replacements to deal with 3 repeating characters int replaces = 0; // the number of sequences that can be substituted with 1 deletions,...
423
Reconstruct Original Digits from English
2
originalDigits
Given a string `s` containing an out-of-order English representation of digits `0-9`, return the digits in ascending order.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def originalDigits(self, s: str) -> str: count = [0] * 10 for c in s: if c == 'z': count[0] += 1 ...
class Solution { public String originalDigits(String s) { StringBuilder sb = new StringBuilder(); int[] count = new int[10]; for (final char c : s.toCharArray()) { if (c == 'z') ++count[0]; if (c == 'o') ++count[1]; if (c == 'w') ++count[2]; if (c == 'h') ...
class Solution { public: string originalDigits(string s) { string ans; vector<int> count(10); for (const char c : s) { if (c == 'z') ++count[0]; if (c == 'o') ++count[1]; if (c == 'w') ++count[2]; if (c == 'h') ++count[3]; if (c == 'u') ...
457
Circular Array Loop
2
circularArrayLoop
You are playing a game involving a circular array of non-zero integers `nums`. Each `nums[i]` denotes the number of indices forward/backward you must move if you are located at index `i`: * If `nums[i]` is positive, move `nums[i]` steps forward, and * If `nums[i]` is negative, move `nums[i]` steps backward. Since 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 circularArrayLoop(self, nums: List[int]) -> bool: def advance(i: int) -> int: return (i + nums[i]) % len(nums)...
class Solution { public boolean circularArrayLoop(int[] nums) { if (nums.length < 2) return false; for (int i = 0; i < nums.length; ++i) { if (nums[i] == 0) continue; int slow = i; int fast = advance(nums, slow); while (nums[i] * nums[fast] > 0 && nums[i] * nums[advance(...
class Solution { public: bool circularArrayLoop(vector<int>& nums) { const int n = nums.size(); if (n < 2) return false; auto advance = [&](int i) { const int val = (i + nums[i]) % n; return i + nums[i] >= 0 ? val : n + val; }; for (int i = 0; i < n; ++i) { if (nums[i] =...
524
Longest Word in Dictionary through Deleting
2
findLongestWord
Given a string `s` and a string array `dictionary`, return the longest string in the dictionary that can be formed by deleting some of the given string characters. If there is more than one possible result, return the longest word with the smallest lexicographical order. If there is no possible result, return the empty...
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 findLongestWord(self, s: str, d: List[str]) -> str: ans = '' for word in d: i = 0 for c in s: ...
class Solution { public String findLongestWord(String s, List<String> d) { String ans = ""; for (final String word : d) if (isSubsequence(word, s)) if (word.length() > ans.length() || word.length() == ans.length() && word.compareTo(ans) < 0) ans = word; return ans; ...
class Solution { public: string findLongestWord(string s, vector<string>& d) { string ans; for (const string& word : d) if (isSubsequence(word, s)) if (word.length() > ans.length() || word.length() == ans.length() && word.compare(ans) < 0) ans = word; return ans; }...
542
01 Matrix
2
updateMatrix
Given an `m x n` binary matrix `mat`, return the distance of the nearest `0` for each cell. The distance between two adjacent cells is `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 updateMatrix(self, mat: List[List[int]]) -> List[List[int]]: dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) m = len(m...
class Solution { public int[][] updateMatrix(int[][] mat) { final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; final int m = mat.length; final int n = mat[0].length; Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(); boolean[][] seen = new boolean[m][n]; for (int i = 0; i < m; ++i) ...
class Solution { public: vector<vector<int>> updateMatrix(vector<vector<int>>& mat) { constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; const int m = mat.size(); const int n = mat[0].size(); queue<pair<int, int>> q; vector<vector<bool>> seen(m, vector<bool>(n)); for (int i = 0;...
547
Friend Circles
2
findCircleNum
There are `n` cities. Some of them are connected, while some are not. If city `a` is connected directly with city `b`, and city `b` is connected directly with city `c`, then city `a` is connected indirectly with city `c`. A province is a group of directly or indirectly connected cities and no other cities outside of 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 UnionFind: def __init__(self, n: int): self.count = n self.id = list(range(n)) self.rank = [0] * n def unionByRank(self...
class UnionFind { public UnionFind(int n) { count = 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]) { ...
class UnionFind { public: UnionFind(int n) : count(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]) { ...
581
Shortest Unsorted Continuous Subarray
2
findUnsortedSubarray
Given an integer array `nums`, you need to find one continuous subarray such that if you only sort this subarray in non-decreasing order, then the whole array will be sorted in non-decreasing order. Return the shortest such subarray and output its 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 findUnsortedSubarray(self, nums: List[int]) -> int: mini = math.inf maxi = -math.inf flag = False for i...
class Solution { public int findUnsortedSubarray(int[] nums) { final int n = nums.length; int mn = Integer.MAX_VALUE; int mx = Integer.MIN_VALUE; boolean meetDecrease = false; boolean meetIncrease = false; for (int i = 1; i < n; ++i) { if (nums[i] < nums[i - 1]) meetDecrease = t...
class Solution { public: int findUnsortedSubarray(vector<int>& nums) { const int n = nums.size(); int mn = INT_MAX; int mx = INT_MIN; bool meetDecrease = false; bool meetIncrease = false; for (int i = 1; i < n; ++i) { if (nums[i] < nums[i - 1]) meetDecrease = true; if (me...
591
Tag Validator
3
isValid
Given a string representing a code snippet, implement a tag validator to parse the code and return whether it is valid. A code snippet is valid if all the following rules hold: 1. The code must be wrapped in a valid closed tag. Otherwise, the code is invalid. 2. A closed tag (not necessarily valid) has exactly the fo...
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 isValid(self, code: str) -> bool: if code[0] != '<' or code[-1] != '>': return False containsTag = False ...
class Solution { public boolean isValid(String code) { if (code.charAt(0) != '<' || code.charAt(code.length() - 1) != '>') return false; Deque<String> stack = new ArrayDeque<>(); for (int i = 0; i < code.length(); ++i) { int closeIndex = 0; if (stack.isEmpty() && containsTag) r...
class Solution { public: bool isValid(string code) { if (code[0] != '<' || code.back() != '>') return false; stack<string> stack; for (int i = 0; i < code.length(); ++i) { int closeIndex = 0; if (stack.empty() && containsTag) return false; if (code[i] == '<') { /...
648
Replace Words
2
replaceWords
In English, we have a concept called root, which can be followed by some other word to form another longer word - let's call this word successor. For example, when the root `"help"` is followed by the successor word `"ful"`, we can form a new word `"helpful"`. Given a `dictionary` consisting of many roots and a `sente...
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.root = {} def insert(self, word: str) -> None: node = self.root for c in word: ...
class TrieNode { TrieNode[] children = new TrieNode[26]; String word; } class Solution { public String replaceWords(List<String> dictionary, String sentence) { StringBuilder sb = new StringBuilder(); for (final String word : dictionary) insert(word); final String[] words = sentence.split(" ")...
struct TrieNode { vector<shared_ptr<TrieNode>> children; const string* word = nullptr; TrieNode() : children(26) {} }; class Solution { public: string replaceWords(vector<string>& dictionary, string sentence) { for (const string& word : dictionary) insert(word); string ans; istringstream is...
673
Number of Longest Increasing Subsequence
2
findNumberOfLIS
Given an integer array `nums`, return the number of longest increasing subsequences. Notice that the sequence has to be strictly increasing.
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 findNumberOfLIS(self, nums: List[int]) -> int: ans = 0 maxLength = 0 length = [1] * len(nums) count = [1...
class Solution { public int findNumberOfLIS(int[] nums) { final int n = nums.length; int ans = 0; int maxLength = 0; // length[i] := the length of the LIS ending in nums[i] int[] length = new int[n]; // count[i] := the number of LIS's ending in nums[i] int[] count = new int[n]; Arrays...
class Solution { public: int findNumberOfLIS(vector<int>& nums) { const int n = nums.size(); int ans = 0; int maxLength = 0; // length[i] := the length of LIS's ending in nums[i] vector<int> length(n, 1); // count[i] := the number of LIS's ending in nums[i] vector<int> count(n, 1); /...
684
Redundant Connection
2
findRedundantConnection
In this problem, a tree is an undirected graph that is connected and has no cycles. You are given a graph that started as a tree with `n` nodes labeled from `1` to `n`, with one additional edge added. The added edge has two different vertices chosen from `1` to `n`, and was not an edge that already existed. The graph ...
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 boolean unionByRank(int u, int v) { final int i = find(u); final int j = find(v); if (i == j) return false; if (rank[i] < rank[j]) { id[i] ...
class UnionFind { public: UnionFind(int n) : id(n), rank(n) { iota(id.begin(), id.end(), 0); } bool unionByRank(int u, int v) { const int i = find(u); const int j = find(v); if (i == j) return false; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id...
685
Redundant Connection II
3
findRedundantDirectedConnection
In this problem, a rooted tree is a directed graph such that, there is exactly one node (the root) for which all other nodes are descendants of this node, plus every node has exactly one parent, except for the root node which has no parents. The given input is a directed graph that started as a rooted tree with `n` 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 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 boolean unionByRank(int u, int v) { final int i = find(u); final int j = find(v); if (i == j) return false; if (rank[i] < rank[j]) { id[i] ...
class UnionFind { public: UnionFind(int n) : id(n), rank(n) { iota(id.begin(), id.end(), 0); } bool unionByRank(int u, int v) { const int i = find(u); const int j = find(v); if (i == j) return false; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id...
688
Knight Probability in Chessboard
2
knightProbability
On an `n x n` chessboard, a knight starts at the cell `(row, column)` and attempts to make exactly `k` moves. The rows and columns are 0-indexed, so the top-left cell is `(0, 0)`, and the bottom-right cell is `(n - 1, n - 1)`. A chess knight has eight possible moves it can make, as illustrated below. Each move is two ...
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 knightProbability(self, n: int, k: int, row: int, column: int) -> float: dirs = ((1, 2), (2, 1), (2, -1), (1, -2), (...
class Solution { public double knightProbability(int n, int k, int row, int column) { final int[][] DIRS = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}}; final double PROB = 0.125; // dp[i][j] := the probability to stand on (i, j) double[][] dp = new double[n][n]; dp[row...
class Solution { public: double knightProbability(int n, int k, int row, int column) { constexpr int kDirs[8][2] = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}}; constexpr double kProb = 0.125; // dp[i][j] := the probability to stand on (i, ...
689
Maximum Sum of 3 Non-Overlapping Subarrays
3
maxSumOfThreeSubarrays
Given an integer array `nums` and an integer `k`, find three non-overlapping subarrays of length `k` with maximum sum and return them. Return the result as a list of indices representing the starting position of each interval (0-indexed). If there are multiple answers, return the lexicographically smallest 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 maxSumOfThreeSubarrays(self, nums: List[int], k: int) -> List[int]: n = len(nums) - k + 1 sums = [0] * n l =...
class Solution { public int[] maxSumOfThreeSubarrays(int[] nums, int k) { final int n = nums.length - k + 1; // sums[i] := sum(nums[i..i + k)) int[] sums = new int[n]; // l[i] := the index in [0..i] that has the maximum sums[i] int[] l = new int[n]; // r[i] := the index in [i..n) that has the ...
class Solution { public: vector<int> maxSumOfThreeSubarrays(vector<int>& nums, int k) { const int n = nums.size() - k + 1; // sums[i] := sum(nums[i..i + k)) vector<int> sums(n); // l[i] := the index in [0..i] that has the maximum sums[i] vector<int> l(n); // r[i] := the index in [i..n) that h...
691
Stickers to Spell Word
3
minStickers
We are given `n` different types of `stickers`. Each sticker has a lowercase English word on it. You would like to spell out the given string `target` by cutting individual letters from your collection of stickers and rearranging them. You can use each sticker more than once if you want, and you have infinite quantiti...
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 minStickers(self, stickers: List[str], target: str) -> int: maxMask = 1 << len(target) dp = [math.inf] * maxMask...
class Solution { public int minStickers(String[] stickers, String target) { final int n = target.length(); final int maxMask = 1 << n; // dp[i] := the minimum number of stickers to spell out i, where i is the // bit mask of target int[] dp = new int[maxMask]; Arrays.fill(dp, Integer.MAX_VALUE)...
class Solution { public: int minStickers(vector<string>& stickers, string target) { const int n = target.size(); const int maxMask = 1 << n; // dp[i] := the minimum number of stickers to spell out i, where i is the // bit mask of target vector<int> dp(maxMask, INT_MAX); dp[0] = 0; for (i...
722
Remove Comments
2
removeComments
Given a C++ program, remove comments from it. The program source is an array of strings `source` where `source[i]` is the `ith` line of the source code. This represents the result of splitting the original source code string by the newline character `'\n'`. In C++, there are two types of comments, line comments, and b...
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def removeComments(self, source: List[str]) -> List[str]: ans = [] commenting = False modified = '' for lin...
class Solution { public List<String> removeComments(String[] source) { List<String> ans = new ArrayList<>(); boolean commenting = false; StringBuilder modified = new StringBuilder(); for (final String line : source) { for (int i = 0; i < line.length();) { if (i + 1 == line.length()) { ...
class Solution { public: vector<string> removeComments(vector<string>& source) { vector<string> ans; bool commenting = false; string modified; for (const string& line : source) { for (int i = 0; i < line.length();) { if (i + 1 == line.length()) { if (!commenting) ...
730
Count Different Palindromic Subsequences
3
countPalindromicSubsequences
Given a string s, return the number of different non-empty palindromic subsequences in `s`. Since the answer may be very large, return it modulo `109 + 7`. A subsequence of a string is obtained by deleting zero or more characters from the string. A sequence is palindromic if it is equal to the sequence reversed. Two...
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 countPalindromicSubsequences(self, s: str) -> int: kMod = 1_000_000_007 n = len(s) dp = [[0] * n for _ in ra...
class Solution { public int countPalindromicSubsequences(String s) { final int MOD = 1_000_000_007; final int n = s.length(); // dp[i][j] := the number of different non-empty palindromic subsequences in // s[i..j] int[][] dp = new int[n][n]; for (int i = 0; i < n; ++i) dp[i][i] = 1; ...
class Solution { public: int countPalindromicSubsequences(string s) { constexpr int kMod = 1'000'000'007; const int n = s.length(); // dp[i][j] := the number of different non-empty palindromic subsequences in // s[i..j] vector<vector<long>> dp(n, vector<long>(n)); for (int i = 0; i < n; ++i)...
735
Asteroid Collision
2
asteroidCollision
We are given an array `asteroids` of integers representing asteroids in a row. For each asteroid, the absolute value represents its size, and the sign represents its direction (positive meaning right, negative meaning left). Each asteroid moves at the same speed. Find out the state of the asteroids after all collisio...
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 asteroidCollision(self, asteroids: List[int]) -> List[int]: stack = [] for a in asteroids: if a > 0: ...
class Solution { public int[] asteroidCollision(int[] asteroids) { Stack<Integer> stack = new Stack<>(); for (final int a : asteroids) if (a > 0) { stack.push(a); } else { // a < 0 // Destroy the previous positive one(s). while (!stack.isEmpty() && stack.peek() > 0 && stac...
class Solution { public: vector<int> asteroidCollision(vector<int>& asteroids) { vector<int> stack; for (const int a : asteroids) if (a > 0) { stack.push_back(a); } else { // a < 0 // Destroy the previous positive one(s). while (!stack.empty() && stack.back() > 0 && stac...
743
Network Delay Time
2
networkDelayTime
You are given a network of `n` nodes, labeled from `1` to `n`. You are also given `times`, a list of travel times as directed edges `times[i] = (ui, vi, wi)`, where `ui` is the source node, `vi` is the target node, and `wi` is the time it takes for a signal to travel from source to target. We will send a signal from 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 networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: graph = [[] for _ in range(n)] for u, v,...
class Solution { public int networkDelayTime(int[][] times, int n, int k) { List<Pair<Integer, Integer>>[] graph = new List[n]; for (int i = 0; i < n; i++) graph[i] = new ArrayList<>(); for (int[] time : times) { final int u = time[0] - 1; final int v = time[1] - 1; final int w =...
class Solution { public: int networkDelayTime(vector<vector<int>>& times, int n, int k) { vector<vector<pair<int, int>>> graph(n); for (const vector<int>& time : times) { const int u = time[0] - 1; const int v = time[1] - 1; const int w = time[2]; graph[u].emplace_back(v, w); } ...
770
Basic Calculator IV
3
basicCalculatorIV
Given an expression such as `expression = "e + 8 - a + 5"` and an evaluation map such as `{"e": 1}` (given in terms of `evalvars = ["e"]` and `evalints = [1]`), return a list of tokens representing the simplified expression, such as `["-1*a","14"]` * An expression alternates chunks and symbols, with a space separating...
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Poly: def __init__(self, term: str = None, coef: int = None): if term and coef: self.terms = collections.Counter({term: coef...
class Poly { public Poly add(Poly o) { for (final String term : o.terms.keySet()) terms.merge(term, o.terms.get(term), Integer::sum); return this; } public Poly minus(Poly o) { for (final String term : o.terms.keySet()) terms.merge(term, -o.terms.get(term), Integer::sum); return this;...
class Poly { friend Poly operator+(const Poly& lhs, const Poly& rhs) { Poly res(lhs); for (const auto& [term, coef] : rhs.terms) res.terms[term] += coef; return res; } friend Poly operator-(const Poly& lhs, const Poly& rhs) { Poly res(lhs); for (const auto& [term, coef] : rhs.terms) ...
777
Swap Adjacent in LR String
2
canTransform
In a string composed of `'L'`, `'R'`, and `'X'` characters, like `"RXXLRXRXL"`, a move consists of either replacing one occurrence of `"XL"` with `"LX"`, or replacing one occurrence of `"RX"` with `"XR"`. Given the starting string `start` and the ending string `end`, return `True` if and only if there exists a sequence...
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 canTransform(self, start: str, end: str) -> bool: if start.replace('X', '') != end.replace('X', ''): return Fa...
class Solution { public boolean canTransform(String start, String end) { if (!start.replace("X", "").equals(end.replace("X", ""))) return false; int i = 0; // start's index int j = 0; // end's index while (i < start.length() && j < end.length()) { while (i < start.length() && start.charA...
class Solution { public: bool canTransform(string start, string end) { if (removeX(start) != removeX(end)) return false; int i = 0; // start's index int j = 0; // end's index while (i < start.length() && j < end.length()) { while (i < start.length() && start[i] == 'X') ++i; ...
782
Transform to Chessboard
3
movesToChessboard
You are given an `n x n` binary grid `board`. In each move, you can swap any two rows with each other, or any two columns with each other. Return the minimum number of moves to transform the board into a chessboard board. If the task is impossible, return `-1`. A chessboard board is a board where no `0`'s and no `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 movesToChessboard(self, board: List[List[int]]) -> int: n = len(board) for i in range(n): for j in range(...
class Solution { public int movesToChessboard(int[][] board) { final int n = board.length; int rowSum = 0; int colSum = 0; int rowSwaps = 0; int colSwaps = 0; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) if ((board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j]) == 1...
class Solution { public: int movesToChessboard(vector<vector<int>>& board) { const int n = board.size(); int rowSum = 0; int colSum = 0; int rowSwaps = 0; int colSwaps = 0; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) if (board[0][0] ^ board[i][0] ^ board[0][j] ^ boa...
786
K-th Smallest Prime Fraction
2
kthSmallestPrimeFraction
You are given a sorted integer array `arr` containing `1` and prime numbers, where all the integers of `arr` are unique. You are also given an integer `k`. For every `i` and `j` where `0 <= i < j < arr.length`, we consider the fraction `arr[i] / arr[j]`. Return the `kth` smallest fraction considered. Return your answ...
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 kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]: n = len(arr) ans = [0, 1] l = 0 r =...
class Solution { public int[] kthSmallestPrimeFraction(int[] arr, int k) { final int n = arr.length; double l = 0.0; double r = 1.0; while (l < r) { final double m = (l + r) / 2.0; int fractionsNoGreaterThanM = 0; int p = 0; int q = 1; // For each index i, find the firs...
class Solution { public: vector<int> kthSmallestPrimeFraction(vector<int>& arr, int k) { const int n = arr.size(); double l = 0.0; double r = 1.0; while (l < r) { const double m = (l + r) / 2.0; int fractionsNoGreaterThanM = 0; int p = 0; int q = 1; // For each index i...
787
Cheapest Flights Within K Stops
2
findCheapestPrice
There are `n` cities connected by some number of flights. You are given an array `flights` where `flights[i] = [fromi, toi, pricei]` indicates that there is a flight from city `fromi` to city `toi` with cost `pricei`. You are also given three integers `src`, `dst`, and `k`, return the cheapest price from `src` to `dst...
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 findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: graph = [[] for _ in r...
class Solution { public int findCheapestPrice(int n, int[][] flights, int src, int dst, int k) { List<Pair<Integer, Integer>>[] graph = new List[n]; for (int i = 0; i < n; i++) graph[i] = new ArrayList<>(); for (int[] flight : flights) { final int u = flight[0]; final int v = flight[1]...
class Solution { public: int findCheapestPrice(int n, vector<vector<int>>& flights, int src, int dst, int k) { vector<vector<pair<int, int>>> graph(n); for (const vector<int>& flight : flights) { const int u = flight[0]; const int v = flight[1]; const int w = flight...
End of preview. Expand in Data Studio

TestEval-extend

This is the extended dataset used in the paper DiffuTester: Accelerating Unit Test Generation for Diffusion LLMs via Mining Structural Pattern.

Code: https://github.com/TsinghuaISE/DiffuTester

Overview

Software development relies heavily on extensive unit testing, making the efficiency of automated Unit Test Generation (UTG) crucial. This dataset, TestEval-extend, is designed to evaluate diffusion large language models (dLLMs) in UTG. It extends the original TestEval benchmark by incorporating additional programming languages, including Java and C++, alongside Python, to enable comprehensive evaluation of dLLMs for UTG. The dataset supports research into accelerating UTG without compromising the quality of the generated test cases, as explored by the DiffTester framework.

Sample Usage

To get started with the associated code and reproduce the main results from the paper, follow these steps:

Installation

First, install the Python dependencies:

pip install -r requirements.txt

For Java, you need to install JDK17 and Maven. You can set them up with the following commands:

wget https://download.oracle.com/java/17/archive/jdk-17.0.12_linux-x64_bin.tar.gz
wget https://dlcdn.apache.org/maven/maven-3/3.9.11/binaries/apache-maven-3.9.11-bin.tar.gz
tar -zxvf jdk-17.0.12_linux-x64_bin.tar.gz
tar -zxvf apache-maven-3.9.11-bin.tar.gz
export JAVA_HOME=~/jdk-17.0.12
export PATH=$PATH:$JAVA_HOME/bin
export MAVEN_HOME=~/apache-maven-3.9.11
export PATH=$PATH:$MAVEN_HOME/bin

For C++, ensure your environment supports the C++20 standard.

Run Experiments

After environment preparation, you can run the following command to reproduce the main results in the paper:

./run_all.sh

Note: to enable acceleration, the evaluation code will replace generate_utils.py in the model folder with ./generate_utils_diffucoder.py. Please make sure that generate_utils.py in your model folder is writable.

Downloads last month
19

Paper for wellbeing/TestEval-extend