Dataset Viewer
Auto-converted to Parquet
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) if n1 > n2: return self.findMedianSortedArrays(nums2, nums1) l = 0 r = n1 while l <= r: partition1 = (l + r) // 2 partition2 = (n1 + n2 + 1) // 2 - partition1 maxLeft1 = -2**31 if partition1 == 0 else nums1[partition1 - 1] maxLeft2 = -2**31 if partition2 == 0 else nums2[partition2 - 1] minRight1 = 2**31 - 1 if partition1 == n1 else nums1[partition1] minRight2 = 2**31 - 1 if partition2 == n2 else nums2[partition2] if maxLeft1 <= minRight2 and maxLeft2 <= minRight1: if (n1 + n2) % 2 == 0: return (max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) * 0.5 else: return max(maxLeft1, maxLeft2) elif maxLeft1 > minRight2: r = partition1 - 1 else: l = partition1 + 1
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; final int partition2 = (n1 + n2 + 1) / 2 - partition1; final int maxLeft1 = partition1 == 0 ? Integer.MIN_VALUE : nums1[partition1 - 1]; final int maxLeft2 = partition2 == 0 ? Integer.MIN_VALUE : nums2[partition2 - 1]; final int minRight1 = partition1 == n1 ? Integer.MAX_VALUE : nums1[partition1]; final int minRight2 = partition2 == n2 ? Integer.MAX_VALUE : nums2[partition2]; if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) return (n1 + n2) % 2 == 0 ? (Math.max(maxLeft1, maxLeft2) + Math.min(minRight1, minRight2)) * 0.5 : Math.max(maxLeft1, maxLeft2); else if (maxLeft1 > minRight2) r = partition1 - 1; else l = partition1 + 1; } throw new IllegalArgumentException(); } }
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 + r) / 2; const int partition2 = (n1 + n2 + 1) / 2 - partition1; const int maxLeft1 = partition1 == 0 ? INT_MIN : nums1[partition1 - 1]; const int maxLeft2 = partition2 == 0 ? INT_MIN : nums2[partition2 - 1]; const int minRight1 = partition1 == n1 ? INT_MAX : nums1[partition1]; const int minRight2 = partition2 == n2 ? INT_MAX : nums2[partition2]; if (maxLeft1 <= minRight2 && maxLeft2 <= minRight1) return (n1 + n2) % 2 == 0 ? (max(maxLeft1, maxLeft2) + min(minRight1, minRight2)) * 0.5 : max(maxLeft1, maxLeft2); else if (maxLeft1 > minRight2) r = partition1 - 1; else l = partition1 + 1; } throw; } };
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)] dp[0][0] = True def isMatch(i: int, j: int) -> bool: return j >= 0 and p[j] == '.' or s[i] == p[j] for j, c in enumerate(p): if c == '*' and dp[0][j - 1]: dp[0][j + 1] = True for i in range(m): for j in range(n): if p[j] == '*': noRepeat = dp[i + 1][j - 1] doRepeat = isMatch(i, j - 1) and dp[i][j + 1] dp[i + 1][j + 1] = noRepeat or doRepeat elif isMatch(i, j): dp[i + 1][j + 1] = dp[i][j] return dp[m][n]
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[0][j - 1]) dp[0][j + 1] = true; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (p.charAt(j) == '*') { // The minimum index of '*' is 1. final boolean noRepeat = dp[i + 1][j - 1]; final boolean doRepeat = isMatch(s, i, p, j - 1) && dp[i][j + 1]; dp[i + 1][j + 1] = noRepeat || doRepeat; } else if (isMatch(s, i, p, j)) { dp[i + 1][j + 1] = dp[i][j]; } return dp[m][n]; } private boolean isMatch(final String s, int i, final String p, int j) { return j >= 0 && p.charAt(j) == '.' || s.charAt(i) == 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 && p[j] == '.' || s[i] == p[j]; }; for (int j = 0; j < p.length(); ++j) if (p[j] == '*' && dp[0][j - 1]) dp[0][j + 1] = true; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (p[j] == '*') { // The minimum index of '*' is 1. const bool noRepeat = dp[i + 1][j - 1]; const bool doRepeat = isMatch(i, j - 1) && dp[i][j + 1]; dp[i + 1][j + 1] = noRepeat || doRepeat; } else if (isMatch(i, j)) { dp[i + 1][j + 1] = dp[i][j]; } return dp[m][n]; } };
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() for i in range(len(nums) - 2): if i > 0 and nums[i] == nums[i - 1]: continue l = i + 1 r = len(nums) - 1 while l < r: summ = nums[i] + nums[l] + nums[r] if summ == 0: ans.append((nums[i], nums[l], nums[r])) l += 1 r -= 1 while nums[l] == nums[l - 1] and l < r: l += 1 while nums[r] == nums[r + 1] and l < r: r -= 1 elif summ < 0: l += 1 else: r -= 1 return ans
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; // Choose nums[i] as the first number in the triplet, then search the // remaining numbers in [i + 1, n - 1]. int l = i + 1; int r = nums.length - 1; while (l < r) { final int sum = nums[i] + nums[l] + nums[r]; if (sum == 0) { ans.add(Arrays.asList(nums[i], nums[l++], nums[r--])); while (l < r && nums[l] == nums[l - 1]) ++l; while (l < r && nums[r] == nums[r + 1]) --r; } else if (sum < 0) { ++l; } else { --r; } } } return ans; } }
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 first number in the triplet, then search the // remaining numbers in [i + 1, n - 1]. int l = i + 1; int r = nums.size() - 1; while (l < r) { const int sum = nums[i] + nums[l] + nums[r]; if (sum == 0) { ans.push_back({nums[i], nums[l++], nums[r--]}); while (l < r && nums[l] == nums[l - 1]) ++l; while (l < r && nums[r] == nums[r + 1]) --r; } else if (sum < 0) { ++l; } else { --r; } } } return ans; } };
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)] dp[0][0] = True def isMatch(i: int, j: int) -> bool: return i >= 0 and p[j] == '?' or s[i] == p[j] for j, c in enumerate(p): if c == '*': dp[0][j + 1] = dp[0][j] for i in range(m): for j in range(n): if p[j] == '*': matchEmpty = dp[i + 1][j] matchSome = dp[i][j + 1] dp[i + 1][j + 1] = matchEmpty or matchSome elif isMatch(i, j): dp[i + 1][j + 1] = dp[i][j] return dp[m][n]
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[0][j + 1] = dp[0][j]; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (p.charAt(j) == '*') { final boolean matchEmpty = dp[i + 1][j]; final boolean matchSome = dp[i][j + 1]; dp[i + 1][j + 1] = matchEmpty || matchSome; } else if (isMatch(s, i, p, j)) { dp[i + 1][j + 1] = dp[i][j]; } return dp[m][n]; } private boolean isMatch(final String s, int i, final String p, int j) { return j >= 0 && p.charAt(j) == '?' || s.charAt(i) == 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 && p[j] == '?' || s[i] == p[j]; }; for (int j = 0; j < p.length(); ++j) if (p[j] == '*') dp[0][j + 1] = dp[0][j]; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (p[j] == '*') { const bool matchEmpty = dp[i + 1][j]; const bool matchSome = dp[i][j + 1]; dp[i + 1][j + 1] = matchEmpty || matchSome; } else if (isMatch(i, j)) { dp[i + 1][j + 1] = dp[i][j]; } return dp[m][n]; } };
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 = len(matrix[0]) ans = [] r1 = 0 c1 = 0 r2 = m - 1 c2 = n - 1 while len(ans) < m * n: j = c1 while j <= c2 and len(ans) < m * n: ans.append(matrix[r1][j]) j += 1 i = r1 + 1 while i <= r2 - 1 and len(ans) < m * n: ans.append(matrix[i][c2]) i += 1 j = c2 while j >= c1 and len(ans) < m * n: ans.append(matrix[r2][j]) j -= 1 i = r2 - 1 while i >= r1 + 1 and len(ans) < m * n: ans.append(matrix[i][c1]) i -= 1 r1 += 1 c1 += 1 r2 -= 1 c2 -= 1 return ans
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; // Repeatedly add matrix[r1..r2][c1..c2] to `ans`. while (ans.size() < m * n) { for (int j = c1; j <= c2 && ans.size() < m * n; ++j) ans.add(matrix[r1][j]); for (int i = r1 + 1; i <= r2 - 1 && ans.size() < m * n; ++i) ans.add(matrix[i][c2]); for (int j = c2; j >= c1 && ans.size() < m * n; --j) ans.add(matrix[r2][j]); for (int i = r2 - 1; i >= r1 + 1 && ans.size() < m * n; --i) ans.add(matrix[i][c1]); ++r1; ++c1; --r2; --c2; } return ans; } }
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..r2][c1..c2] to `ans`. while (ans.size() < m * n) { for (int j = c1; j <= c2 && ans.size() < m * n; ++j) ans.push_back(matrix[r1][j]); for (int i = r1 + 1; i <= r2 - 1 && ans.size() < m * n; ++i) ans.push_back(matrix[i][c2]); for (int j = c2; j >= c1 && ans.size() < m * n; --j) ans.push_back(matrix[r2][j]); for (int i = r2 - 1; i >= r1 + 1 && ans.size() < m * n; --i) ans.push_back(matrix[i][c1]); ++r1, ++c1, --r2, --c2; } return ans; } };
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. One or more digits, followed by a dot `'.'`. 2. One or more digits, followed by a dot `'.'`, followed by one or more digits. 3. A dot `'.'`, followed by one or more digits. An integer can be split up into these components (in order): 1. (Optional) A sign character (either `'+'` or `'-'`). 2. One or more digits. For example, all the following are valid numbers: `["2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93", "-123.456e789"]`, while the following are not valid numbers: `["abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]`. Given a string `s`, return `true` if `s` is a valid 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 isNumber(self, s: str) -> bool: s = s.strip() if not s: return False seenNum = False seenDot = False seenE = False for i, c in enumerate(s): if c == '.': if seenDot or seenE: return False seenDot = True elif c == 'e' or c == 'E': if seenE or not seenNum: return False seenE = True seenNum = False elif c in '+-': if i > 0 and s[i - 1] not in 'eE': return False seenNum = False else: if not c.isdigit(): return False seenNum = True return seenNum
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 || seenE) return false; seenDot = true; break; case 'e': case 'E': if (seenE || !seenNum) return false; seenE = true; seenNum = false; break; case '+': case '-': if (i > 0 && s.charAt(i - 1) != 'e' && s.charAt(i - 1) != 'E') return false; seenNum = false; break; default: if (!Character.isDigit(s.charAt(i))) return false; seenNum = true; } } return seenNum; } }
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 false; seenDot = true; break; case 'e': case 'E': if (seenE || !seenNum) return false; seenE = true; seenNum = false; break; case '+': case '-': if (i > 0 && s[i - 1] != 'e' && s[i - 1] != 'E') return false; seenNum = false; break; default: if (!isdigit(s[i])) return false; seenNum = true; } } return seenNum; } private: void trim(string& s) { s.erase(0, s.find_first_not_of(' ')); s.erase(s.find_last_not_of(' ') + 1); } };
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 in matrix[0] shouldFillFirstCol = 0 in list(zip(*matrix))[0] for i in range(1, m): for j in range(1, n): if matrix[i][j] == 0: matrix[i][0] = 0 matrix[0][j] = 0 for i in range(1, m): for j in range(1, n): if matrix[i][0] == 0 or matrix[0][j] == 0: matrix[i][j] = 0 if shouldFillFirstRow: matrix[0] = [0] * n if shouldFillFirstCol: for row in matrix: row[0] = 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; } for (int i = 0; i < m; ++i) if (matrix[i][0] == 0) { shouldFillFirstCol = true; break; } // Store the information in the first row and the first column. for (int i = 1; i < m; ++i) for (int j = 1; j < n; ++j) if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } // Fill 0s for the matrix except the first row and the first column. for (int i = 1; i < m; ++i) for (int j = 1; j < n; ++j) if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0; // Fill 0s for the first row if needed. if (shouldFillFirstRow) for (int j = 0; j < n; ++j) matrix[0][j] = 0; // Fill 0s for the first column if needed. if (shouldFillFirstCol) for (int i = 0; i < m; ++i) matrix[i][0] = 0; } }
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; break; } for (int i = 0; i < m; ++i) if (matrix[i][0] == 0) { shouldFillFirstCol = true; break; } // Store the information in the first row and the first column. for (int i = 1; i < m; ++i) for (int j = 1; j < n; ++j) if (matrix[i][j] == 0) { matrix[i][0] = 0; matrix[0][j] = 0; } // Fill 0s for the matrix except the first row and the first column. for (int i = 1; i < m; ++i) for (int j = 1; j < n; ++j) if (matrix[i][0] == 0 || matrix[0][j] == 0) matrix[i][j] = 0; // Fill 0s for the first row if needed. if (shouldFillFirstRow) for (int j = 0; j < n; ++j) matrix[0][j] = 0; // Fill 0s for the first column if needed. if (shouldFillFirstCol) for (int i = 0; i < m; ++i) matrix[i][0] = 0; } };
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` * The interleaving is `s1 + t1 + s2 + t2 + s3 + t3 + ...` or `t1 + s1 + t2 + s2 + t3 + s3 + ...` Note: `a + b` is the concatenation of strings `a` 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 isInterleave(self, s1: str, s2: str, s3: str) -> bool: m = len(s1) n = len(s2) if m + n != len(s3): return False dp=[] for _ in range(m + 1): dp.append([False] * (n + 1)) dp[0][0] = True for i in range(1, m + 1): dp[i][0] = dp[i - 1][0] and s1[i - 1] == s3[i - 1] for j in range(1, n + 1): dp[0][j] = dp[0][j - 1] and s2[j - 1] == s3[j - 1] for i in range(1, m + 1): for j in range(1, n + 1): dp[i][j] = (dp[i - 1][j] and s1[i - 1] == s3[i + j - 1]) or (dp[i][j - 1] and s2[j - 1] == s3[i + j - 1]) return dp[m][n]
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 = new boolean[m + 1][n + 1]; dp[0][0] = true; for (int i = 1; i <= m; ++i) dp[i][0] = dp[i - 1][0] && s1.charAt(i - 1) == s3.charAt(i - 1); for (int j = 1; j <= n; ++j) dp[0][j] = dp[0][j - 1] && s2.charAt(j - 1) == s3.charAt(j - 1); for (int i = 1; i <= m; ++i) for (int j = 1; j <= n; ++j) dp[i][j] = dp[i - 1][j] && s1.charAt(i - 1) == s3.charAt(i + j - 1) || dp[i][j - 1] && s2.charAt(j - 1) == s3.charAt(i + j - 1); return dp[m][n]; } }
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>> dp(m + 1, vector<bool>(n + 1)); dp[0][0] = true; for (int i = 1; i <= m; ++i) dp[i][0] = dp[i - 1][0] && s1[i - 1] == s3[i - 1]; for (int j = 1; j <= n; ++j) dp[0][j] = dp[0][j - 1] && s2[j - 1] == s3[j - 1]; for (int i = 1; i <= m; ++i) for (int j = 1; j <= n; ++j) dp[i][j] = dp[i - 1][j] && s1[i - 1] == s3[i + j - 1] || dp[i][j - 1] && s2[j - 1] == s3[i + j - 1]; return dp[m][n]; } };
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 `wordList`. * `sk == endWord` Given two words, `beginWord` and `endWord`, and a dictionary `wordList`, return all the shortest transformation sequences from `beginWord` to `endWord`, or an empty list if no such sequence exists. Each sequence should be returned as a list of the words `[beginWord, s1, s2, ..., sk]`.
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 import deque def connected(a: str, b: str) -> bool: k = 0 for i in range(len(a)): if a[i] != b[i]: k += 1 return k == 1 if endWord not in wordList: return [] visited = set([beginWord]) q = deque([beginWord]) nodes = [] find = False while q and not find: nodes.append(q.copy()) n = len(q) for _ in range(n): word = q.popleft() for item in wordList: if item in visited: continue if not connected(word, item): continue if item == endWord: find = True break visited.add(item) q.append(item) if find: break if not find: return [] ans = [] def backtracking(word, level: int, steps: List[str]): if word == beginWord: ans.append(steps[::-1]) return if level < 0: return for item in nodes[level]: if connected(item, word): steps.append(item) backtracking(item, level-1, steps) steps.pop() backtracking(endWord, len(nodes)-1, [endWord]) return ans
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>> graph = new HashMap<>(); // Build the graph from the beginWord to the endWord. if (!bfs(beginWord, endWord, wordSet, graph)) return new ArrayList<>(); List<List<String>> ans = new ArrayList<>(); List<String> path = new ArrayList<>(List.of(beginWord)); dfs(graph, beginWord, endWord, path, ans); return ans; } private boolean bfs(final String beginWord, final String endWord, Set<String> wordSet, Map<String, List<String>> graph) { Set<String> currentLevelWords = new HashSet<>(); currentLevelWords.add(beginWord); boolean reachEndWord = false; while (!currentLevelWords.isEmpty()) { for (final String word : currentLevelWords) wordSet.remove(word); Set<String> nextLevelWords = new HashSet<>(); for (final String parent : currentLevelWords) { graph.putIfAbsent(parent, new ArrayList<>()); for (final String child : getChildren(parent, wordSet)) { if (wordSet.contains(child)) { nextLevelWords.add(child); graph.get(parent).add(child); } if (child.equals(endWord)) reachEndWord = true; } } if (reachEndWord) return true; currentLevelWords = nextLevelWords; } return false; } private List<String> getChildren(final String parent, Set<String> wordSet) { List<String> children = new ArrayList<>(); StringBuilder sb = new StringBuilder(parent); for (int i = 0; i < sb.length(); ++i) { final char cache = sb.charAt(i); for (char c = 'a'; c <= 'z'; ++c) { if (c == cache) continue; sb.setCharAt(i, c); final String child = sb.toString(); if (wordSet.contains(child)) children.add(child); } sb.setCharAt(i, cache); } return children; } private void dfs(Map<String, List<String>> graph, final String word, final String endWord, List<String> path, List<List<String>> ans) { if (word.equals(endWord)) { ans.add(new ArrayList<>(path)); return; } if (!graph.containsKey(word)) return; for (final String child : graph.get(word)) { path.add(child); dfs(graph, child, endWord, path, ans); path.remove(path.size() - 1); } } }
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": ["dot", "lot"], ...} unordered_map<string, vector<string>> graph; // Build the graph from the beginWord to the endWord. if (!bfs(beginWord, endWord, wordSet, graph)) return {}; vector<vector<string>> ans; dfs(graph, beginWord, endWord, {beginWord}, ans); return ans; } private: bool bfs(const string& beginWord, const string& endWord, unordered_set<string>& wordSet, unordered_map<string, vector<string>>& graph) { unordered_set<string> currentLevelWords{beginWord}; while (!currentLevelWords.empty()) { for (const string& word : currentLevelWords) wordSet.erase(word); unordered_set<string> nextLevelWords; bool reachEndWord = false; for (const string& parent : currentLevelWords) { vector<string> children; getChildren(parent, wordSet, children); for (const string& child : children) { if (wordSet.contains(child)) { nextLevelWords.insert(child); graph[parent].push_back(child); } if (child == endWord) reachEndWord = true; } } if (reachEndWord) return true; currentLevelWords = std::move(nextLevelWords); } return false; } void getChildren(const string& parent, const unordered_set<string>& wordSet, vector<string>& children) { string s(parent); for (int i = 0; i < s.length(); ++i) { const char cache = s[i]; for (char c = 'a'; c <= 'z'; ++c) { if (c == cache) continue; s[i] = c; if (wordSet.contains(s)) children.push_back(s); } s[i] = cache; } } void dfs(const unordered_map<string, vector<string>>& graph, const string& word, const string& endWord, vector<string>&& path, vector<vector<string>>& ans) { if (word == endWord) { ans.push_back(path); return; } if (!graph.contains(word)) return; for (const string& child : graph.at(word)) { path.push_back(child); dfs(graph, child, endWord, std::move(path), ans); path.pop_back(); } } };
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)) m = len(board) n = len(board[0]) q = collections.deque() for i in range(m): for j in range(n): if i * j == 0 or i == m - 1 or j == n - 1: if board[i][j] == 'O': q.append((i, j)) board[i][j] = '*' while q: i, j = q.popleft() for dx, dy in dirs: x = i + dx y = j + dy if x < 0 or x == m or y < 0 or y == n: continue if board[x][y] != 'O': continue q.append((x, y)) board[x][y] = '*' for row in board: for i, c in enumerate(row): if c == '*': row[i] = 'O' else: row[i] = 'X'
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) for (int j = 0; j < n; ++j) if (i * j == 0 || i == m - 1 || j == n - 1) if (board[i][j] == 'O') { q.offer(new Pair<>(i, j)); board[i][j] = '*'; } // Mark the grids that stretch from the four sides with '*'. while (!q.isEmpty()) { final int i = q.peek().getKey(); final int j = q.poll().getValue(); for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == m || y < 0 || y == n) continue; if (board[x][y] != 'O') continue; q.offer(new Pair<>(x, y)); board[x][y] = '*'; } } for (char[] row : board) for (int i = 0; i < row.length; ++i) if (row[i] == '*') row[i] = 'O'; else if (row[i] == 'O') row[i] = 'X'; } }
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 j = 0; j < n; ++j) if (i * j == 0 || i == m - 1 || j == n - 1) if (board[i][j] == 'O') { q.emplace(i, j); board[i][j] = '*'; } // Mark the grids that stretch from the four sides with '*'. while (!q.empty()) { const auto [i, j] = q.front(); q.pop(); for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == m || y < 0 || y == n) continue; if (board[x][y] != 'O') continue; q.emplace(x, y); board[x][y] = '*'; } } for (vector<char>& row : board) for (char& c : row) if (c == '*') c = 'O'; else if (c == 'O') c = 'X'; } };
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] * n) dp = [n] * n for l in range(2, n + 1): i = 0 for j in range(l - 1, n): isPalindrome[i][j] = s[i] == s[j] and isPalindrome[i + 1][j - 1] i += 1 for i in range(n): if isPalindrome[0][i]: dp[i] = 0 continue for j in range(i): if isPalindrome[j + 1][i]: dp[i] = min(dp[i], dp[j] + 1) return dp[-1]
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 partitioning of s[0..i] int[] dp = new int[n]; Arrays.fill(dp, n); for (int l = 2; l <= n; ++l) for (int i = 0, j = l - 1; j < n; ++i, ++j) isPalindrome[i][j] = s.charAt(i) == s.charAt(j) && isPalindrome[i + 1][j - 1]; for (int i = 0; i < n; ++i) { if (isPalindrome[0][i]) { dp[i] = 0; continue; } // Try all the possible partitions. for (int j = 0; j < i; ++j) if (isPalindrome[j + 1][i]) dp[i] = Math.min(dp[i], dp[j] + 1); } return dp[n - 1]; } }
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); for (int l = 2; l <= n; ++l) for (int i = 0, j = l - 1; j < n; ++i, ++j) isPalindrome[i][j] = s[i] == s[j] && isPalindrome[i + 1][j - 1]; for (int i = 0; i < n; ++i) { if (isPalindrome[0][i]) { dp[i] = 0; continue; } // Try all the possible partitions. for (int j = 0; j < i; ++j) if (isPalindrome[j + 1][i]) dp[i] = min(dp[i], dp[j] + 1); } return dp.back(); } };
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` where `buildings[i] = [lefti, righti, heighti]`: * `lefti` is the x coordinate of the left edge of the `ith` building. * `righti` is the x coordinate of the right edge of the `ith` building. * `heighti` is the height of the `ith` building. You may assume all buildings are perfect rectangles grounded on an absolutely flat surface at height `0`. The skyline should be represented as a list of "key points" sorted by their x-coordinate in the form `[[x1,y1],[x2,y2],...]`. Each key point is the left endpoint of some horizontal segment in the skyline except the last point in the list, which always has a y-coordinate `0` and is used to mark the skyline's termination where the rightmost building ends. Any ground between the leftmost and rightmost buildings should be part of the skyline's contour. Note: There must be no consecutive horizontal lines of equal height in the output skyline. For instance, `[...,[2 3],[4 5],[7 5],[11 5],[12 7],...]` is not acceptable; the three lines of height 5 should be merged into one in the final output as such: `[...,[2 3],[4 5],[12 7],...]`
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def getSkyline(self, buildings: List[List[int]]) -> List[List[int]]: n = len(buildings) if n == 0: return [] if n == 1: left, right, height = buildings[0] return [[left, height], [right, 0]] left = self.getSkyline(buildings[:n // 2]) right = self.getSkyline(buildings[n // 2:]) return self._merge(left, right) def _merge(self, left: List[List[int]], right: List[List[int]]) -> List[List[int]]: ans = [] i = 0 j = 0 leftY = 0 rightY = 0 while i < len(left) and j < len(right): if left[i][0] < right[j][0]: leftY = left[i][1] self._addPoint(ans, left[i][0], max(left[i][1], rightY)) i += 1 else: rightY = right[j][1] self._addPoint(ans, right[j][0], max(right[j][1], leftY)) j += 1 while i < len(left): self._addPoint(ans, left[i][0], left[i][1]) i += 1 while j < len(right): self._addPoint(ans, right[j][0], right[j][1]) j += 1 return ans def _addPoint(self, ans: List[List[int]], x: int, y: int) -> None: if ans and ans[-1][0] == x: ans[-1][1] = y return if ans and ans[-1][1] == y: return ans.append([x, y])
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<Integer>> ans = new ArrayList<>(); ans.add(new ArrayList<>(List.of(left, height))); ans.add(new ArrayList<>(List.of(right, 0))); return ans; } List<List<Integer>> leftSkyline = getSkyline(Arrays.copyOfRange(buildings, 0, n / 2)); List<List<Integer>> rightSkyline = getSkyline(Arrays.copyOfRange(buildings, n / 2, n)); return merge(leftSkyline, rightSkyline); } private List<List<Integer>> merge(List<List<Integer>> left, List<List<Integer>> right) { List<List<Integer>> ans = new ArrayList<>(); int i = 0; // left's index int j = 0; // right's index int leftY = 0; int rightY = 0; while (i < left.size() && j < right.size()) // Choose the point with the smaller x. if (left.get(i).get(0) < right.get(j).get(0)) { leftY = left.get(i).get(1); // Update the ongoing `leftY`. addPoint(ans, left.get(i).get(0), Math.max(left.get(i++).get(1), rightY)); } else { rightY = right.get(j).get(1); // Update the ongoing `rightY`. addPoint(ans, right.get(j).get(0), Math.max(right.get(j++).get(1), leftY)); } while (i < left.size()) addPoint(ans, left.get(i).get(0), left.get(i++).get(1)); while (j < right.size()) addPoint(ans, right.get(j).get(0), right.get(j++).get(1)); return ans; } private void addPoint(List<List<Integer>> ans, int x, int y) { if (!ans.isEmpty() && ans.get(ans.size() - 1).get(0) == x) { ans.get(ans.size() - 1).set(1, y); return; } if (!ans.isEmpty() && ans.get(ans.size() - 1).get(1) == y) return; ans.add(new ArrayList<>(List.of(x, y))); } }
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]; return {{left, height}, {right, 0}}; } const vector<vector<int>> left = getSkyline({buildings.begin(), buildings.begin() + n / 2}); const vector<vector<int>> right = getSkyline({buildings.begin() + n / 2, buildings.end()}); return merge(left, right); } private: vector<vector<int>> merge(const vector<vector<int>>& left, const vector<vector<int>>& right) { vector<vector<int>> ans; int i = 0; // left's index int j = 0; // right's index int leftY = 0; int rightY = 0; while (i < left.size() && j < right.size()) // Choose the point with the smaller x. if (left[i][0] < right[j][0]) { leftY = left[i][1]; // Update the ongoing `leftY`. addPoint(ans, left[i][0], max(left[i++][1], rightY)); } else { rightY = right[j][1]; // Update the ongoing `rightY`. addPoint(ans, right[j][0], max(right[j++][1], leftY)); } while (i < left.size()) addPoint(ans, left[i][0], left[i++][1]); while (j < right.size()) addPoint(ans, right[j][0], right[j++][1]); return ans; } void addPoint(vector<vector<int>>& ans, int x, int y) { if (!ans.empty() && ans.back()[0] == x) { ans.back()[1] = y; return; } if (!ans.empty() && ans.back()[1] == y) return; ans.push_back({x, y}); } };
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-in function which evaluates strings as mathematical expressions, such as `eval()`.
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): if c.isdigit(): currNum = currNum * 10 + int(c) if not c.isdigit() and c != ' ' or i == len(s) - 1: if op == '+' or op == '-': ans += prevNum prevNum = currNum if op == '+' else -currNum elif op == '*': prevNum = prevNum * currNum elif op == '/': if prevNum < 0: prevNum = math.ceil(prevNum / currNum) else: prevNum = prevNum // currNum op = c currNum = 0 return ans + prevNum
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() && Character.isDigit(s.charAt(i + 1))) { num = num * 10 + (s.charAt(i + 1) - '0'); ++i; } nums.push(num); } else if (c == '+' || c == '-' || c == '*' || c == '/') { while (!ops.isEmpty() && compare(ops.peek(), c)) nums.push(calculate(ops.pop(), nums.pop(), nums.pop())); ops.push(c); } } while (!ops.isEmpty()) nums.push(calculate(ops.pop(), nums.pop(), nums.pop())); return nums.peek(); } private int calculate(char op, int b, int a) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } throw new IllegalArgumentException(); } // Returns true if priority(op1) >= priority(op2). private boolean compare(char op1, char op2) { return op1 == '*' || op1 == '/' || op2 == '+' || op2 == '-'; } }
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'); ++i; } nums.push(num); } else if (c == '+' || c == '-' || c == '*' || c == '/') { while (!ops.empty() && compare(ops.top(), c)) nums.push(calculate(pop(ops), pop(nums), pop(nums))); ops.push(c); } } while (!ops.empty()) nums.push(calculate(pop(ops), pop(nums), pop(nums))); return nums.top(); } private: int calculate(char op, int b, int a) { switch (op) { case '+': return a + b; case '-': return a - b; case '*': return a * b; case '/': return a / b; } throw; } // Returns true if priority(op1) >= priority(op2). bool compare(char op1, char op2) { return op1 == '*' || op1 == '/' || op2 == '+' || op2 == '-'; } char pop(stack<char>& ops) { const char op = ops.top(); ops.pop(); return op; } int pop(stack<int>& nums) { const int num = nums.top(); nums.pop(); return num; } };
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`). Each cell interacts with its eight neighbors (horizontal, vertical, diagonal) using the following four rules (taken from the above Wikipedia article): 1. Any live cell with fewer than two live neighbors dies as if caused by under-population. 2. Any live cell with two or three live neighbors lives on to the next generation. 3. Any live cell with more than three live neighbors dies, as if by over-population. 4. Any dead cell with exactly three live neighbors becomes a live cell, as if by reproduction. The next state is created by applying the above rules simultaneously to every cell in the current state, where births and deaths occur simultaneously. Given the current state of the `m x n` grid `board`, return the next state.
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): for j in range(n): ones = 0 for x in range(max(0, i - 1), min(m, i + 2)): for y in range(max(0, j - 1), min(n, j + 2)): ones += board[x][y] & 1 if board[i][j] == 1 and (ones == 3 or ones == 4): board[i][j] |= 0b10 if board[i][j] == 0 and ones == 3: board[i][j] |= 0b10 for i in range(m): for j in range(n): board[i][j] >>= 1
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, j - 1); y < Math.min(n, j + 2); ++y) ones += board[x][y] & 1; // Any live cell with two or three live neighbors lives on to the next // generation. if (board[i][j] == 1 && (ones == 3 || ones == 4)) board[i][j] |= 0b10; // Any dead cell with exactly three live neighbors becomes a live cell, // as if by reproduction. if (board[i][j] == 0 && ones == 3) board[i][j] |= 0b10; } for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) board[i][j] >>= 1; } }
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, j - 1); y < min(n, j + 2); ++y) ones += board[x][y] & 1; // Any live cell with two or three live neighbors lives on to the next // generation. if (board[i][j] == 1 && (ones == 3 || ones == 4)) board[i][j] |= 0b10; // Any dead cell with exactly three live neighbors becomes a live cell, // as if by reproduction. if (board[i][j] == 0 && ones == 3) board[i][j] |= 0b10; } for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) board[i][j] >>= 1; } };
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 between the two nodes `ai` and `bi` in the tree, you can choose any node of the tree as the root. When you select a node `x` as the root, the result tree has height `h`. Among all possible rooted trees, those with minimum height (i.e. `min(h)`) are called minimum height trees (MHTs). Return a list of all MHTs' root labels. You can return the answer in any order. The height of a rooted tree is the number of edges on the longest downward path between the root and a leaf.
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] ans = [] graph = collections.defaultdict(set) for u, v in edges: graph[u].add(v) graph[v].add(u) for label, children in graph.items(): if len(children) == 1: ans.append(label) while n > 2: n -= len(ans) nextLeaves = [] for leaf in ans: u = next(iter(graph[leaf])) graph[u].remove(leaf) if len(graph[u]) == 1: nextLeaves.append(u) ans = nextLeaves return ans
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<>()); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; graph.get(u).add(v); graph.get(v).add(u); } for (Map.Entry<Integer, Set<Integer>> entry : graph.entrySet()) { final int label = entry.getKey(); Set<Integer> children = entry.getValue(); if (children.size() == 1) ans.add(label); } while (n > 2) { n -= ans.size(); List<Integer> nextLeaves = new ArrayList<>(); for (final int leaf : ans) { final int u = (int) graph.get(leaf).iterator().next(); graph.get(u).remove(leaf); if (graph.get(u).size() == 1) nextLeaves.add(u); } ans = nextLeaves; } return ans; } }
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]; graph[u].insert(v); graph[v].insert(u); } for (const auto& [label, children] : graph) if (children.size() == 1) ans.push_back(label); while (n > 2) { n -= ans.size(); vector<int> nextLeaves; for (const int leaf : ans) { const int u = *graph[leaf].begin(); graph[u].erase(leaf); if (graph[u].size() == 1) nextLeaves.push_back(u); } ans = nextLeaves; } return ans; } };
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] + list(itertools.accumulate(nums)) self._mergeSort(prefix, 0, n, lower, upper) return self.ans def _mergeSort(self, prefix: List[int], l: int, r: int, lower: int, upper: int) -> None: if l >= r: return m = (l + r) // 2 self._mergeSort(prefix, l, m, lower, upper) self._mergeSort(prefix, m + 1, r, lower, upper) self._merge(prefix, l, m, r, lower, upper) def _merge(self, prefix: List[int], l: int, m: int, r: int, lower: int, upper: int) -> None: lo = m + 1 hi = m + 1 for i in range(l, m + 1): while lo <= r and prefix[lo] - prefix[i] < lower: lo += 1 while hi <= r and prefix[hi] - prefix[i] <= upper: hi += 1 self.ans += hi - lo sorted = [0] * (r - l + 1) k = 0 i = l j = m + 1 while i <= m and j <= r: if prefix[i] < prefix[j]: sorted[k] = prefix[i] k += 1 i += 1 else: sorted[k] = prefix[j] k += 1 j += 1 while i <= m: sorted[k] = prefix[i] k += 1 i += 1 while j <= r: sorted[k] = prefix[j] k += 1 j += 1 prefix[l:l + len(sorted)] = sorted
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; private void mergeSort(long[] prefix, int l, int r, int lower, int upper) { if (l >= r) return; final int m = (l + r) / 2; mergeSort(prefix, l, m, lower, upper); mergeSort(prefix, m + 1, r, lower, upper); merge(prefix, l, m, r, lower, upper); } private void merge(long[] prefix, int l, int m, int r, int lower, int upper) { int lo = m + 1; // the first index s.t. prefix[lo] - prefix[i] >= lower int hi = m + 1; // the first index s.t. prefix[hi] - prefix[i] > upper // For each index i in range [l, m], add hi - lo to `ans`. for (int i = l; i <= m; ++i) { while (lo <= r && prefix[lo] - prefix[i] < lower) ++lo; while (hi <= r && prefix[hi] - prefix[i] <= upper) ++hi; ans += hi - lo; } long[] sorted = new long[r - l + 1]; int k = 0; // sorted's index int i = l; // left's index int j = m + 1; // right's index while (i <= m && j <= r) if (prefix[i] < prefix[j]) sorted[k++] = prefix[i++]; else sorted[k++] = prefix[j++]; // Put the possible remaining left part into the sorted array. while (i <= m) sorted[k++] = prefix[i++]; // Put the possible remaining right part into the sorted array. while (j <= r) sorted[k++] = prefix[j++]; System.arraycopy(sorted, 0, prefix, l, sorted.length); } }
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; } private: void mergeSort(vector<long>& prefix, int l, int r, int lower, int upper, int& ans) { if (l >= r) return; const int m = (l + r) / 2; mergeSort(prefix, l, m, lower, upper, ans); mergeSort(prefix, m + 1, r, lower, upper, ans); merge(prefix, l, m, r, lower, upper, ans); } void merge(vector<long>& prefix, int l, int m, int r, int lower, int upper, int& ans) { int lo = m + 1; // the first index s.t. prefix[lo] - prefix[i] >= lower int hi = m + 1; // the first index s.t. prefix[hi] - prefix[i] > upper // For each index i in range [l, m], add hi - lo to `ans`. for (int i = l; i <= m; ++i) { while (lo <= r && prefix[lo] - prefix[i] < lower) ++lo; while (hi <= r && prefix[hi] - prefix[i] <= upper) ++hi; ans += hi - lo; } vector<long> sorted(r - l + 1); int k = 0; // sorted's index int i = l; // left's index int j = m + 1; // right's index while (i <= m && j <= r) if (prefix[i] < prefix[j]) sorted[k++] = prefix[i++]; else sorted[k++] = prefix[j++]; // Put the possible remaining left part into the sorted array. while (i <= m) sorted[k++] = prefix[i++]; // Put the possible remaining right part into the sorted array. while (j <= r) sorted[k++] = prefix[j++]; copy(sorted.begin(), sorted.end(), prefix.begin() + l); } };
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 counter-clockwise. Return `true` if your path crosses itself or `false` if it does not.
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)): if x[i - 2] <= x[i] and x[i - 1] <= x[i - 3]: return True if i >= 4 and x[i - 1] == x[i - 3] and x[i - 2] <= x[i] + x[i - 4]: return True if i >= 5 and x[i - 4] <= x[i - 2] and x[i - 2] <= x[i] + x[i - 4] and x[i - 1] <= x[i - 3] and x[i - 3] <= x[i - 1] + x[i - 5]: return True return False
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 (i >= 5 && x[i - 4] <= x[i - 2] && x[i - 2] <= x[i] + x[i - 4] && x[i - 1] <= x[i - 3] && x[i - 3] <= x[i - 1] + x[i - 5]) return true; } return false; } }
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; if (i >= 5 && x[i - 4] <= x[i - 2] && x[i - 2] <= x[i] + x[i - 4] && x[i - 1] <= x[i - 3] && x[i - 3] <= x[i - 1] + x[i - 5]) return true; } return false; } };
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 an algorithm with `O(sum of words[i].length)` runtime complexity.
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 enumerate(words)} for i, word in enumerate(words): if "" in dict and dict[""] != i and word == word[::-1]: ans.append([i, dict[""]]) for j in range(1, len(word) + 1): l = word[:j] r = word[j:] if l in dict and dict[l] != i and r == r[::-1]: ans.append([i, dict[l]]) if r in dict and dict[r] != i and l == l[::-1]: ans.append([dict[r], i]) return ans
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); for (int i = 0; i < words.length; ++i) { final String word = words[i]; // a special case to prevent duplicate calculation if (map.containsKey("") && map.get("") != i && isPalindrome(word)) ans.add(Arrays.asList(i, map.get(""))); for (int j = 1; j <= word.length(); ++j) { final String l = word.substring(0, j); final String r = word.substring(j); if (map.containsKey(l) && map.get(l) != i && isPalindrome(r)) ans.add(Arrays.asList(i, map.get(l))); if (map.containsKey(r) && map.get(r) != i && isPalindrome(l)) ans.add(Arrays.asList(map.get(r), i)); } } return ans; } private boolean isPalindrome(final String word) { int l = 0; int r = word.length() - 1; while (l < r) if (word.charAt(l++) != word.charAt(r--)) return false; return true; } }
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; } for (int i = 0; i < words.size(); ++i) { const string& word = words[i]; // a special case to prevent duplicate calculation if (const auto it = map.find(""); it != map.cend() && it->second != i && isPalindrome(word)) ans.push_back({i, it->second}); for (int j = 1; j <= word.length(); ++j) { const string& l = word.substr(0, j); const string& r = word.substr(j); if (const auto it = map.find(l); it != map.cend() && it->second != i && isPalindrome(r)) ans.push_back({i, it->second}); if (const auto it = map.find(r); it != map.cend() && it->second != i && isPalindrome(l)) ans.push_back({it->second, i}); } } return ans; } private: bool isPalindrome(const string& word) { int l = 0; int r = word.length() - 1; while (l < r) if (word[l++] != word[r--]) return false; return true; } };
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 x2 = -math.inf y2 = -math.inf corners: Set[Tuple[int, int]] = set() for x, y, a, b in rectangles: area += (a - x) * (b - y) x1 = min(x1, x) y1 = min(y1, y) x2 = max(x2, a) y2 = max(y2, b) for point in [(x, y), (x, b), (a, y), (a, b)]: if point in corners: corners.remove(point) else: corners.add(point) if len(corners) != 4: return False if (x1, y1) not in corners or (x1, y2) not in corners or (x2, y1) not in corners or (x2, y2) not in corners: return False return area == (x2 - x1) * (y2 - y1)
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[0]) * (r[3] - r[1]); x1 = Math.min(x1, r[0]); y1 = Math.min(y1, r[1]); x2 = Math.max(x2, r[2]); y2 = Math.max(y2, r[3]); // the four points of the current rectangle String[] points = new String[] {r[0] + " " + r[1], // r[0] + " " + r[3], // r[2] + " " + r[1], // r[2] + " " + r[3]}; for (final String point : points) if (!corners.add(point)) corners.remove(point); } if (corners.size() != 4) return false; if (!corners.contains(x1 + " " + y1) || // !corners.contains(x1 + " " + y2) || // !corners.contains(x2 + " " + y1) || // !corners.contains(x2 + " " + y2)) return false; return area == (x2 - x1) * (y2 - y1); } }
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]); x1 = min(x1, r[0]); y1 = min(y1, r[1]); x2 = max(x2, r[2]); y2 = max(y2, r[3]); // the four points of the current rectangle const vector<string> points{to_string(r[0]) + " " + to_string(r[1]), to_string(r[0]) + " " + to_string(r[3]), to_string(r[2]) + " " + to_string(r[1]), to_string(r[2]) + " " + to_string(r[3])}; for (const string& point : points) if (!corners.insert(point).second) corners.erase(point); } if (corners.size() != 4) return false; if (!corners.contains(to_string(x1) + " " + to_string(y1)) || !corners.contains(to_string(x1) + " " + to_string(y2)) || !corners.contains(to_string(x2) + " " + to_string(y1)) || !corners.contains(to_string(x2) + " " + to_string(y2))) return false; return area == (x2 - x1) * (y2 - y1); } };
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 = [] for i, digit in enumerate(num): while k > 0 and stack and stack[-1] > digit: stack.pop() k -= 1 stack.append(digit) for _ in range(k): stack.pop() for c in stack: if c == '0' and not ans: continue ans.append(c) return ''.join(ans) if ans else '0'
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() > num.charAt(i)) { stack.pollLast(); --k; } stack.addLast(num.charAt(i)); } while (k-- > 0) stack.pollLast(); for (final char c : stack) { if (c == '0' && sb.length() == 0) continue; sb.append(c); } return sb.length() == 0 ? "0" : sb.toString(); } }
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; } stack.push_back(num[i]); } while (k-- > 0) stack.pop_back(); for (const char c : stack) { if (c == '0' && ans.empty()) continue; ans += c; } return ans.empty() ? "0" : ans; } };
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(heightMap) n = len(heightMap[0]) ans = 0 minHeap = [] seen = set() for i in range(m): heapq.heappush(minHeap, (heightMap[i][0], i, 0)) heapq.heappush(minHeap, (heightMap[i][n - 1], i, n - 1)) seen.add((i, 0)) seen.add((i, n - 1)) for j in range(1, n - 1): heapq.heappush(minHeap, (heightMap[0][j], 0, j)) heapq.heappush(minHeap, (heightMap[m - 1][j], m - 1, j)) seen.add((0, j)) seen.add((m - 1, j)) while minHeap: h, i, j = heapq.heappop(minHeap) for dx, dy in dirs: x = i + dx y = j + dy if x < 0 or x == m or y < 0 or y == n: continue if (x, y) in seen: continue if heightMap[x][y] < h: ans += h - heightMap[x][y] heapq.heappush(minHeap, (h, x, y)) else: heapq.heappush(minHeap, (heightMap[x][y], x, y)) seen.add((x, y)) return ans
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; Queue<T> minHeap = new PriorityQueue<>(Comparator.comparingInt(T::h)); boolean[][] seen = new boolean[m][n]; for (int i = 0; i < m; ++i) { minHeap.offer(new T(i, 0, heightMap[i][0])); minHeap.offer(new T(i, n - 1, heightMap[i][n - 1])); seen[i][0] = true; seen[i][n - 1] = true; } for (int j = 1; j < n - 1; ++j) { minHeap.offer(new T(0, j, heightMap[0][j])); minHeap.offer(new T(m - 1, j, heightMap[m - 1][j])); seen[0][j] = true; seen[m - 1][j] = true; } while (!minHeap.isEmpty()) { final int i = minHeap.peek().i; final int j = minHeap.peek().j; final int h = minHeap.poll().h; for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == m || y < 0 || y == n) continue; if (seen[x][y]) continue; if (heightMap[x][y] < h) { ans += h - heightMap[x][y]; minHeap.offer(new T(x, y, h)); // Fill water in grid[x][y]. } else { minHeap.offer(new T(x, y, heightMap[x][y])); } seen[x][y] = true; } } return ans; } }
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 = heightMap.size(); const int n = heightMap[0].size(); int ans = 0; auto compare = [](const T& a, const T& b) { return a.h > b.h; }; priority_queue<T, vector<T>, decltype(compare)> minHeap(compare); vector<vector<bool>> seen(m, vector<bool>(n)); for (int i = 0; i < m; ++i) { minHeap.emplace(i, 0, heightMap[i][0]); minHeap.emplace(i, n - 1, heightMap[i][n - 1]); seen[i][0] = true; seen[i][n - 1] = true; } for (int j = 1; j < n - 1; ++j) { minHeap.emplace(0, j, heightMap[0][j]); minHeap.emplace(m - 1, j, heightMap[m - 1][j]); seen[0][j] = true; seen[m - 1][j] = true; } while (!minHeap.empty()) { const auto [i, j, h] = minHeap.top(); minHeap.pop(); for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == m || y < 0 || y == n) continue; if (seen[x][y]) continue; if (heightMap[x][y] < h) { ans += h - heightMap[x][y]; minHeap.emplace(x, y, h); // Fill water in grid[x][y]. } else { minHeap.emplace(x, y, heightMap[x][y]); } seen[x][y] = true; } } return ans; } };
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 `heights` where `heights[r][c]` represents the height above sea level of the cell at coordinate `(r, c)`. The island receives a lot of rain, and the rain water can flow to neighboring cells directly north, south, east, and west if the neighboring cell's height is less than or equal to the current cell's height. Water can flow from any cell adjacent to an ocean into the ocean. Return a 2D list of grid coordinates `result` where `result[i] = [ri, ci]` denotes that rain water can flow from cell `(ri, ci)` to both the Pacific and Atlantic oceans.
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 = len(heights) n = len(heights[0]) qP = collections.deque() qA = collections.deque() seenP = [[False] * n for _ in range(m)] seenA = [[False] * n for _ in range(m)] for i in range(m): qP.append((i, 0)) qA.append((i, n - 1)) seenP[i][0] = True seenA[i][n - 1] = True for j in range(n): qP.append((0, j)) qA.append((m - 1, j)) seenP[0][j] = True seenA[m - 1][j] = True def bfs(q: collections.deque, seen: List[List[bool]]): while q: i, j = q.popleft() h = heights[i][j] for dx, dy in dirs: x = i + dx y = j + dy if x < 0 or x == m or y < 0 or y == n: continue if seen[x][y] or heights[x][y] < h: continue q.append((x, y)) seen[x][y] = True bfs(qP, seenP) bfs(qA, seenA) res=[] for i in range(m): for j in range(n): if seenP[i][j] and seenA[i][j]: res.append([i, j]) return res
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<>(); boolean[][] seenP = new boolean[m][n]; boolean[][] seenA = new boolean[m][n]; for (int i = 0; i < m; ++i) { qP.offer(new Pair<>(i, 0)); qA.offer(new Pair<>(i, n - 1)); seenP[i][0] = true; seenA[i][n - 1] = true; } for (int j = 0; j < n; ++j) { qP.offer(new Pair<>(0, j)); qA.offer(new Pair<>(m - 1, j)); seenP[0][j] = true; seenA[m - 1][j] = true; } bfs(heights, qP, seenP); bfs(heights, qA, seenA); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (seenP[i][j] && seenA[i][j]) ans.add(new ArrayList<>(List.of(i, j))); return ans; } private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; private void bfs(int[][] heights, Queue<Pair<Integer, Integer>> q, boolean[][] seen) { while (!q.isEmpty()) { final int i = q.peek().getKey(); final int j = q.poll().getValue(); final int h = heights[i][j]; for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == heights.length || y < 0 || y == heights[0].length) continue; if (seen[x][y] || heights[x][y] < h) continue; q.offer(new Pair<>(x, y)); seen[x][y] = true; } } } }
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>> qA; vector<vector<bool>> seenP(m, vector<bool>(n)); vector<vector<bool>> seenA(m, vector<bool>(n)); auto bfs = [&](queue<pair<int, int>>& q, vector<vector<bool>>& seen) { while (!q.empty()) { const auto [i, j] = q.front(); q.pop(); const int h = heights[i][j]; for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == m || y < 0 || y == n) continue; if (seen[x][y] || heights[x][y] < h) continue; q.emplace(x, y); seen[x][y] = true; } } }; for (int i = 0; i < m; ++i) { qP.emplace(i, 0); qA.emplace(i, n - 1); seenP[i][0] = true; seenA[i][n - 1] = true; } for (int j = 0; j < n; ++j) { qP.emplace(0, j); qA.emplace(m - 1, j); seenP[0][j] = true; seenA[m - 1][j] = true; } bfs(qP, seenP); bfs(qA, seenA); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (seenP[i][j] && seenA[i][j]) ans.push_back({i, j}); return ans; } };
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, but `"Baaba0"` is strong). Given a string `password`, return the minimum number of steps required to make `password` strong. if `password` is already strong, return `0`. In one step, you can: * Insert one character to `password`, * Delete one character from `password`, or * Replace one character of `password` with another 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 strongPasswordChecker(self, password: str) -> int: n = len(password) missing = self._getMissing(password) replaces = 0 oneSeq = 0 twoSeq = 0 i = 2 while i < n: if password[i] == password[i - 1] and password[i - 1] == password[i - 2]: length = 2 while i < n and password[i] == password[i - 1]: length += 1 i += 1 replaces += length // 3 if length % 3 == 0: oneSeq += 1 if length % 3 == 1: twoSeq += 1 else: i += 1 if n < 6: return max(6 - n, missing) if n <= 20: return max(replaces, missing) deletes = n - 20 replaces -= min(oneSeq, deletes) replaces -= min(max(deletes - oneSeq, 0), twoSeq * 2) // 2 replaces -= max(deletes - oneSeq - twoSeq * 2, 0) // 3 return deletes + max(replaces, missing) def _getMissing(self, password: str) -> int: return 3 - any(c.isupper() for c in password) - any(c.islower() for c in password) - any(c.isdigit() for c in password)
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, (3k)-seqs int oneSeq = 0; // the number of sequences that can be substituted with 2 deletions, (3k + 1)-seqs int twoSeq = 0; for (int i = 2; i < n;) if (password.charAt(i) == password.charAt(i - 1) && password.charAt(i - 1) == password.charAt(i - 2)) { int length = 2; // the length of the repeating password while (i < n && password.charAt(i) == password.charAt(i - 1)) { ++length; ++i; } replaces += length / 3; // 'aaaaaaa' -> 'aaxaaxa' if (length % 3 == 0) ++oneSeq; if (length % 3 == 1) ++twoSeq; } else { ++i; } if (n < 6) return Math.max(6 - n, missing); if (n <= 20) return Math.max(replaces, missing); final int deletes = n - 20; // Each replacement in (3k)-seqs can be substituted with 1 deletions. replaces -= Math.min(oneSeq, deletes); // Each replacement in (3k + 1)-seqs can be substituted with 2 deletions. replaces -= Math.min(Math.max(deletes - oneSeq, 0), twoSeq * 2) / 2; // Each replacement in other seqs can be substituted with 3 deletions. replaces -= Math.max(deletes - oneSeq - twoSeq * 2, 0) / 3; return deletes + Math.max(replaces, missing); } private int getMissing(final String password) { return 3 - // (password.chars().anyMatch(Character::isUpperCase) ? 1 : 0) - (password.chars().anyMatch(Character::isLowerCase) ? 1 : 0) - (password.chars().anyMatch(Character::isDigit) ? 1 : 0); } }
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, // (3k)-seqs int oneSeq = 0; // the number of sequences that can be substituted with 2 deletions, // (3k + 1)-seqs int twoSeq = 0; for (int i = 2; i < n;) if (password[i] == password[i - 1] && password[i - 1] == password[i - 2]) { int length = 2; // the length of the repeating password while (i < n && password[i] == password[i - 1]) { ++length; ++i; } replaces += length / 3; // 'aaaaaaa' -> 'aaxaaxa' if (length % 3 == 0) ++oneSeq; if (length % 3 == 1) ++twoSeq; } else { ++i; } if (n < 6) return max(6 - n, missing); if (n <= 20) return max(replaces, missing); const int deletes = n - 20; // Each replacement in (3k)-seqs can be substituted with 1 deletions. replaces -= min(oneSeq, deletes); // Each replacement in (3k + 1)-seqs can be substituted with 2 deletions. replaces -= min(max(deletes - oneSeq, 0), twoSeq * 2) / 2; // Each replacement in other seqs can be substituted with 3 deletions. replaces -= max(deletes - oneSeq - twoSeq * 2, 0) / 3; return deletes + max(replaces, missing); } private: int getMissing(const string& password) { return 3 - // ranges::any_of(password, [](char c) { return isupper(c); }) - ranges::any_of(password, [](char c) { return islower(c); }) - ranges::any_of(password, [](char c) { return isdigit(c); }); } };
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 if c == 'o': count[1] += 1 if c == 'w': count[2] += 1 if c == 'h': count[3] += 1 if c == 'u': count[4] += 1 if c == 'f': count[5] += 1 if c == 'x': count[6] += 1 if c == 's': count[7] += 1 if c == 'g': count[8] += 1 if c == 'i': count[9] += 1 count[1] -= count[0] + count[2] + count[4] count[3] -= count[8] count[5] -= count[4] count[7] -= count[6] count[9] -= count[5] + count[6] + count[8] return ''.join(chr(i + ord('0')) for i, c in enumerate(count) for j in range(c))
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') ++count[3]; if (c == 'u') ++count[4]; if (c == 'f') ++count[5]; if (c == 'x') ++count[6]; if (c == 's') ++count[7]; if (c == 'g') ++count[8]; if (c == 'i') ++count[9]; } count[1] -= count[0] + count[2] + count[4]; count[3] -= count[8]; count[5] -= count[4]; count[7] -= count[6]; count[9] -= count[5] + count[6] + count[8]; for (int i = 0; i < 10; ++i) for (int j = 0; j < count[i]; ++j) sb.append(i); return sb.toString(); } }
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') ++count[4]; if (c == 'f') ++count[5]; if (c == 'x') ++count[6]; if (c == 's') ++count[7]; if (c == 'g') ++count[8]; if (c == 'i') ++count[9]; } count[1] -= count[0] + count[2] + count[4]; count[3] -= count[8]; count[5] -= count[4]; count[7] -= count[6]; count[9] -= count[5] + count[6] + count[8]; for (int i = 0; i < 10; ++i) for (int j = 0; j < count[i]; ++j) ans += i + '0'; return ans; } };
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 array is circular, you may assume that moving forward from the last element puts you on the first element, and moving backwards from the first element puts you on the last element. A cycle in the array consists of a sequence of indices `seq` of length `k` where: * Following the movement rules above results in the repeating index sequence `seq[0] -> seq[1] -> ... -> seq[k - 1] -> seq[0] -> ...` * Every `nums[seq[j]]` is either all positive or all negative. * `k > 1` Return `true` if there is a cycle in `nums`, or `false` otherwise.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def circularArrayLoop(self, nums: List[int]) -> bool: def advance(i: int) -> int: return (i + nums[i]) % len(nums) if len(nums) < 2: return False for i, num in enumerate(nums): if num == 0: continue slow = i fast = advance(slow) while num * nums[fast] > 0 and num * nums[advance(fast)] > 0: if slow == fast: if slow == advance(slow): break return True slow = advance(slow) fast = advance(advance(fast)) slow = i sign = num while sign * nums[slow] > 0: next = advance(slow) nums[slow] = 0 slow = next return False
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(nums, fast)] > 0) { if (slow == fast) { if (slow == advance(nums, slow)) break; return true; } slow = advance(nums, slow); fast = advance(nums, advance(nums, fast)); } slow = i; final int sign = nums[i]; while (sign * nums[slow] > 0) { final int next = advance(nums, slow); nums[slow] = 0; slow = next; } } return false; } private int advance(int[] nums, int i) { final int n = nums.length; final int val = (i + nums[i]) % n; return i + nums[i] >= 0 ? val : n + val; } }
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] == 0) continue; int slow = i; int fast = advance(slow); while (nums[i] * nums[fast] > 0 && nums[i] * nums[advance(fast)] > 0) { if (slow == fast) { if (slow == advance(slow)) break; return true; } slow = advance(slow); fast = advance(advance(fast)); } slow = i; const int sign = nums[i]; while (sign * nums[slow] > 0) { const int next = advance(slow); nums[slow] = 0; slow = next; } } return false; } };
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 string.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def findLongestWord(self, s: str, d: List[str]) -> str: ans = '' for word in d: i = 0 for c in s: if i < len(word) and c == word[i]: i += 1 if i == len(word): if len(word) > len(ans) or len(word) == len(ans) and word < ans: ans = word return ans
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; } // Returns true if a is a subsequence of b. private boolean isSubsequence(final String a, final String b) { int i = 0; for (final char c : b.toCharArray()) if (i < a.length() && c == a.charAt(i)) ++i; return i == a.length(); } }
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; } private: // Returns true if a is a subsequence of b. bool isSubsequence(const string& a, const string& b) { int i = 0; for (const char c : b) if (i < a.length() && c == a[i]) ++i; return i == a.length(); }; };
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(mat) n = len(mat[0]) q = collections.deque() seen = [[False] * n for _ in range(m)] for i in range(m): for j in range(n): if mat[i][j] == 0: q.append((i, j)) seen[i][j] = True while q: i, j = q.popleft() for dx, dy in dirs: x = i + dx y = j + dy if x < 0 or x == m or y < 0 or y == n: continue if seen[x][y]: continue mat[x][y] = mat[i][j] + 1 q.append((x, y)) seen[x][y] = True return mat
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) for (int j = 0; j < n; ++j) if (mat[i][j] == 0) { q.offer(new Pair<>(i, j)); seen[i][j] = true; } while (!q.isEmpty()) { final int i = q.peek().getKey(); final int j = q.poll().getValue(); for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == m || y < 0 || y == n) continue; if (seen[x][y]) continue; mat[x][y] = mat[i][j] + 1; q.offer(new Pair<>(x, y)); seen[x][y] = true; } } return mat; } }
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; i < m; ++i) for (int j = 0; j < n; ++j) if (mat[i][j] == 0) { q.emplace(i, j); seen[i][j] = true; } while (!q.empty()) { const auto [i, j] = q.front(); q.pop(); for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == m || y < 0 || y == n) continue; if (seen[x][y]) continue; mat[x][y] = mat[i][j] + 1; q.emplace(x, y); seen[x][y] = true; } } return mat; } };
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 the group. You are given an `n x n` matrix `isConnected` where `isConnected[i][j] = 1` if the `ith` city and the `jth` city are directly connected, and `isConnected[i][j] = 0` otherwise. Return the total number of provinces.
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, u: int, v: int) -> None: i = self._find(u) j = self._find(v) if i == j: return if self.rank[i] < self.rank[j]: self.id[i] = j elif self.rank[i] > self.rank[j]: self.id[j] = i else: self.id[i] = j self.rank[j] += 1 self.count -= 1 def _find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self._find(self.id[u]) return self.id[u] class Solution: def findCircleNum(self, isConnected: List[List[int]]) -> int: n = len(isConnected) uf = UnionFind(n) for i in range(n): for j in range(i, n): if isConnected[i][j] == 1: uf.unionByRank(i, j) return uf.count
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]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } --count; } public int getCount() { return count; } private int count; private int[] id; private int[] rank; private int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } } class Solution { public int findCircleNum(int[][] isConnected) { final int n = isConnected.length; UnionFind uf = new UnionFind(n); for (int i = 0; i < n; ++i) for (int j = i; j < n; ++j) if (isConnected[i][j] == 1) uf.unionByRank(i, j); return uf.getCount(); } }
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]) { id[j] = i; } else { id[i] = j; ++rank[j]; } --count; } int getCount() const { return count; } private: int count; vector<int> id; vector<int> rank; int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } }; class Solution { public: int findCircleNum(vector<vector<int>>& isConnected) { const int n = isConnected.size(); UnionFind uf(n); for (int i = 0; i < n; ++i) for (int j = i; j < n; ++j) if (isConnected[i][j] == 1) uf.unionByRank(i, j); return uf.getCount(); } };
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 in range(1, len(nums)): if nums[i] < nums[i - 1]: flag = True if flag: mini = min(mini, nums[i]) flag = False for i in reversed(range(len(nums) - 1)): if nums[i] > nums[i + 1]: flag = True if flag: maxi = max(maxi, nums[i]) for l in range(len(nums)): if nums[l] > mini: break for r, num in reversed(list(enumerate(nums))): if num < maxi: break return 0 if l >= r else r - l + 1
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 = true; if (meetDecrease) mn = Math.min(mn, nums[i]); } for (int i = n - 2; i >= 0; --i) { if (nums[i] > nums[i + 1]) meetIncrease = true; if (meetIncrease) mx = Math.max(mx, nums[i]); } int l = 0; for (l = 0; l < n; ++l) if (nums[l] > mn) break; int r = 0; for (r = n - 1; r >= 0; --r) if (nums[r] < mx) break; return l > r ? 0 : r - l + 1; } }
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 (meetDecrease) mn = min(mn, nums[i]); } for (int i = n - 2; i >= 0; --i) { if (nums[i] > nums[i + 1]) meetIncrease = true; if (meetIncrease) mx = max(mx, nums[i]); } int l; for (l = 0; l < n; ++l) if (nums[l] > mn) break; int r; for (r = n - 1; r >= 0; --r) if (nums[r] < mx) break; return l < r ? r - l + 1 : 0; } };
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 following format : `<TAG_NAME>TAG_CONTENT</TAG_NAME>`. Among them, `<TAG_NAME>` is the start tag, and `</TAG_NAME>` is the end tag. The TAG_NAME in start and end tags should be the same. A closed tag is valid if and only if the TAG_NAME and TAG_CONTENT are valid. 3. A valid `TAG_NAME` only contain upper-case letters, and has length in range [1,9]. Otherwise, the `TAG_NAME` is invalid. 4. A valid `TAG_CONTENT` may contain other valid closed tags, cdata and any characters (see note1) EXCEPT unmatched `<`, unmatched start and end tag, and unmatched or closed tags with invalid TAG_NAME. Otherwise, the `TAG_CONTENT` is invalid. 5. A start tag is unmatched if no end tag exists with the same TAG_NAME, and vice versa. However, you also need to consider the issue of unbalanced when tags are nested. 6. A `<` is unmatched if you cannot find a subsequent `>`. And when you find a `<` or `</`, all the subsequent characters until the next `>` should be parsed as TAG_NAME (not necessarily valid). 7. The cdata has the following format : `<![CDATA[CDATA_CONTENT]]>`. The range of `CDATA_CONTENT` is defined as the characters between `<![CDATA[` and the first subsequent `]]>`. 8. `CDATA_CONTENT` may contain any characters. The function of cdata is to forbid the validator to parse `CDATA_CONTENT`, so even it has some characters that can be parsed as tag (no matter valid or invalid), you should treat it as regular characters.
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 stack = [] def isValidCdata(s: str) -> bool: return s.find('[CDATA[') == 0 def isValidTagName(tagName: str, isEndTag: bool) -> bool: nonlocal containsTag if not tagName or len(tagName) > 9: return False if any(not c.isupper() for c in tagName): return False if isEndTag: return stack and stack.pop() == tagName containsTag = True stack.append(tagName) return True i = 0 while i < len(code): if not stack and containsTag: return False if code[i] == '<': if stack and code[i + 1] == '!': closeIndex = code.find(']]>', i + 2) if closeIndex == -1 or not isValidCdata(code[i + 2:closeIndex]): return False elif code[i + 1] == '/': closeIndex = code.find('>', i + 2) if closeIndex == -1 or not isValidTagName(code[i + 2:closeIndex], True): return False else: closeIndex = code.find('>', i + 1) if closeIndex == -1 or not isValidTagName(code[i + 1:closeIndex], False): return False i = closeIndex i += 1 return not stack and containsTag
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) return false; if (code.charAt(i) == '<') { // It's inside a tag, so check if it's a cdata. if (!stack.isEmpty() && code.charAt(i + 1) == '!') { closeIndex = code.indexOf("]]>", i + 2); if (closeIndex < 0 || !isValidCdata(code.substring(i + 2, closeIndex))) return false; } else if (code.charAt(i + 1) == '/') { // the end tag closeIndex = code.indexOf('>', i + 2); if (closeIndex < 0 || !isValidTagName(stack, code.substring(i + 2, closeIndex), true)) return false; } else { // the start tag closeIndex = code.indexOf('>', i + 1); if (closeIndex < 0 || !isValidTagName(stack, code.substring(i + 1, closeIndex), false)) return false; } i = closeIndex; } } return stack.isEmpty() && containsTag; } private boolean containsTag = false; private boolean isValidCdata(final String s) { return s.indexOf("[CDATA[") == 0; } private boolean isValidTagName(Deque<String> stack, String tagName, boolean isEndTag) { if (tagName.isEmpty() || tagName.length() > 9) return false; for (final char c : tagName.toCharArray()) if (!Character.isUpperCase(c)) return false; if (isEndTag) return !stack.isEmpty() && stack.pop().equals(tagName); containsTag = true; stack.push(tagName); return true; } }
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] == '<') { // It's inside a tag, so check if it's a cdata. if (!stack.empty() && code[i + 1] == '!') { closeIndex = code.find("]]>", i + 2); if (closeIndex == string::npos || !isValidCdata(code.substr(i + 2, closeIndex - i - 2))) return false; } else if (code[i + 1] == '/') { // the end tag closeIndex = code.find('>', i + 2); if (closeIndex == string::npos || !isValidTagName(stack, code.substr(i + 2, closeIndex - i - 2), true)) return false; } else { // the start tag closeIndex = code.find('>', i + 1); if (closeIndex == string::npos || !isValidTagName(stack, code.substr(i + 1, closeIndex - i - 1), false)) return false; } i = closeIndex; } } return stack.empty() && containsTag; } private: bool containsTag = false; bool isValidCdata(const string& s) { return s.find("[CDATA[") == 0; } bool isValidTagName(stack<string>& stack, const string& tagName, bool isEndTag) { if (tagName.empty() || tagName.length() > 9) return false; for (const char c : tagName) if (!isupper(c)) return false; if (isEndTag) { if (stack.empty()) return false; if (stack.top() != tagName) return false; stack.pop(); return true; } containsTag = true; stack.push(tagName); return true; } };
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 `sentence` consisting of words separated by spaces, replace all the successors in the sentence with the root forming it. If a successor can be replaced by more than one root, replace it with the root that has the shortest length. Return the `sentence` after the replacement.
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: if c not in node: node[c] = {} node = node[c] node['word'] = word def search(self, word: str) -> str: node = self.root for c in word: if 'word' in node: return node['word'] if c not in node: return word node = node[c] return word def replaceWords(self, dictionary: List[str], sentence: str) -> str: for word in dictionary: self.insert(word) words = sentence.split(' ') return ' '.join([self.search(word) for word in words])
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(" "); for (final String word : words) sb.append(' ').append(search(word)); return sb.substring(1).toString(); } private TrieNode root = new TrieNode(); private void insert(final String word) { TrieNode node = root; for (char c : word.toCharArray()) { final int i = c - 'a'; if (node.children[i] == null) node.children[i] = new TrieNode(); node = node.children[i]; } node.word = word; } private String search(final String word) { TrieNode node = root; for (char c : word.toCharArray()) { if (node.word != null) return node.word; final int i = c - 'a'; if (node.children[i] == null) return word; node = node.children[i]; } return word; } }
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 iss(sentence); for (string s; iss >> s;) ans += search(s) + ' '; ans.pop_back(); return ans; } private: shared_ptr<TrieNode> root = make_shared<TrieNode>(); void insert(const string& word) { shared_ptr<TrieNode> node = root; for (const char c : word) { const int i = c - 'a'; if (node->children[i] == nullptr) node->children[i] = make_shared<TrieNode>(); node = node->children[i]; } node->word = &word; } string search(const string& word) { shared_ptr<TrieNode> node = root; for (const char c : word) { if (node->word) return *node->word; const int i = c - 'a'; if (node->children[i] == nullptr) return word; node = node->children[i]; } return word; } };
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] * len(nums) for i, num in enumerate(nums): for j in range(i): if nums[j] < num: if length[i] < length[j] + 1: length[i] = length[j] + 1 count[i] = count[j] elif length[i] == length[j] + 1: count[i] += count[j] for i, l in enumerate(length): if l > maxLength: maxLength = l ans = count[i] elif l == maxLength: ans += count[i] return ans
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.fill(length, 1); Arrays.fill(count, 1); // Calculate the `length` and `count` arrays. for (int i = 0; i < n; ++i) for (int j = 0; j < i; ++j) if (nums[j] < nums[i]) if (length[i] < length[j] + 1) { length[i] = length[j] + 1; count[i] = count[j]; } else if (length[i] == length[j] + 1) { count[i] += count[j]; } // Get the number of LIS. for (int i = 0; i < n; ++i) if (length[i] > maxLength) { maxLength = length[i]; ans = count[i]; } else if (length[i] == maxLength) { ans += count[i]; } return ans; } }
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); // Calculate `length` and `count` arrays. for (int i = 0; i < n; ++i) for (int j = 0; j < i; ++j) if (nums[j] < nums[i]) if (length[i] < length[j] + 1) { length[i] = length[j] + 1; count[i] = count[j]; } else if (length[i] == length[j] + 1) { count[i] += count[j]; } // Get the number of LIS. for (int i = 0; i < n; ++i) if (length[i] > maxLength) { maxLength = length[i]; ans = count[i]; } else if (length[i] == maxLength) { ans += count[i]; } return ans; } };
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 is represented as an array `edges` of length `n` where `edges[i] = [ai, bi]` indicates that there is an edge between nodes `ai` and `bi` in the graph. Return an edge that can be removed so that the resulting graph is a tree of `n` nodes. If there are multiple answers, return the answer that occurs last in the input.
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) -> bool: i = self._find(u) j = self._find(v) if i == j: return False if self.rank[i] < self.rank[j]: self.id[i] = j elif self.rank[i] > self.rank[j]: self.id[j] = i else: self.id[i] = j self.rank[j] += 1 return True def _find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self._find(self.id[u]) return self.id[u] class Solution: def findRedundantConnection(self, edges: List[List[int]]) -> List[int]: uf = UnionFind(len(edges) + 1) for edge in edges: u, v = edge if not uf.unionByRank(u, v): return edge
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] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } return true; } private int[] id; private int[] rank; private int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } } class Solution { public int[] findRedundantConnection(int[][] edges) { UnionFind uf = new UnionFind(edges.length + 1); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; if (!uf.unionByRank(u, v)) return edge; } throw new IllegalArgumentException(); } }
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[j] = i; } else { id[i] = j; ++rank[j]; } return true; } private: vector<int> id; vector<int> rank; int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } }; class Solution { public: vector<int> findRedundantConnection(vector<vector<int>>& edges) { UnionFind uf(edges.size() + 1); for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; if (!uf.unionByRank(u, v)) return edge; } throw; } };
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` nodes (with distinct values from `1` to `n`), with one additional directed edge added. The added edge has two different vertices chosen from `1` to `n`, and was not an edge that already existed. The resulting graph is given as a 2D-array of `edges`. Each element of `edges` is a pair `[ui, vi]` that represents a directed edge connecting nodes `ui` and `vi`, where `ui` is a parent of child `vi`. Return an edge that can be removed so that the resulting graph is a rooted tree of `n` nodes. If there are multiple answers, return the answer that occurs last in the given 2D-array.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class UnionFind: def __init__(self, n: int): self.id = list(range(n)) self.rank = [0] * n def unionByRank(self, u: int, v: int) -> bool: i = self._find(u) j = self._find(v) if i == j: return False if self.rank[i] < self.rank[j]: self.id[i] = j elif self.rank[i] > self.rank[j]: self.id[j] = i else: self.id[i] = j self.rank[j] += 1 return True def _find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self._find(self.id[u]) return self.id[u] class Solution: def findRedundantDirectedConnection(self, edges: List[List[int]]) -> List[int]: ids = [0] * (len(edges) + 1) nodeWithTwoParents = 0 for _, v in edges: ids[v] += 1 if ids[v] == 2: nodeWithTwoParents = v def findRedundantDirectedConnection(skippedEdgeIndex: int) -> List[int]: uf = UnionFind(len(edges) + 1) for i, edge in enumerate(edges): if i == skippedEdgeIndex: continue if not uf.unionByRank(edge[0], edge[1]): return edge return [] if nodeWithTwoParents == 0: return findRedundantDirectedConnection(-1) for i in reversed(range(len(edges))): _, v = edges[i] if v == nodeWithTwoParents: if not findRedundantDirectedConnection(i): return edges[i]
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] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } return true; } private int[] id; private int[] rank; private int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } } class Solution { public int[] findRedundantDirectedConnection(int[][] edges) { int[] ids = new int[edges.length + 1]; int nodeWithTwoParents = 0; for (int[] edge : edges) { final int v = edge[1]; if (++ids[v] == 2) { nodeWithTwoParents = v; break; } } // If there is no edge with two ids, don't skip any edge. if (nodeWithTwoParents == 0) return findRedundantDirectedConnection(edges, -1); for (int i = edges.length - 1; i >= 0; --i) if (edges[i][1] == nodeWithTwoParents) // Try to delete the edges[i]. if (findRedundantDirectedConnection(edges, i).length == 0) return edges[i]; throw new IllegalArgumentException(); } private int[] findRedundantDirectedConnection(int[][] edges, int skippedEdgeIndex) { UnionFind uf = new UnionFind(edges.length + 1); for (int i = 0; i < edges.length; ++i) { if (i == skippedEdgeIndex) continue; if (!uf.unionByRank(edges[i][0], edges[i][1])) return edges[i]; } return new int[] {}; } }
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[j] = i; } else { id[i] = j; ++rank[j]; } return true; } private: vector<int> id; vector<int> rank; int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } }; class Solution { public: vector<int> findRedundantDirectedConnection(vector<vector<int>>& edges) { vector<int> ids(edges.size() + 1); int nodeWithTwoParents = 0; for (const vector<int>& edge : edges) { const int v = edge[1]; if (++ids[v] == 2) { nodeWithTwoParents = v; break; } } // If there is no edge with two ids, don't skip any edge. if (nodeWithTwoParents == 0) return findRedundantDirectedConnection(edges, -1); for (int i = edges.size() - 1; i >= 0; --i) if (edges[i][1] == nodeWithTwoParents) // Try to delete the edges[i]. if (findRedundantDirectedConnection(edges, i).empty()) return edges[i]; throw; } vector<int> findRedundantDirectedConnection(const vector<vector<int>>& edges, int skippedEdgeIndex) { UnionFind uf(edges.size() + 1); for (int i = 0; i < edges.size(); ++i) { if (i == skippedEdgeIndex) continue; if (!uf.unionByRank(edges[i][0], edges[i][1])) return edges[i]; } return {}; } };
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 cells in a cardinal direction, then one cell in an orthogonal direction. Each time the knight is to move, it chooses one of eight possible moves uniformly at random (even if the piece would go off the chessboard) and moves there. The knight continues moving until it has made exactly `k` moves or has moved off the chessboard. Return the probability that the knight remains on the board after it has stopped moving.
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), (-1, -2), (-2, -1), (-2, 1), (-1, 2)) dp = [[0] * n for _ in range(n)] dp[row][column] = 1.0 for _ in range(k): newDp = [[0] * n for _ in range(n)] for i in range(n): for j in range(n): for dx, dy in dirs: x = i + dx y = j + dy if 0 <= x < n and 0 <= y < n: newDp[i][j] += dp[x][y] dp = newDp return sum(map(sum, dp)) / 8**k
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][column] = 1.0; for (int move = 0; move < k; ++move) { double[][] newDp = new double[n][n]; for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) if (dp[i][j] > 0.0) { for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x >= n || y < 0 || y >= n) continue; newDp[x][y] += dp[i][j] * PROB; } } dp = newDp; } return Arrays.stream(dp).flatMapToDouble(Arrays::stream).sum(); } }
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, j) vector<vector<double>> dp(n, vector<double>(n)); dp[row][column] = 1.0; for (int move = 0; move < k; ++move) { vector<vector<double>> newDp(n, vector<double>(n)); for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) if (dp[i][j] > 0.0) { for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x >= n || y < 0 || y >= n) continue; newDp[x][y] += dp[i][j] * kProb; } } dp = std::move(newDp); } return accumulate(dp.begin(), dp.end(), 0.0, [](double acc, const vector<double>& row) { return acc + accumulate(row.begin(), row.end(), 0.0); }); } };
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 = [0] * n r = [0] * n summ = 0 for i, num in enumerate(nums): summ += num if i >= k: summ -= nums[i - k] if i >= k - 1: sums[i - k + 1] = summ maxIndex = 0 for i in range(n): if sums[i] > sums[maxIndex]: maxIndex = i l[i] = maxIndex maxIndex = n - 1 for i in range(n - 1, -1, -1): if sums[i] >= sums[maxIndex]: maxIndex = i r[i] = maxIndex ans = [-1, -1, -1] for i in range(k, n - k): if ans[0] == -1 or sums[ans[0]] + sums[ans[1]] + sums[ans[2]] < sums[l[i - k]] + sums[i] + sums[r[i + k]]: ans[0] = l[i - k] ans[1] = i ans[2] = r[i + k] return ans
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 maximum sums[i] int[] r = new int[n]; int sum = 0; for (int i = 0; i < nums.length; ++i) { sum += nums[i]; if (i >= k) sum -= nums[i - k]; if (i >= k - 1) sums[i - k + 1] = sum; } int maxIndex = 0; for (int i = 0; i < n; ++i) { if (sums[i] > sums[maxIndex]) maxIndex = i; l[i] = maxIndex; } maxIndex = n - 1; for (int i = n - 1; i >= 0; --i) { if (sums[i] >= sums[maxIndex]) maxIndex = i; r[i] = maxIndex; } int[] ans = {-1, -1, -1}; for (int i = k; i + k < n; ++i) if (ans[0] == -1 || sums[ans[0]] + sums[ans[1]] + sums[ans[2]] < sums[l[i - k]] + sums[i] + sums[r[i + k]]) { ans[0] = l[i - k]; ans[1] = i; ans[2] = r[i + k]; } return ans; } }
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 has the maximum sums[i] vector<int> r(n); int sum = 0; for (int i = 0; i < nums.size(); ++i) { sum += nums[i]; if (i >= k) sum -= nums[i - k]; if (i >= k - 1) sums[i - k + 1] = sum; } int maxIndex = 0; for (int i = 0; i < n; ++i) { if (sums[i] > sums[maxIndex]) maxIndex = i; l[i] = maxIndex; } maxIndex = n - 1; for (int i = n - 1; i >= 0; --i) { if (sums[i] >= sums[maxIndex]) maxIndex = i; r[i] = maxIndex; } vector<int> ans{-1, -1, -1}; for (int i = k; i < n - k; ++i) if (ans[0] == -1 || sums[ans[0]] + sums[ans[1]] + sums[ans[2]] < sums[l[i - k]] + sums[i] + sums[r[i + k]]) { ans[0] = l[i - k]; ans[1] = i; ans[2] = r[i + k]; } return ans; } };
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 quantities of each sticker. Return the minimum number of stickers that you need to spell out `target`. If the task is impossible, return `-1`. Note: In all test cases, all words were chosen randomly from the `1000` most common US English words, and `target` was chosen as a concatenation of two random words.
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 dp[0] = 0 for mask in range(maxMask): if dp[mask] == math.inf: continue for sticker in stickers: superMask = mask for c in sticker: for i, t in enumerate(target): if c == t and not (superMask >> i & 1): superMask |= 1 << i break dp[superMask] = min(dp[superMask], dp[mask] + 1) return -1 if dp[-1] == math.inf else dp[-1]
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); dp[0] = 0; for (int mask = 0; mask < maxMask; ++mask) { if (dp[mask] == Integer.MAX_VALUE) continue; // Try to expand from `mask` by using each sticker. for (final String sticker : stickers) { int superMask = mask; for (final char c : sticker.toCharArray()) for (int i = 0; i < n; ++i) // Try to apply it on a missing letter. if (c == target.charAt(i) && (superMask >> i & 1) == 0) { superMask |= 1 << i; break; } dp[superMask] = Math.min(dp[superMask], dp[mask] + 1); } } return dp[maxMask - 1] == Integer.MAX_VALUE ? -1 : dp[maxMask - 1]; } }
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 (int mask = 0; mask < maxMask; ++mask) { if (dp[mask] == INT_MAX) continue; // Try to expand from `mask` by using each sticker. for (const string& sticker : stickers) { int superMask = mask; for (const char c : sticker) for (int i = 0; i < n; ++i) // Try to apply it on a missing letter. if (c == target[i] && (superMask >> i & 1) == 0) { superMask |= 1 << i; break; } dp[superMask] = min(dp[superMask], dp[mask] + 1); } } return dp.back() == INT_MAX ? -1 : dp.back(); } };
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 block comments. * The string `"//"` denotes a line comment, which represents that it and the rest of the characters to the right of it in the same line should be ignored. * The string `"/*"` denotes a block comment, which represents that all characters until the next (non-overlapping) occurrence of `"*/"` should be ignored. (Here, occurrences happen in reading order: line by line from left to right.) To be clear, the string `"/*/"` does not yet end the block comment, as the ending would be overlapping the beginning. The first effective comment takes precedence over others. * For example, if the string `"//"` occurs in a block comment, it is ignored. * Similarly, if the string `"/*"` occurs in a line or block comment, it is also ignored. If a certain line of code is empty after removing comments, you must not output that line: each string in the answer list will be non-empty. There will be no control characters, single quote, or double quote characters. * For example, `source = "string s = "/* Not a comment. */";"` will not be a test case. Also, nothing else such as defines or macros will interfere with the comments. It is guaranteed that every open block comment will eventually be closed, so `"/*"` outside of a line or block comment always starts a new comment. Finally, implicit newline characters can be deleted by block comments. Please see the examples below for details. After removing the comments from the source code, return the source code in the same format.
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 line in source: i = 0 while i < len(line): if i + 1 == len(line): if not commenting: modified += line[i] i += 1 break twoChars = line[i:i + 2] if twoChars == '/*' and not commenting: commenting = True i += 2 elif twoChars == '*/' and commenting: commenting = False i += 2 elif twoChars == '//': if not commenting: break else: i += 2 else: if not commenting: modified += line[i] i += 1 if modified and not commenting: ans.append(modified) modified = '' return ans
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()) { if (!commenting) modified.append(line.charAt(i)); ++i; break; } String twoChars = line.substring(i, i + 2); if (twoChars.equals("/*") && !commenting) { commenting = true; i += 2; } else if (twoChars.equals("*/") && commenting) { commenting = false; i += 2; } else if (twoChars.equals("//")) { if (!commenting) break; else i += 2; } else { if (!commenting) modified.append(line.charAt(i)); ++i; } } if (modified.length() > 0 && !commenting) { ans.add(modified.toString()); modified.setLength(0); } } return ans; } }
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) modified += line[i]; ++i; break; } const string& twoChars = line.substr(i, 2); if (twoChars == "/*" && !commenting) { commenting = true; i += 2; } else if (twoChars == "*/" && commenting) { commenting = false; i += 2; } else if (twoChars == "//") { if (!commenting) break; else i += 2; } else { if (!commenting) modified += line[i]; ++i; } } if (modified.length() > 0 && !commenting) { ans.push_back(modified); modified = ""; } } return ans; } };
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 sequences `a1, a2, ...` and `b1, b2, ...` are different if there is some `i` for which `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 countPalindromicSubsequences(self, s: str) -> int: kMod = 1_000_000_007 n = len(s) dp = [[0] * n for _ in range(n)] for i in range(n): dp[i][i] = 1 for d in range(1, n): for i in range(n - d): j = i + d if s[i] == s[j]: lo = i + 1 hi = j - 1 while lo <= hi and s[lo] != s[i]: lo += 1 while lo <= hi and s[hi] != s[i]: hi -= 1 if lo > hi: dp[i][j] = dp[i + 1][j - 1] * 2 + 2 elif lo == hi: dp[i][j] = dp[i + 1][j - 1] * 2 + 1 else: dp[i][j] = dp[i + 1][j - 1] * 2 - dp[lo + 1][hi - 1] else: dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1] dp[i][j] = (dp[i][j] + kMod) % kMod return dp[0][n - 1]
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; for (int d = 1; d < n; ++d) for (int i = 0; i + d < n; ++i) { final int j = i + d; if (s.charAt(i) == s.charAt(j)) { int lo = i + 1; int hi = j - 1; while (lo <= hi && s.charAt(lo) != s.charAt(i)) ++lo; while (lo <= hi && s.charAt(hi) != s.charAt(i)) --hi; if (lo > hi) dp[i][j] = dp[i + 1][j - 1] * 2 + 2; else if (lo == hi) dp[i][j] = dp[i + 1][j - 1] * 2 + 1; else dp[i][j] = dp[i + 1][j - 1] * 2 - dp[lo + 1][hi - 1]; } else { dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]; } dp[i][j] = (int) ((dp[i][j] + MOD) % MOD); } return dp[0][n - 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) dp[i][i] = 1; for (int d = 1; d < n; ++d) for (int i = 0; i + d < n; ++i) { const int j = i + d; if (s[i] == s[j]) { int lo = i + 1; int hi = j - 1; while (lo <= hi && s[lo] != s[i]) ++lo; while (lo <= hi && s[hi] != s[i]) --hi; if (lo > hi) dp[i][j] = dp[i + 1][j - 1] * 2 + 2; else if (lo == hi) dp[i][j] = dp[i + 1][j - 1] * 2 + 1; else dp[i][j] = dp[i + 1][j - 1] * 2 - dp[lo + 1][hi - 1]; } else { dp[i][j] = dp[i][j - 1] + dp[i + 1][j] - dp[i + 1][j - 1]; } dp[i][j] = (dp[i][j] + kMod) % kMod; } return dp[0][n - 1]; } };
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 collisions. If two asteroids meet, the smaller one will explode. If both are the same size, both will explode. Two asteroids moving in the same direction will never meet.
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: stack.append(a) else: while stack and stack[-1] > 0 and stack[-1] < -a: stack.pop() if not stack or stack[-1] < 0: stack.append(a) elif stack[-1] == -a: stack.pop() else: pass return stack
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 && stack.peek() < -a) stack.pop(); if (stack.isEmpty() || stack.peek() < 0) stack.push(a); else if (stack.peek() == -a) stack.pop(); // Both asteroids explode. else // stack[-1] > the current asteroid. ; // Destroy the current asteroid, so do nothing. } return stack.stream().mapToInt(Integer::intValue).toArray(); } }
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 && stack.back() < -a) stack.pop_back(); if (stack.empty() || stack.back() < 0) stack.push_back(a); else if (stack.back() == -a) stack.pop_back(); // Both asteroids explode. else // stack[-1] > the current asteroid. ; // Destroy the current asteroid, so do nothing. } return stack; } };
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 given node `k`. Return the minimum time it takes for all the `n` nodes to receive the signal. If it is impossible for all the `n` nodes to receive the signal, return `-1`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def networkDelayTime(self, times: List[List[int]], n: int, k: int) -> int: graph = [[] for _ in range(n)] for u, v, w in times: graph[u - 1].append((v - 1, w)) return self._dijkstra(graph, k - 1) def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int) -> int: dist = [math.inf] * len(graph) dist[src] = 0 minHeap = [(dist[src], src)] while minHeap: d, u = heapq.heappop(minHeap) if d > dist[u]: continue for v, w in graph[u]: if d + w < dist[v]: dist[v] = d + w heapq.heappush(minHeap, (dist[v], v)) maxDist = max(dist) return maxDist if maxDist != math.inf else -1
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 = time[2]; graph[u].add(new Pair<>(v, w)); } return dijkstra(graph, k - 1); } private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src) { int[] dist = new int[graph.length]; Arrays.fill(dist, Integer.MAX_VALUE); dist[src] = 0; Queue<Pair<Integer, Integer>> minHeap = new PriorityQueue<>(Comparator.comparingInt(Pair::getKey)) { { offer(new Pair<>(dist[src], src)); } // (d, u) }; while (!minHeap.isEmpty()) { final int d = minHeap.peek().getKey(); final int u = minHeap.poll().getValue(); if (d > dist[u]) continue; for (Pair<Integer, Integer> pair : graph[u]) { final int v = pair.getKey(); final int w = pair.getValue(); if (d + w < dist[v]) { dist[v] = d + w; minHeap.offer(new Pair<>(dist[v], v)); } } } final int maxDist = Arrays.stream(dist).max().getAsInt(); return maxDist == Integer.MAX_VALUE ? -1 : maxDist; } }
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); } return dijkstra(graph, k - 1); } private: int dijkstra(const vector<vector<pair<int, int>>>& graph, int src) { vector<int> dist(graph.size(), INT_MAX); dist[src] = 0; using P = pair<int, int>; // (d, u) priority_queue<P, vector<P>, greater<>> minHeap; minHeap.emplace(dist[src], src); while (!minHeap.empty()) { const auto [d, u] = minHeap.top(); minHeap.pop(); if (d > dist[u]) continue; for (const auto& [v, w] : graph[u]) if (d + w < dist[v]) { dist[v] = d + w; minHeap.emplace(dist[v], v); } } const int maxDist = ranges::max(dist); return maxDist == INT_MAX ? -1 : maxDist; } };
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 each chunk and symbol. * A chunk is either an expression in parentheses, a variable, or a non-negative integer. * A variable is a string of lowercase letters (not including digits.) Note that variables can be multiple letters, and note that variables never have a leading coefficient or unary operator like `"2x"` or `"-x"`. Expressions are evaluated in the usual order: brackets first, then multiplication, then addition and subtraction. * For example, `expression = "1 + 2 * 3"` has an answer of `["7"]`. The format of the output is as follows: * For each term of free variables with a non-zero coefficient, we write the free variables within a term in sorted order lexicographically. * For example, we would never write a term like `"b*a*c"`, only `"a*b*c"`. * Terms have degrees equal to the number of free variables being multiplied, counting multiplicity. We write the largest degree terms of our answer first, breaking ties by lexicographic order ignoring the leading coefficient of the term. * For example, `"a*a*b*c"` has degree `4`. * The leading coefficient of the term is placed directly to the left with an asterisk separating it from the variables (if they exist.) A leading coefficient of 1 is still printed. * An example of a well-formatted answer is `["-2*a*a*a", "3*a*a*b", "3*b*b", "4*a", "5*c", "-6"]`. * Terms (including constant terms) with coefficient `0` are not included. * For example, an expression of `"0"` has an output of `[]`. Note: You may assume that the given expression is always valid. All intermediate results will be in the range of `[-231, 231 - 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 Poly: def __init__(self, term: str = None, coef: int = None): if term and coef: self.terms = collections.Counter({term: coef}) else: self.terms = collections.Counter() def __add__(self, other): for term, coef in other.terms.items(): self.terms[term] += coef return self def __sub__(self, other): for term, coef in other.terms.items(): self.terms[term] -= coef return self def __mul__(self, other): res = Poly() for a, aCoef in self.terms.items(): for b, bCoef in other.terms.items(): res.terms[self._merge(a, b)] += aCoef * bCoef return res def toList(self) -> List[str]: for term in list(self.terms.keys()): if not self.terms[term]: del self.terms[term] def cmp(term: str) -> tuple: if term == '1': return (0,) var = term.split('*') return (-len(var), term) def concat(term: str) -> str: if term == '1': return str(self.terms[term]) return str(self.terms[term]) + '*' + term terms = list(self.terms.keys()) terms.sort(key=cmp) return [concat(term) for term in terms] def _merge(self, a: str, b: str) -> str: if a == '1': return b if b == '1': return a res = [] A = a.split('*') B = b.split('*') i = 0 j = 0 while i < len(A) and j < len(B): if A[i] < B[j]: res.append(A[i]) i += 1 else: res.append(B[j]) j += 1 return '*'.join(res + A[i:] + B[j:]) class Solution: def basicCalculatorIV(self, expression: str, evalvars: List[str], evalints: List[int]) -> List[str]: tokens = list(self._getTokens(expression)) evalMap = {a: b for a, b in zip(evalvars, evalints)} for i, token in enumerate(tokens): if token in evalMap: tokens[i] = str(evalMap[token]) postfix = self._infixToPostfix(tokens) return self._evaluate(postfix).toList() def _getTokens(self, s: str) -> Iterator[str]: i = 0 for j, c in enumerate(s): if c == ' ': if i < j: yield s[i:j] i = j + 1 elif c in '()+-*': if i < j: yield s[i:j] yield c i = j + 1 if i < len(s): yield s[i:] def _infixToPostfix(self, tokens: List[str]) -> List[str]: postfix = [] ops = [] def precedes(prevOp: str, currOp: str) -> bool: if prevOp == '(': return False return prevOp == '*' or currOp in '+-' for token in tokens: if token == '(': ops.append(token) elif token == ')': while ops[-1] != '(': postfix.append(ops.pop()) ops.pop() elif token in '+-*': while ops and precedes(ops[-1], token): postfix.append(ops.pop()) ops.append(token) else: postfix.append(token) return postfix + ops[::-1] def _evaluate(self, postfix: List[str]) -> Poly: polys: List[Poly] = [] for token in postfix: if token in '+-*': b = polys.pop() a = polys.pop() if token == '+': polys.append(a + b) elif token == '-': polys.append(a - b) else: polys.append(a * b) elif token.lstrip('-').isnumeric(): polys.append(Poly("1", int(token))) else: polys.append(Poly(token, 1)) return polys[0]
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; } public Poly mult(Poly o) { Poly res = new Poly(); for (final String a : terms.keySet()) for (final String b : o.terms.keySet()) res.terms.merge(merge(a, b), terms.get(a) * o.terms.get(b), Integer::sum); return res; } // @Override // Public String toString() { // StringBuilder sb = new StringBuilder(); // sb.append("{"); // for (final String term : terms.keySet()) // sb.append(term).append(": ").append(terms.get(term)).append(", "); // sb.append("}"); // return sb.toString(); // } public List<String> toList() { List<String> res = new ArrayList<>(); List<String> keys = new ArrayList<>(terms.keySet()); Collections.sort(keys, new Comparator<String>() { @Override public int compare(final String a, final String b) { // the minimum degree is the last if (a.equals("1")) return 1; if (b.equals("1")) return -1; String[] as = a.split("\\*"); String[] bs = b.split("\\*"); // the maximum degree is the first // Break ties by their lexicographic orders. return as.length == bs.length ? a.compareTo(b) : bs.length - as.length; } }); for (final String key : keys) if (terms.get(key) != 0) res.add(concat(key)); return res; } public Poly() {} public Poly(final String term, int coef) { terms.put(term, coef); } private Map<String, Integer> terms = new HashMap<>(); // e.g. merge("a*b", "a*c") -> "a*a*b*c" private static String merge(final String a, final String b) { if (a.equals("1")) return b; if (b.equals("1")) return a; StringBuilder sb = new StringBuilder(); String[] A = a.split("\\*"); String[] B = b.split("\\*"); int i = 0; // A's index int j = 0; // B's index while (i < A.length && j < B.length) if (A[i].compareTo(B[j]) < 0) sb.append("*").append(A[i++]); else sb.append("*").append(B[j++]); while (i < A.length) sb.append("*").append(A[i++]); while (j < B.length) sb.append("*").append(B[j++]); return sb.substring(1).toString(); } private String concat(final String term) { if (term.equals("1")) return String.valueOf(terms.get(term)); return new StringBuilder().append(terms.get(term)).append('*').append(term).toString(); } } class Solution { public List<String> basicCalculatorIV(String expression, String[] evalvars, int[] evalints) { List<String> tokens = getTokens(expression); Map<String, Integer> evalMap = new HashMap<>(); for (int i = 0; i < evalvars.length; ++i) evalMap.put(evalvars[i], evalints[i]); for (int i = 0; i < tokens.size(); ++i) if (evalMap.containsKey(tokens.get(i))) tokens.set(i, String.valueOf(evalMap.get(tokens.get(i)))); List<String> postfix = infixToPostfix(tokens); return evaluate(postfix).toList(); } private List<String> getTokens(final String s) { List<String> tokens = new ArrayList<>(); int i = 0; for (int j = 0; j < s.length(); ++j) if (s.charAt(j) == ' ') { if (i < j) tokens.add(s.substring(i, j)); i = j + 1; } else if ("()+-*".contains(s.substring(j, j + 1))) { if (i < j) tokens.add(s.substring(i, j)); tokens.add(s.substring(j, j + 1)); i = j + 1; } if (i < s.length()) tokens.add(s.substring(i)); return tokens; } private boolean isOperator(final String token) { return token.equals("+") || token.equals("-") || token.equals("*"); } private boolean precedes(final String prevOp, final String currOp) { if (prevOp.equals("(")) return false; return prevOp.equals("*") || currOp.equals("+") || currOp.equals("-"); } private List<String> infixToPostfix(List<String> tokens) { List<String> postfix = new ArrayList<>(); Deque<String> ops = new ArrayDeque<>(); for (final String token : tokens) if (token.equals("(")) { ops.push(token); } else if (token.equals(")")) { while (!ops.peek().equals("(")) postfix.add(ops.pop()); ops.pop(); } else if (isOperator(token)) { while (!ops.isEmpty() && precedes(ops.peek(), token)) postfix.add(ops.pop()); ops.push(token); } else { // isOperand(token) postfix.add(token); } while (!ops.isEmpty()) postfix.add(ops.pop()); return postfix; } private Poly evaluate(List<String> postfix) { LinkedList<Poly> polys = new LinkedList<>(); for (final String token : postfix) if (isOperator(token)) { final Poly b = polys.removeLast(); final Poly a = polys.removeLast(); if (token.equals("+")) polys.add(a.add(b)); else if (token.equals("-")) polys.add(a.minus(b)); else // token == "*" polys.add(a.mult(b)); } else if (token.charAt(0) == '-' || token.chars().allMatch(c -> Character.isDigit(c))) { polys.add(new Poly("1", Integer.parseInt(token))); } else { polys.add(new Poly(token, 1)); } return polys.getFirst(); } }
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) res.terms[term] -= coef; return res; } friend Poly operator*(const Poly& lhs, const Poly& rhs) { Poly res; for (const auto& [a, aCoef] : lhs.terms) for (const auto& [b, bCoef] : rhs.terms) res.terms[merge(a, b)] += aCoef * bCoef; return res; } // Friend ostream& operator<<(ostream& os, const Poly& poly) { // os << "{"; // for (const auto& [term, coef] : poly.terms) // os << term << ": " << coef << ", "; // os << "}"; // return os; // } public: vector<string> toList() { vector<string> res; vector<string> keys; for (const auto& [term, _] : terms) keys.push_back(term); ranges::sort(keys, [&](const string& a, const string& b) { // the minimum degree is the last if (a == "1") return false; if (b == "1") return true; const vector<string> as = split(a, '*'); const vector<string> bs = split(b, '*'); // the maximum degree is the first // Break ties by their lexicographic orders. return as.size() == bs.size() ? a < b : as.size() > bs.size(); }); auto concat = [&](const string& term) -> string { if (term == "1") return to_string(terms[term]); return to_string(terms[term]) + '*' + term; }; for (const string& key : keys) if (terms[key]) res.push_back(concat(key)); return res; } Poly() = default; Poly(const string& term, int coef) { terms[term] = coef; } private: unordered_map<string, int> terms; // e.g. merge("a*b", "a*c") -> "a*a*b*c" static string merge(const string& a, const string& b) { if (a == "1") return b; if (b == "1") return a; string res; vector<string> A = split(a, '*'); vector<string> B = split(b, '*'); int i = 0; // A's index int j = 0; // B's index while (i < A.size() && j < B.size()) if (A[i] < B[j]) res += '*' + A[i++]; else res += '*' + B[j++]; while (i < A.size()) res += '*' + A[i++]; while (j < B.size()) res += '*' + B[j++]; return res.substr(1); } static vector<string> split(const string& token, char c) { vector<string> vars; istringstream iss(token); for (string var; getline(iss, var, c);) vars.push_back(var); return vars; } }; class Solution { public: vector<string> basicCalculatorIV(string expression, vector<string>& evalvars, vector<int>& evalints) { vector<string> tokens = getTokens(expression); unordered_map<string, int> evalMap; for (int i = 0; i < evalvars.size(); ++i) evalMap[evalvars[i]] = evalints[i]; for (string& token : tokens) if (const auto it = evalMap.find(token); it != evalMap.cend()) token = to_string(it->second); const vector<string>& postfix = infixToPostfix(tokens); return evaluate(postfix).toList(); } private: vector<string> getTokens(const string& s) { vector<string> tokens; int i = 0; for (int j = 0; j < s.length(); ++j) if (s[j] == ' ') { if (i < j) tokens.push_back(s.substr(i, j - i)); i = j + 1; } else if (string("()+-*").find(s[j]) != string::npos) { if (i < j) tokens.push_back(s.substr(i, j - i)); tokens.push_back(s.substr(j, 1)); i = j + 1; } if (i < s.length()) tokens.push_back(s.substr(i)); return tokens; } bool isOperator(const string& token) { return token == "+" || token == "-" || token == "*"; } vector<string> infixToPostfix(const vector<string>& tokens) { vector<string> postfix; stack<string> ops; auto precedes = [](const string& prevOp, const string& currOp) -> bool { if (prevOp == "(") return false; return prevOp == "*" || currOp == "+" || currOp == "-"; }; for (const string& token : tokens) if (token == "(") { ops.push(token); } else if (token == ")") { while (ops.top() != "(") postfix.push_back(ops.top()), ops.pop(); ops.pop(); } else if (isOperator(token)) { while (!ops.empty() && precedes(ops.top(), token)) postfix.push_back(ops.top()), ops.pop(); ops.push(token); } else { // isOperand(token) postfix.push_back(token); } while (!ops.empty()) postfix.push_back(ops.top()), ops.pop(); return postfix; } Poly evaluate(const vector<string>& postfix) { vector<Poly> polys; for (const string& token : postfix) if (isOperator(token)) { const Poly b = polys.back(); polys.pop_back(); const Poly a = polys.back(); polys.pop_back(); if (token == "+") polys.push_back(a + b); else if (token == "-") polys.push_back(a - b); else // token == "*" polys.push_back(a * b); } else if (token[0] == '-' || ranges::all_of(token, [](char c) { return isdigit(c); })) { polys.push_back(Poly("1", stoi(token))); } else { polys.push_back(Poly(token, 1)); } return polys[0]; } };
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 of moves to transform one string to the other.
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 False i = 0 j = 0 while i < len(start) and j < len(end): while i < len(start) and start[i] == 'X': i += 1 while j < len(end) and end[j] == 'X': j += 1 if i == len(start) and j == len(end): return True if i == len(start) or j == len(end): return False if start[i] == 'L' and i < j: return False if start[i] == 'R' and i > j: return False i += 1 j += 1 return True
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.charAt(i) == 'X') ++i; while (j < end.length() && end.charAt(j) == 'X') ++j; if (i == start.length() && j == end.length()) return true; if (i == start.length() || j == end.length()) return false; // L can only move to left. if (start.charAt(i) == 'L' && i < j) return false; // R can only move to right. if (start.charAt(i) == 'R' && i > j) return false; ++i; ++j; } return true; } }
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; while (j < end.length() && end[j] == 'X') ++j; if (i == start.length() && j == end.length()) return true; if (i == start.length() || j == end.length()) return false; // L can only move to left. if (start[i] == 'L' && i < j) return false; // R can only move to right. if (start[i] == 'R' && i > j) return false; ++i; ++j; } return true; } private: string removeX(const string& s) { string t = s; std::erase(t, 'X'); return t; } };
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`'s are 4-directionally adjacent.
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(n): if board[0][0] ^ board[i][0] ^ board[0][j] ^ board[i][j]: return -1 rowSum = sum(board[0]) colSum = sum(board[i][0] for i in range(n)) if rowSum != n // 2 and rowSum != (n + 1) // 2: return -1 if colSum != n // 2 and colSum != (n + 1) // 2: return -1 rowSwaps = sum(board[i][0] == (i & 1) for i in range(n)) colSwaps = sum(board[0][i] == (i & 1) for i in range(n)) if n & 1: if rowSwaps & 1: rowSwaps = n - rowSwaps if colSwaps & 1: colSwaps = n - colSwaps else: rowSwaps = min(rowSwaps, n - rowSwaps) colSwaps = min(colSwaps, n - colSwaps) return (rowSwaps + colSwaps) // 2
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) return -1; for (int i = 0; i < n; ++i) { rowSum += board[0][i]; colSum += board[i][0]; } if (rowSum != n / 2 && rowSum != (n + 1) / 2) return -1; if (colSum != n / 2 && colSum != (n + 1) / 2) return -1; for (int i = 0; i < n; ++i) { if (board[i][0] == (i & 1)) ++rowSwaps; if (board[0][i] == (i & 1)) ++colSwaps; } if (n % 2 == 1) { if (rowSwaps % 2 == 1) rowSwaps = n - rowSwaps; if (colSwaps % 2 == 1) colSwaps = n - colSwaps; } else { rowSwaps = Math.min(rowSwaps, n - rowSwaps); colSwaps = Math.min(colSwaps, n - colSwaps); } return (rowSwaps + colSwaps) / 2; } }
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] ^ board[i][j] == 1) return -1; for (int i = 0; i < n; ++i) { rowSum += board[0][i]; colSum += board[i][0]; } if (rowSum != n / 2 && rowSum != (n + 1) / 2) return -1; if (colSum != n / 2 && colSum != (n + 1) / 2) return -1; for (int i = 0; i < n; ++i) { rowSwaps += board[i][0] == (i & 1); colSwaps += board[0][i] == (i & 1); } if (n % 2 == 1) { if (rowSwaps % 2 == 1) rowSwaps = n - rowSwaps; if (colSwaps % 2 == 1) colSwaps = n - colSwaps; } else { rowSwaps = min(rowSwaps, n - rowSwaps); colSwaps = min(colSwaps, n - colSwaps); } return (rowSwaps + colSwaps) / 2; } };
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 answer as an array of integers of size `2`, where `answer[0] == arr[i]` and `answer[1] == arr[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 kthSmallestPrimeFraction(self, arr: List[int], k: int) -> List[int]: n = len(arr) ans = [0, 1] l = 0 r = 1 while True: m = (l + r) / 2 ans[0] = 0 count = 0 j = 1 for i in range(n): while j < n and arr[i] > m * arr[j]: j += 1 count += n - j if j == n: break if ans[0] * arr[j] < ans[1] * arr[i]: ans[0] = arr[i] ans[1] = arr[j] if count < k: l = m elif count > k: r = m else: return ans
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 first index j s.t. arr[i] / arr[j] <= m, // so fractionsNoGreaterThanM for index i will be n - j. for (int i = 0, j = 1; i < n; ++i) { while (j < n && arr[i] > m * arr[j]) ++j; if (j == n) break; fractionsNoGreaterThanM += n - j; if (p * arr[j] < q * arr[i]) { p = arr[i]; q = arr[j]; } } if (fractionsNoGreaterThanM == k) return new int[] {p, q}; if (fractionsNoGreaterThanM > k) r = m; else l = m; } throw new IllegalArgumentException(); } }
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, find the first index j s.t. arr[i] / arr[j] <= m, // so fractionsNoGreaterThanM for index i will be n - j. for (int i = 0, j = 1; i < n; ++i) { while (j < n && arr[i] > m * arr[j]) ++j; if (j == n) break; fractionsNoGreaterThanM += n - j; if (p * arr[j] < q * arr[i]) { p = arr[i]; q = arr[j]; } } if (fractionsNoGreaterThanM == k) return {p, q}; if (fractionsNoGreaterThanM > k) r = m; else l = m; } throw; } };
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` with at most `k` stops. If there is no such route, return `-1`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def findCheapestPrice(self, n: int, flights: List[List[int]], src: int, dst: int, k: int) -> int: graph = [[] for _ in range(n)] for u, v, w in flights: graph[u].append((v, w)) return self._dijkstra(graph, src, dst, k) def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, dst: int, k: int) -> int: dist=[] for i in range(len(graph)): dist.append([math.inf for _ in range(k + 2)]) dist[src][k + 1] = 0 minHeap = [(dist[src][k + 1], src, k + 1)] while minHeap: d, u, stops = heapq.heappop(minHeap) if u == dst: return d if stops == 0 or d > dist[u][stops]: continue for v, w in graph[u]: if d + w < dist[v][stops - 1]: dist[v][stops - 1] = d + w heapq.heappush(minHeap, (dist[v][stops - 1], v, stops - 1)) return -1
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]; final int w = flight[2]; graph[u].add(new Pair<>(v, w)); } return dijkstra(graph, src, dst, k); } private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int dst, int k) { int[][] dist = new int[graph.length][k + 2]; Arrays.stream(dist).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); dist[src][k + 1] = 0; Queue<int[]> minHeap = new PriorityQueue<>(Comparator.comparingInt(a -> a[0])) { { offer(new int[] {dist[src][k + 1], src, k + 1}); } // (d, u, stops) }; while (!minHeap.isEmpty()) { final int d = minHeap.peek()[0]; final int u = minHeap.peek()[1]; final int stops = minHeap.poll()[2]; if (u == dst) return d; if (stops == 0 || d > dist[u][stops]) continue; for (Pair<Integer, Integer> pair : graph[u]) { final int v = pair.getKey(); final int w = pair.getValue(); if (d + w < dist[v][stops - 1]) { dist[v][stops - 1] = d + w; minHeap.offer(new int[] {dist[v][stops - 1], v, stops - 1}); } } } return -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[2]; graph[u].emplace_back(v, w); } return dijkstra(graph, src, dst, k); } private: int dijkstra(const vector<vector<pair<int, int>>>& graph, int src, int dst, int k) { vector<vector<int>> dist(graph.size(), vector<int>(k + 2, INT_MAX)); dist[src][k + 1] = 0; using T = tuple<int, int, int>; // (d, u, stops) priority_queue<T, vector<T>, greater<>> minHeap; minHeap.emplace(dist[src][k + 1], src, k + 1); while (!minHeap.empty()) { const auto [d, u, stops] = minHeap.top(); minHeap.pop(); if (u == dst) return d; if (stops == 0 || d > dist[u][stops]) continue; for (const auto& [v, w] : graph[u]) if (d + w < dist[v][stops - 1]) { dist[v][stops - 1] = d + w; minHeap.emplace(dist[v][stops - 1], v, stops - 1); } } return -1; } };
End of preview. Expand in Data Studio

TestEval-extend

This is the extended dataset used in the paper DiffTester: Accelerating Unit Test Generation for Diffusion LLMs via Repetitive Pattern.

Code: https://github.com/wellbeingyang/DLM4UTG-open

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
25