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; } };
794
Valid Tic-Tac-Toe State
2
validTicTacToe
Given a Tic-Tac-Toe board as a string array `board`, return `true` if and only if it is possible to reach this board position during the course of a valid tic-tac-toe game. The board is a `3 x 3` array that consists of characters `' '`, `'X'`, and `'O'`. The `' '` character represents an empty square. Here are the rules of Tic-Tac-Toe: * Players take turns placing characters into empty squares `' '`. * The first player always places `'X'` characters, while the second player always places `'O'` characters. * `'X'` and `'O'` characters are always placed into empty squares, never filled ones. * The game ends when there are three of the same (non-empty) character filling any row, column, or diagonal. * The game also ends if all squares are non-empty. * No more moves can be played if the game is over.
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 validTicTacToe(self, board: List[str]) -> bool: def isWin(c: str) -> bool: return any(row.count(c) == 3 for row in board) or any(row.count(c) == 3 for row in list(zip(*board))) or all(board[i][i] == c for i in range(3)) or all(board[i][2 - i] == c for i in range(3)) countX = sum(row.count('X') for row in board) countO = sum(row.count('O') for row in board) if countX < countO or countX - countO > 1: return False if isWin('X') and countX == countO or isWin('O') and countX != countO: return False return True
class Solution { public boolean validTicTacToe(String[] board) { final int countX = sum(board, 'X'); final int countO = sum(board, 'O'); if (countX < countO || countX - countO > 1) return false; if (isWinned(board, 'X') && countX == countO || // isWinned(board, 'O') && countX != countO) return false; return true; } private int sum(final String[] board, char c) { int ans = 0; for (final String row : board) ans += row.chars().filter(i -> i == c).count(); return ans; } private boolean isWinned(final String[] board, char c) { String[] rotated = rotate(board); return Arrays.stream(board).anyMatch(row -> row.chars().filter(i -> i == c).count() == 3) || Arrays.stream(rotated).anyMatch(row -> row.chars().filter(i -> i == c).count() == 3) || board[0].charAt(0) == c && board[1].charAt(1) == c && board[2].charAt(2) == c || board[0].charAt(2) == c && board[1].charAt(1) == c && board[2].charAt(0) == c; } private String[] rotate(final String[] board) { String[] rotated = new String[3]; for (final String row : board) for (int i = 0; i < 3; ++i) rotated[i] += row.charAt(i); return rotated; } }
class Solution { public: bool validTicTacToe(vector<string>& board) { const int countX = sum(board, 'X'); const int countO = sum(board, 'O'); if (countX < countO || countX - countO > 1) return false; if (isWinned(board, 'X') && countX == countO || isWinned(board, 'O') && countX != countO) return false; return true; } private: int sum(const vector<string>& board, char c) { int ans = 0; for (const string& row : board) ans += ranges::count(row, c); return ans; } bool isWinned(const vector<string>& board, char c) { vector<string> rotated = rotate(board); auto equalsToThree = [&c](const string& row) { return ranges::count(row, c) == 3; }; return ranges::any_of(board, equalsToThree) || ranges::any_of(rotated, equalsToThree) || board[0][0] == c && board[1][1] == c && board[2][2] == c || board[0][2] == c && board[1][1] == c && board[2][0] == c; } vector<string> rotate(const vector<string>& board) { vector<string> rotated(3); for (const string& row : board) for (int i = 0; i < 3; ++i) rotated[i].push_back(row[i]); return rotated; } };
805
Split Array With Same Average
3
splitArraySameAverage
You are given an integer array `nums`. You should move each element of `nums` into one of the two arrays `A` and `B` such that `A` and `B` are non-empty, and `average(A) == average(B)`. Return `true` if it is possible to achieve that and `false` otherwise. Note that for an array `arr`, `average(arr)` is the sum of all the elements of `arr` over the length of `arr`.
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 splitArraySameAverage(self, nums: List[int]) -> bool: n = len(nums) summ = sum(nums) if not any(i * summ % n == 0 for i in range(1, n // 2 + 1)): return False sums = [set() for _ in range(n // 2 + 1)] sums[0].add(0) for num in nums: for i in range(n // 2, 0, -1): for val in sums[i - 1]: sums[i].add(num + val) for i in range(1, n // 2 + 1): if i * summ % n == 0 and i * summ // n in sums[i]: return True return False
class Solution { public boolean splitArraySameAverage(int[] nums) { final int n = nums.length; final int sum = Arrays.stream(nums).sum(); if (!isPossible(sum, n)) return false; List<Set<Integer>> sums = new ArrayList<>(); for (int i = 0; i < n / 2 + 1; ++i) sums.add(new HashSet<>()); sums.get(0).add(0); for (final int num : nums) for (int i = n / 2; i > 0; --i) for (final int val : sums.get(i - 1)) sums.get(i).add(num + val); for (int i = 1; i < n / 2 + 1; ++i) if (i * sum % n == 0 && sums.get(i).contains(i * sum / n)) return true; return false; } private boolean isPossible(int sum, int n) { for (int i = 1; i < n / 2 + 1; ++i) if (i * sum % n == 0) return true; return false; } }
class Solution { public: bool splitArraySameAverage(vector<int>& nums) { const int n = nums.size(); const int sum = accumulate(nums.begin(), nums.end(), 0); if (!isPossible(sum, n)) return false; vector<unordered_set<int>> sums(n / 2 + 1); sums[0].insert(0); for (const int num : nums) for (int i = n / 2; i > 0; --i) for (const int val : sums[i - 1]) sums[i].insert(num + val); for (int i = 1; i < n / 2 + 1; ++i) if (i * sum % n == 0 && sums[i].contains(i * sum / n)) return true; return false; } private: bool isPossible(int sum, int n) { for (int i = 1; i < n / 2 + 1; ++i) if (i * sum % n == 0) return true; return false; } };
815
Bus Routes
3
numBusesToDestination
You are given an array `routes` representing bus routes where `routes[i]` is a bus route that the `ith` bus repeats forever. * For example, if `routes[0] = [1, 5, 7]`, this means that the `0th` bus travels in the sequence `1 -> 5 -> 7 -> 1 -> 5 -> 7 -> 1 -> ...` forever. You will start at the bus stop `source` (You are not on any bus initially), and you want to go to the bus stop `target`. You can travel between bus stops by buses only. Return the least number of buses you must take to travel from `source` to `target`. Return `-1` if it is not possible.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def numBusesToDestination(self, routes: List[List[int]], source: int, target: int) -> int: if source == target: return 0 graph = collections.defaultdict(list) usedBuses = set() for i in range(len(routes)): for route in routes[i]: graph[route].append(i) ans = 0 q = collections.deque([source]) while q: ans += 1 for _ in range(len(q)): for bus in graph[q.popleft()]: if bus in usedBuses: continue usedBuses.add(bus) for nextRoute in routes[bus]: if nextRoute == target: return ans q.append(nextRoute) return -1
class Solution { public int numBusesToDestination(int[][] routes, int source, int target) { if (source == target) return 0; Map<Integer, List<Integer>> graph = new HashMap<>(); // {route: [buses]} Set<Integer> usedBuses = new HashSet<>(); for (int i = 0; i < routes.length; ++i) for (final int route : routes[i]) { graph.putIfAbsent(route, new ArrayList<>()); graph.get(route).add(i); } Queue<Integer> q = new ArrayDeque<>(List.of(source)); for (int step = 1; !q.isEmpty(); ++step) for (int sz = q.size(); sz > 0; --sz) { for (final int bus : graph.getOrDefault(q.poll(), new ArrayList<>())) if (usedBuses.add(bus)) for (final int nextRoute : routes[bus]) { if (nextRoute == target) return step; q.offer(nextRoute); } } return -1; } }
class Solution { public: int numBusesToDestination(vector<vector<int>>& routes, int source, int target) { if (source == target) return 0; unordered_map<int, vector<int>> graph; // {route: [buses]} unordered_set<int> usedBuses; for (int i = 0; i < routes.size(); ++i) for (const int route : routes[i]) graph[route].push_back(i); queue<int> q{{source}}; for (int step = 1; !q.empty(); ++step) for (int sz = q.size(); sz > 0; --sz) { const int route = q.front(); q.pop(); for (const int bus : graph[route]) if (usedBuses.insert(bus).second) for (const int nextRoute : routes[bus]) { if (nextRoute == target) return step; q.push(nextRoute); } } return -1; } };
838
Push Dominoes
2
pushDominoes
There are `n` dominoes in a line, and we place each domino vertically upright. In the beginning, we simultaneously push some of the dominoes either to the left or to the right. After each second, each domino that is falling to the left pushes the adjacent domino on the left. Similarly, the dominoes falling to the right push their adjacent dominoes standing on the right. When a vertical domino has dominoes falling on it from both sides, it stays still due to the balance of the forces. For the purposes of this question, we will consider that a falling domino expends no additional force to a falling or already fallen domino. You are given a string `dominoes` representing the initial state where: * `dominoes[i] = 'L'`, if the `ith` domino has been pushed to the left, * `dominoes[i] = 'R'`, if the `ith` domino has been pushed to the right, and * `dominoes[i] = '.'`, if the `ith` domino has not been pushed. Return a string representing the final 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 pushDominoes(self, dominoes: str) -> str: ans = list(dominoes) L = -1 R = -1 for i in range(len(dominoes) + 1): if i == len(dominoes) or dominoes[i] == 'R': if L < R: while R < i: ans[R] = 'R' R += 1 R = i elif dominoes[i] == 'L': if R < L or (L, R) == (-1, -1): if (L, R) == (-1, -1): L += 1 while L < i: ans[L] = 'L' L += 1 else: l = R + 1 r = i - 1 while l < r: ans[l] = 'R' ans[r] = 'L' l += 1 r -= 1 L = i return ''.join(ans)
class Solution { public String pushDominoes(String dominoes) { char[] s = dominoes.toCharArray(); int L = -1; int R = -1; for (int i = 0; i <= dominoes.length(); ++i) if (i == dominoes.length() || s[i] == 'R') { if (L < R) while (R < i) s[R++] = 'R'; R = i; } else if (s[i] == 'L') { if (R < L || L == -1 && R == -1) { if (L == -1 && R == -1) ++L; while (L < i) s[L++] = 'L'; } else { int l = R + 1; int r = i - 1; while (l < r) { s[l++] = 'R'; s[r--] = 'L'; } } L = i; } return new String(s); } }
class Solution { public: string pushDominoes(string dominoes) { int L = -1; int R = -1; for (int i = 0; i <= dominoes.length(); ++i) if (i == dominoes.length() || dominoes[i] == 'R') { if (L < R) while (R < i) dominoes[R++] = 'R'; R = i; } else if (dominoes[i] == 'L') { if (R < L || L == -1 && R == -1) { if (L == -1 && R == -1) ++L; while (L < i) dominoes[L++] = 'L'; } else { int l = R + 1; int r = i - 1; while (l < r) { dominoes[l++] = 'R'; dominoes[r--] = 'L'; } } L = i; } return dominoes; } };
845
Longest Mountain in Array
2
longestMountain
You may recall that an array `arr` is a mountain array if and only if: * `arr.length >= 3` * There exists some index `i` (0-indexed) with `0 < i < arr.length - 1` such that: * `arr[0] < arr[1] < ... < arr[i - 1] < arr[i]` * `arr[i] > arr[i + 1] > ... > arr[arr.length - 1]` Given an integer array `arr`, return the length of the longest subarray, which is a mountain. Return `0` if there is no mountain subarray.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def longestMountain(self, arr: List[int]) -> int: ans = 0 i = 0 while i + 1 < len(arr): while i + 1 < len(arr) and arr[i] == arr[i + 1]: i += 1 increasing = 0 decreasing = 0 while i + 1 < len(arr) and arr[i] < arr[i + 1]: increasing += 1 i += 1 while i + 1 < len(arr) and arr[i] > arr[i + 1]: decreasing += 1 i += 1 if increasing > 0 and decreasing > 0: ans = max(ans, increasing + decreasing + 1) return ans
class Solution { public int longestMountain(int[] arr) { int ans = 0; for (int i = 0; i + 1 < arr.length;) { while (i + 1 < arr.length && arr[i] == arr[i + 1]) ++i; int increasing = 0; int decreasing = 0; while (i + 1 < arr.length && arr[i] < arr[i + 1]) { ++increasing; ++i; } while (i + 1 < arr.length && arr[i] > arr[i + 1]) { ++decreasing; ++i; } if (increasing > 0 && decreasing > 0) ans = Math.max(ans, increasing + decreasing + 1); } return ans; } }
class Solution { public: int longestMountain(vector<int>& arr) { int ans = 0; for (int i = 0; i + 1 < arr.size();) { while (i + 1 < arr.size() && arr[i] == arr[i + 1]) ++i; int increasing = 0; int decreasing = 0; while (i + 1 < arr.size() && arr[i] < arr[i + 1]) { ++increasing; ++i; } while (i + 1 < arr.size() && arr[i] > arr[i + 1]) { ++decreasing; ++i; } if (increasing > 0 && decreasing > 0) ans = max(ans, increasing + decreasing + 1); } return ans; } };
854
K-Similar Strings
3
kSimilarity
Strings `s1` and `s2` are `k`-similar (for some non-negative integer `k`) if we can swap the positions of two letters in `s1` exactly `k` times so that the resulting string equals `s2`. Given two anagrams `s1` and `s2`, return the smallest `k` for which `s1` and `s2` are `k`-similar.
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 kSimilarity(self, s1: str, s2: str) -> int: ans = 0 q = collections.deque([s1]) seen = {s1} while q: for _ in range(len(q)): curr = q.popleft() if curr == s2: return ans for child in self._getChildren(curr, s2): if child in seen: continue q.append(child) seen.add(child) ans += 1 return -1 def _getChildren(self, curr: str, target: str) -> List[str]: children = [] s = list(curr) i = 0 while curr[i] == target[i]: i += 1 for j in range(i + 1, len(s)): if s[j] == target[i]: s[i], s[j] = s[j], s[i] children.append(''.join(s)) s[i], s[j] = s[j], s[i] return children
class Solution { public int kSimilarity(String s1, String s2) { Queue<String> q = new ArrayDeque<>(List.of(s1)); Set<String> seen = new HashSet<>(Arrays.asList(s1)); for (int step = 0; !q.isEmpty(); ++step) for (int sz = q.size(); sz > 0; --sz) { final String curr = q.poll(); if (curr.equals(s2)) return step; for (final String child : getChildren(curr, s2)) { if (seen.contains(child)) continue; q.offer(child); seen.add(child); } } return -1; } private List<String> getChildren(final String curr, final String target) { List<String> children = new ArrayList<>(); char[] charArray = curr.toCharArray(); int i = 0; // the first index s.t. curr.charAt(i) != target.charAt(i) while (curr.charAt(i) == target.charAt(i)) ++i; for (int j = i + 1; j < charArray.length; ++j) if (curr.charAt(j) == target.charAt(i)) { swap(charArray, i, j); children.add(String.valueOf(charArray)); swap(charArray, i, j); } return children; } private void swap(char[] charArray, int i, int j) { final char temp = charArray[i]; charArray[i] = charArray[j]; charArray[j] = temp; } }
class Solution { public: int kSimilarity(string s1, string s2) { queue<string> q{{s1}}; unordered_set<string> seen{{s1}}; for (int step = 0; !q.empty(); ++step) for (int sz = q.size(); sz > 0; --sz) { string curr = q.front(); q.pop(); if (curr == s2) return step; for (const string& child : getChildren(curr, s2)) { if (seen.contains(child)) continue; q.push(child); seen.insert(child); } } return -1; } private: vector<string> getChildren(string& curr, const string& target) { vector<string> children; int i = 0; // the first index s.t. curr[i] != target[i] while (curr[i] == target[i]) ++i; for (int j = i + 1; j < curr.length(); ++j) if (curr[j] == target[i]) { swap(curr[i], curr[j]); children.push_back(curr); swap(curr[i], curr[j]); } return children; } };
861
Score After Flipping Matrix
2
matrixScore
You are given an `m x n` binary matrix `grid`. A move consists of choosing any row or column and toggling each value in that row or column (i.e., changing all `0`'s to `1`'s, and all `1`'s to `0`'s). Every row of the matrix is interpreted as a binary number, and the score of the matrix is the sum of these numbers. Return the highest possible score after making any number of moves (including zero moves).
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 matrixScore(self, grid: List[List[int]]) -> int: for row in grid: if row[0] == 0: self._flip(row) for j, col in enumerate(list(zip(*grid))): if sum(col) * 2 < len(grid): self._flipCol(grid, j) return sum(self._binary(row) for row in grid) def _flip(self, row: List[int]) -> None: for i in range(len(row)): row[i] ^= 1 def _flipCol(self, grid: List[List[int]], j: int) -> None: for i in range(len(grid)): grid[i][j] ^= 1 def _binary(self, row: List[int]) -> int: res = row[0] for j in range(1, len(row)): res = res * 2 + row[j] return res
class Solution { public int matrixScore(int[][] grid) { final int m = grid.length; final int n = grid[0].length; int ans = 0; // Flip the rows with a leading 0. for (int[] row : grid) if (row[0] == 0) flip(row); // Flip the columns with 1s < 0s. for (int j = 0; j < n; ++j) if (onesColCount(grid, j) * 2 < m) flipCol(grid, j); // Add a binary number for each row. for (int[] row : grid) ans += binary(row); return ans; } private void flip(int[] row) { for (int i = 0; i < row.length; ++i) row[i] ^= 1; } private int onesColCount(int[][] grid, int j) { int ones = 0; for (int i = 0; i < grid.length; ++i) ones += grid[i][j]; return ones; } private void flipCol(int[][] grid, int j) { for (int i = 0; i < grid.length; ++i) grid[i][j] ^= 1; } private int binary(int[] row) { int res = row[0]; for (int j = 1; j < row.length; ++j) res = res * 2 + row[j]; return res; } }
class Solution { public: int matrixScore(vector<vector<int>>& grid) { const int m = grid.size(); const int n = grid[0].size(); int ans = 0; // Flip the rows with a leading 0. for (auto& row : grid) if (row[0] == 0) flip(row); // Flip the columns with 1s < 0s. for (int j = 0; j < n; ++j) if (onesColCount(grid, j) * 2 < m) flipCol(grid, j); // Add a binary number for each row. for (const vector<int>& row : grid) ans += binary(row); return ans; } private: void flip(vector<int>& row) { for (int i = 0; i < row.size(); ++i) row[i] ^= 1; } int onesColCount(const vector<vector<int>>& grid, int j) { int ones = 0; for (int i = 0; i < grid.size(); ++i) ones += grid[i][j]; return ones; } void flipCol(vector<vector<int>>& grid, int j) { for (int i = 0; i < grid.size(); ++i) grid[i][j] ^= 1; } int binary(const vector<int>& row) { int res = row[0]; for (int j = 1; j < row.size(); ++j) res = res * 2 + row[j]; return res; } };
866
Prime Palindrome
2
primePalindrome
Given an integer n, return the smallest prime palindrome greater than or equal to `n`. An integer is prime if it has exactly two divisors: `1` and itself. Note that `1` is not a prime number. * For example, `2`, `3`, `5`, `7`, `11`, and `13` are all primes. An integer is a palindrome if it reads the same from left to right as it does from right to left. * For example, `101` and `12321` are palindromes. The test cases are generated so that the answer always exists and is in the range `[2, 2 * 108]`.
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 primePalindrome(self, n: int) -> int: def getPalindromes(n: int): length = n // 2 for i in range(10**(length - 1), 10**length): s = str(i) for j in range(10): yield int(s + str(j) + s[::-1]) def isPrime(num: int) -> bool: for i in range(2, int(num**0.5 + 1)): if num % i == 0: return False return True if n <= 2: return 2 if n == 3: return 3 if n <= 5: return 5 if n <= 7: return 7 if n <= 11: return 11 nLength = len(str(n)) while True: for num in getPalindromes(nLength): if num >= n and isPrime(num): return num nLength += 1
class Solution { public int primePalindrome(int n) { if (n <= 2) return 2; if (n == 3) return 3; if (n <= 5) return 5; if (n <= 7) return 7; if (n <= 11) return 11; int nLength = String.valueOf(n).length(); while (true) { for (final int num : getPalindromes(nLength)) if (num >= n && isPrime(num)) return num; ++nLength; } } private List<Integer> getPalindromes(int n) { List<Integer> palindromes = new ArrayList<>(); int length = n / 2; for (int i = (int) Math.pow(10, length - 1); i < (int) Math.pow(10, length); ++i) { String s = String.valueOf(i); String reversedS = new StringBuilder(s).reverse().toString(); for (int j = 0; j < 10; ++j) palindromes.add(Integer.valueOf(s + String.valueOf(j) + reversedS)); } return palindromes; } private boolean isPrime(int num) { for (int i = 2; i < (int) Math.sqrt(num) + 1; ++i) if (num % i == 0) return false; return true; } }
class Solution { public: int primePalindrome(int n) { if (n <= 2) return 2; if (n == 3) return 3; if (n <= 5) return 5; if (n <= 7) return 7; if (n <= 11) return 11; int nLength = to_string(n).length(); while (true) { for (const int num : getPalindromes(nLength)) if (num >= n && isPrime(num)) return num; ++nLength; } throw; } private: vector<int> getPalindromes(int n) { vector<int> palindromes; const int length = n / 2; for (int i = pow(10, length - 1); i < pow(10, length); ++i) { const string s = to_string(i); string reversedS = s; ranges::reverse(reversedS); for (int j = 0; j < 10; ++j) palindromes.push_back(stoi(s + to_string(j) + reversedS)); } return palindromes; } bool isPrime(int num) { for (int i = 2; i < sqrt(num) + 1; ++i) if (num % i == 0) return false; return true; } };
882
Reachable Nodes In Subdivided Graph
3
reachableNodes
You are given an undirected graph (the "original graph") with `n` nodes labeled from `0` to `n - 1`. You decide to subdivide each edge in the graph into a chain of nodes, with the number of new nodes varying between each edge. The graph is given as a 2D array of `edges` where `edges[i] = [ui, vi, cnti]` indicates that there is an edge between nodes `ui` and `vi` in the original graph, and `cnti` is the total number of new nodes that you will subdivide the edge into. Note that `cnti == 0` means you will not subdivide the edge. To subdivide the edge `[ui, vi]`, replace it with `(cnti + 1)` new edges and `cnti` new nodes. The new nodes are `x1`, `x2`, ..., `xcnti`, and the new edges are `[ui, x1]`, `[x1, x2]`, `[x2, x3]`, ..., `[xcnti-1, xcnti]`, `[xcnti, vi]`. In this new graph, you want to know how many nodes are reachable from the node `0`, where a node is reachable if the distance is `maxMoves` or less. Given the original graph and `maxMoves`, return the number of nodes that are reachable from node `0` in the new graph.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def reachableNodes(self, edges: List[List[int]], maxMoves: int, n: int) -> int: graph = [[] for _ in range(n)] dist = [maxMoves + 1] * n for u, v, cnt in edges: graph[u].append((v, cnt)) graph[v].append((u, cnt)) reachableNodes = self._dijkstra(graph, 0, maxMoves, dist) reachableSubnodes = 0 for u, v, cnt in edges: a = 0 if dist[u] > maxMoves else min(maxMoves - dist[u], cnt) b = 0 if dist[v] > maxMoves else min(maxMoves - dist[v], cnt) reachableSubnodes += min(a + b, cnt) return reachableNodes + reachableSubnodes def _dijkstra(self, graph: List[List[Tuple[int, int]]], src: int, maxMoves: int, dist: List[int]) -> int: dist[src] = 0 minHeap = [(dist[src], src)] while minHeap: d, u = heapq.heappop(minHeap) if dist[u] >= maxMoves: break if d > dist[u]: continue for v, w in graph[u]: newDist = d + w + 1 if newDist < dist[v]: dist[v] = newDist heapq.heappush(minHeap, (newDist, v)) return sum(d <= maxMoves for d in dist)
class Solution { public int reachableNodes(int[][] edges, int maxMoves, int n) { List<Pair<Integer, Integer>>[] graph = new List[n]; int[] dist = new int[n]; Arrays.fill(dist, maxMoves + 1); Arrays.setAll(graph, i -> new ArrayList<>()); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; final int cnt = edge[2]; graph[u].add(new Pair<>(v, cnt)); graph[v].add(new Pair<>(u, cnt)); } final int reachableNodes = dijkstra(graph, 0, maxMoves, dist); int reachableSubnodes = 0; for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; final int cnt = edge[2]; // the number of reachable nodes of `edge` from `u` final int a = dist[u] > maxMoves ? 0 : Math.min(maxMoves - dist[u], cnt); // the number of reachable nodes of `edge` from `v` final int b = dist[v] > maxMoves ? 0 : Math.min(maxMoves - dist[v], cnt); reachableSubnodes += Math.min(a + b, cnt); } return reachableNodes + reachableSubnodes; } private int dijkstra(List<Pair<Integer, Integer>>[] graph, int src, int maxMoves, int[] dist) { 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(); // Already took `maxMoves` to reach `u`, so can't explore anymore. if (d >= maxMoves) break; 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 + 1 < dist[v]) { dist[v] = d + w + 1; minHeap.offer(new Pair<>(dist[v], v)); } } } return (int) Arrays.stream(dist).filter(d -> d <= maxMoves).count(); } }
class Solution { public: int reachableNodes(vector<vector<int>>& edges, int maxMoves, int n) { vector<vector<pair<int, int>>> graph(n); vector<int> dist(graph.size(), maxMoves + 1); for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; const int cnt = edge[2]; graph[u].emplace_back(v, cnt); graph[v].emplace_back(u, cnt); } const int reachableNodes = dijkstra(graph, 0, maxMoves, dist); int reachableSubnodes = 0; for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; const int cnt = edge[2]; // the number of reachable nodes of `edge` from `u` const int a = dist[u] > maxMoves ? 0 : min(maxMoves - dist[u], cnt); // the number of reachable nodes of `edge` from `v` const int b = dist[v] > maxMoves ? 0 : min(maxMoves - dist[v], cnt); reachableSubnodes += min(a + b, cnt); } return reachableNodes + reachableSubnodes; } private: int dijkstra(const vector<vector<pair<int, int>>>& graph, int src, int maxMoves, vector<int>& dist) { 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(); // Already took `maxMoves` to reach `u`, so can't explore anymore. if (d >= maxMoves) break; if (d > dist[u]) continue; for (const auto& [v, w] : graph[u]) if (d + w + 1 < dist[v]) { dist[v] = d + w + 1; minHeap.emplace(dist[v], v); } } return ranges::count_if(dist, [&](int d) { return d <= maxMoves; }); } };
909
Snakes and Ladders
2
snakesAndLadders
You are given an `n x n` integer matrix `board` where the cells are labeled from `1` to `n2` in a Boustrophedon style starting from the bottom left of the board (i.e. `board[n - 1][0]`) and alternating direction each row. You start on square `1` of the board. In each move, starting from square `curr`, do the following: * Choose a destination square `next` with a label in the range `[curr + 1, min(curr + 6, n2)]`. * This choice simulates the result of a standard 6-sided die roll: i.e., there are always at most 6 destinations, regardless of the size of the board. * If `next` has a snake or ladder, you must move to the destination of that snake or ladder. Otherwise, you move to `next`. * The game ends when you reach the square `n2`. A board square on row `r` and column `c` has a snake or ladder if `board[r][c] != -1`. The destination of that snake or ladder is `board[r][c]`. Squares `1` and `n2` do not have a snake or ladder. Note that you only take a snake or ladder at most once per move. If the destination to a snake or ladder is the start of another snake or ladder, you do not follow the subsequent snake or ladder. * For example, suppose the board is `[[-1,4],[-1,3]]`, and on the first move, your destination square is `2`. You follow the ladder to square `3`, but do not follow the subsequent ladder to `4`. Return the least number of moves required to reach the square `n2`. If it is not possible to reach the square, 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 snakesAndLadders(self, board: List[List[int]]) -> int: n = len(board) ans = 0 q = collections.deque([1]) seen = set() A = [0] * (1 + n * n) for i in range(n): for j in range(n): if n - i & 1 : A[(n - 1 - i) * n + (j + 1)] = board[i][j] else: A[(n - 1 - i) * n + (n - j)] = board[i][j] while q: ans += 1 for _ in range(len(q)): curr = q.popleft() for next in range(curr + 1, min(curr + 6, n * n) + 1): dest = A[next] if A[next] > 0 else next if dest == n * n: return ans if dest in seen: continue q.append(dest) seen.add(dest) return -1
class Solution { public int snakesAndLadders(int[][] board) { final int n = board.length; Queue<Integer> q = new ArrayDeque<>(List.of(1)); boolean[] seen = new boolean[1 + n * n]; int[] arr = new int[1 + n * n]; // 2D -> 1D for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) arr[(n - 1 - i) * n + ((n - i) % 2 == 0 ? n - j : j + 1)] = board[i][j]; for (int step = 1; !q.isEmpty(); ++step) for (int sz = q.size(); sz > 0; --sz) { final int curr = q.poll(); for (int next = curr + 1; next <= Math.min(curr + 6, n * n); ++next) { final int dest = arr[next] > 0 ? arr[next] : next; if (dest == n * n) return step; if (seen[dest]) continue; q.offer(dest); seen[dest] = true; } } return -1; } }
class Solution { public: int snakesAndLadders(vector<vector<int>>& board) { const int n = board.size(); queue<int> q{{1}}; vector<bool> seen(1 + n * n); vector<int> arr(1 + n * n); // 2D -> 1D for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) arr[(n - 1 - i) * n + ((n - i) % 2 == 0 ? n - j : j + 1)] = board[i][j]; for (int step = 1; !q.empty(); ++step) for (int sz = q.size(); sz > 0; --sz) { const int curr = q.front(); q.pop(); for (int next = curr + 1; next <= min(curr + 6, n * n); ++next) { const int dest = arr[next] > 0 ? arr[next] : next; if (dest == n * n) return step; if (seen[dest]) continue; q.push(dest); seen[dest] = true; } } return -1; } };
913
Cat and Mouse
3
catMouseGame
A game on an undirected graph is played by two players, Mouse and Cat, who alternate turns. The graph is given as follows: `graph[a]` is a list of all nodes `b` such that `ab` is an edge of the graph. The mouse starts at node `1` and goes first, the cat starts at node `2` and goes second, and there is a hole at node `0`. During each player's turn, they must travel along one edge of the graph that meets where they are. For example, if the Mouse is at node 1, it must travel to any node in `graph[1]`. Additionally, it is not allowed for the Cat to travel to the Hole (node `0`). Then, the game can end in three ways: * If ever the Cat occupies the same node as the Mouse, the Cat wins. * If ever the Mouse reaches the Hole, the Mouse wins. * If ever a position is repeated (i.e., the players are in the same position as a previous turn, and it is the same player's turn to move), the game is a draw. Given a `graph`, and assuming both players play optimally, return * `1` if the mouse wins the game, * `2` if the cat wins the game, or * `0` if the game is a draw.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator from enum import IntEnum class State(IntEnum): kDraw = 0 kMouseWin = 1 kCatWin = 2 class Solution: def catMouseGame(self, graph: List[List[int]]) -> int: n = len(graph) states = [[[0] * 2 for i in range(n)] for j in range(n)] outDegree = [[[0] * 2 for i in range(n)] for j in range(n)] q = collections.deque() for cat in range(n): for mouse in range(n): outDegree[cat][mouse][0] = len(graph[mouse]) outDegree[cat][mouse][1] = len(graph[cat]) - graph[cat].count(0) for cat in range(1, n): for move in range(2): states[cat][0][move] = int(State.kMouseWin) q.append((cat, 0, move, int(State.kMouseWin))) states[cat][cat][move] = int(State.kCatWin) q.append((cat, cat, move, int(State.kCatWin))) while q: cat, mouse, move, state = q.popleft() if cat == 2 and mouse == 1 and move == 0: return state prevMove = move ^ 1 for prev in graph[cat if prevMove else mouse]: prevCat = prev if prevMove else cat if prevCat == 0: continue prevMouse = mouse if prevMove else prev if states[prevCat][prevMouse][prevMove]: continue if prevMove == 0 and state == int(State.kMouseWin) or \ prevMove == 1 and state == int(State.kCatWin): states[prevCat][prevMouse][prevMove] = state q.append((prevCat, prevMouse, prevMove, state)) else: outDegree[prevCat][prevMouse][prevMove] -= 1 if outDegree[prevCat][prevMouse][prevMove] == 0: states[prevCat][prevMouse][prevMove] = state q.append((prevCat, prevMouse, prevMove, state)) return states[2][1][0]
enum State { DRAW, MOUSE_WIN, CAT_WIN } class Solution { public int catMouseGame(int[][] graph) { final int n = graph.length; // result of (cat, mouse, move) // move := 0 (mouse) / 1 (cat) int[][][] states = new int[n][n][2]; int[][][] outDegree = new int[n][n][2]; Queue<int[]> q = new ArrayDeque<>(); for (int cat = 0; cat < n; ++cat) for (int mouse = 0; mouse < n; ++mouse) { outDegree[cat][mouse][0] = graph[mouse].length; outDegree[cat][mouse][1] = graph[cat].length - (Arrays.stream(graph[cat]).anyMatch(v -> v == 0) ? 1 : 0); } // Start from the states s.t. the winner can be determined. for (int cat = 1; cat < n; ++cat) for (int move = 0; move < 2; ++move) { // Mouse is in the hole. states[cat][0][move] = State.MOUSE_WIN.ordinal(); q.offer(new int[] {cat, 0, move, State.MOUSE_WIN.ordinal()}); // Cat catches mouse. states[cat][cat][move] = State.CAT_WIN.ordinal(); q.offer(new int[] {cat, cat, move, State.CAT_WIN.ordinal()}); } while (!q.isEmpty()) { final int cat = q.peek()[0]; final int mouse = q.peek()[1]; final int move = q.peek()[2]; final int state = q.poll()[3]; if (cat == 2 && mouse == 1 && move == 0) return state; final int prevMove = move ^ 1; for (final int prev : graph[prevMove == 0 ? mouse : cat]) { final int prevCat = prevMove == 0 ? cat : prev; if (prevCat == 0) // invalid continue; final int prevMouse = prevMove == 0 ? prev : mouse; // The state has been determined. if (states[prevCat][prevMouse][prevMove] > 0) continue; if (prevMove == 0 && state == State.MOUSE_WIN.ordinal() || prevMove == 1 && state == State.CAT_WIN.ordinal() || --outDegree[prevCat][prevMouse][prevMove] == 0) { states[prevCat][prevMouse][prevMove] = state; q.offer(new int[] {prevCat, prevMouse, prevMove, state}); } } } return states[2][1][0]; } }
enum class State { kDraw, kMouseWin, kCatWin }; class Solution { public: int catMouseGame(vector<vector<int>>& graph) { const int n = graph.size(); // result of (cat, mouse, move) // move := 0 (mouse) / 1 (cat) vector<vector<vector<State>>> states( n, vector<vector<State>>(n, vector<State>(2))); vector<vector<vector<int>>> outDegree( n, vector<vector<int>>(n, vector<int>(2))); queue<tuple<int, int, int, State>> q; // (cat, mouse, move, state) for (int cat = 0; cat < n; ++cat) for (int mouse = 0; mouse < n; ++mouse) { outDegree[cat][mouse][0] = graph[mouse].size(); outDegree[cat][mouse][1] = graph[cat].size() - ranges::count(graph[cat], 0); } // Start from the states s.t. the winner can be determined. for (int cat = 1; cat < n; ++cat) for (int move = 0; move < 2; ++move) { // Mouse is in the hole. states[cat][0][move] = State::kMouseWin; q.emplace(cat, 0, move, State::kMouseWin); // Cat catches mouse. states[cat][cat][move] = State::kCatWin; q.emplace(cat, cat, move, State::kCatWin); } while (!q.empty()) { const auto [cat, mouse, move, state] = q.front(); q.pop(); if (cat == 2 && mouse == 1 && move == 0) return static_cast<int>(state); const int prevMove = move ^ 1; for (const int prev : graph[prevMove ? cat : mouse]) { const int prevCat = prevMove ? prev : cat; if (prevCat == 0) // invalid continue; const int prevMouse = prevMove ? mouse : prev; // The state has been determined. if (states[prevCat][prevMouse][prevMove] != State::kDraw) continue; if (prevMove == 0 && state == State::kMouseWin || prevMove == 1 && state == State::kCatWin || --outDegree[prevCat][prevMouse][prevMove] == 0) { states[prevCat][prevMouse][prevMove] = state; q.emplace(prevCat, prevMouse, prevMove, state); } } } return static_cast<int>(states[2][1][0]); } };
923
3Sum With Multiplicity
2
threeSumMulti
Given an integer array `arr`, and an integer `target`, return the number of tuples `i, j, k` such that `i < j < k` and `arr[i] + arr[j] + arr[k] == target`. As the answer can be very large, return it modulo `109 + 7`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def threeSumMulti(self, arr: List[int], target: int) -> int: kMod = 1_000_000_007 ans = 0 count = collections.Counter(arr) for i, x in count.items(): for j, y in count.items(): k = target - i - j if k not in count: continue if i == j and j == k: ans = (ans + x * (x - 1) * (x - 2) // 6) % kMod elif i == j and j != k: ans = (ans + x * (x - 1) // 2 * count[k]) % kMod elif i < j and j < k: ans = (ans + x * y * count[k]) % kMod return ans % kMod
class Solution { public int threeSumMulti(int[] arr, int target) { final int MOD = 1_000_000_007; int ans = 0; Map<Integer, Integer> count = new HashMap<>(); for (final int a : arr) count.merge(a, 1, Integer::sum); for (Map.Entry<Integer, Integer> entry : count.entrySet()) { final int i = entry.getKey(); final int x = entry.getValue(); for (Map.Entry<Integer, Integer> entry2 : count.entrySet()) { final int j = entry2.getKey(); final int y = entry2.getValue(); final int k = target - i - j; if (!count.containsKey(k)) continue; if (i == j && j == k) ans = (int) ((ans + (long) x * (x - 1) * (x - 2) / 6) % MOD); else if (i == j && j != k) ans = (int) ((ans + (long) x * (x - 1) / 2 * count.get(k)) % MOD); else if (i < j && j < k) ans = (int) ((ans + (long) x * y * count.get(k)) % MOD); } } return ans; } }
class Solution { public: int threeSumMulti(vector<int>& arr, int target) { constexpr int kMod = 1'000'000'007; int ans = 0; unordered_map<int, int> count; for (const int a : arr) ++count[a]; for (const auto& [i, x] : count) for (const auto& [j, y] : count) { const int k = target - i - j; const auto it = count.find(k); if (it == count.cend()) continue; if (i == j && j == k) ans = (ans + static_cast<long>(x) * (x - 1) * (x - 2) / 6) % kMod; else if (i == j && j != k) ans = (ans + static_cast<long>(x) * (x - 1) / 2 * it->second) % kMod; else if (i < j && j < k) ans = (ans + static_cast<long>(x) * y * it->second) % kMod; } return ans; } };
927
Three Equal Parts
3
threeEqualParts
You are given an array `arr` which consists of only zeros and ones, divide the array into three non-empty parts such that all of these parts represent the same binary value. If it is possible, return any `[i, j]` with `i + 1 < j`, such that: * `arr[0], arr[1], ..., arr[i]` is the first part, * `arr[i + 1], arr[i + 2], ..., arr[j - 1]` is the second part, and * `arr[j], arr[j + 1], ..., arr[arr.length - 1]` is the third part. * All three parts have equal binary values. If it is not possible, return `[-1, -1]`. Note that the entire part is used when considering what binary value it represents. For example, `[1,1,0]` represents `6` in decimal, not `3`. Also, leading zeros are allowed, so `[0,1,1]` and `[1,1]` represent the same value.
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 threeEqualParts(self, arr: List[int]) -> List[int]: ones = sum(a == 1 for a in arr) if ones == 0: return [0, len(arr) - 1] if ones % 3 != 0: return [-1, -1] k = ones // 3 i = 0 for i in range(len(arr)): if arr[i] == 1: first = i break gapOnes = k for j in range(i + 1, len(arr)): if arr[j] == 1: gapOnes -= 1 if gapOnes == 0: second = j break gapOnes = k for i in range(j + 1, len(arr)): if arr[i] == 1: gapOnes -= 1 if gapOnes == 0: third = i break while third < len(arr) and arr[first] == arr[second] == arr[third]: first += 1 second += 1 third += 1 if third == len(arr): return [first - 1, second] return [-1, -1]
class Solution { public int[] threeEqualParts(int[] arr) { int ones = 0; for (final int a : arr) if (a == 1) ++ones; if (ones == 0) return new int[] {0, arr.length - 1}; if (ones % 3 != 0) return new int[] {-1, -1}; int k = ones / 3; int i = 0; int j = 0; int first = 0; int second = 0; int third = 0; for (i = 0; i < arr.length; ++i) if (arr[i] == 1) { first = i; break; } int gapOnes = k; for (j = i + 1; j < arr.length; ++j) if (arr[j] == 1 && --gapOnes == 0) { second = j; break; } gapOnes = k; for (i = j + 1; i < arr.length; ++i) if (arr[i] == 1 && --gapOnes == 0) { third = i; break; } while (third < arr.length && arr[first] == arr[second] && arr[second] == arr[third]) { ++first; ++second; ++third; } if (third == arr.length) return new int[] {first - 1, second}; return new int[] {-1, -1}; } }
class Solution { public: vector<int> threeEqualParts(vector<int>& arr) { const int ones = ranges::count_if(arr, [](int a) { return a == 1; }); if (ones == 0) return {0, static_cast<int>(arr.size()) - 1}; if (ones % 3 != 0) return {-1, -1}; int k = ones / 3; int i; int j; int first; int second; int third; for (i = 0; i < arr.size(); ++i) if (arr[i] == 1) { first = i; break; } int gapOnes = k; for (j = i + 1; j < arr.size(); ++j) if (arr[j] == 1 && --gapOnes == 0) { second = j; break; } gapOnes = k; for (i = j + 1; i < arr.size(); ++i) if (arr[i] == 1 && --gapOnes == 0) { third = i; break; } while (third < arr.size() && arr[first] == arr[second] && arr[second] == arr[third]) { ++first; ++second; ++third; } if (third == arr.size()) return {first - 1, second}; return {-1, -1}; } };
935
Knight Dialer
2
knightDialer
The chess knight has a unique movement, it may move two squares vertically and one square horizontally, or two squares horizontally and one square vertically (with both forming the shape of an L). The possible movements of chess knight are shown in this diagram: A chess knight can move as indicated in the chess diagram below: We have a chess knight and a phone pad as shown below, the knight can only stand on a numeric cell (i.e. blue cell). Given an integer `n`, return how many distinct phone numbers of length `n` we can dial. You are allowed to place the knight on any numeric cell initially and then you should perform `n - 1` jumps to dial a number of length `n`. All jumps should be valid knight jumps. As the answer may be very large, return the answer modulo `109 + 7`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def knightDialer(self, n: int) -> int: dirs = ((1, 2), (2, 1), (2, -1), (1, -2), (-1, -2), (-2, -1), (-2, 1), (-1, 2)) kMod = 1_000_000_007 dp = [[1] * 3 for _ in range(4)] dp[3][0] = dp[3][2] = 0 for _ in range(n - 1): newDp = [[0] * 3 for _ in range(4)] for i in range(4): for j in range(3): if (i, j) in ((3, 0), (3, 2)): continue for dx, dy in dirs: x = i + dx y = j + dy if x < 0 or x >= 4 or y < 0 or y >= 3: continue if (x, y) in ((3, 0), (3, 2)): continue newDp[x][y] = (newDp[x][y] + dp[i][j]) % kMod dp = newDp return sum(map(sum, dp)) % kMod
class Solution { public int knightDialer(int n) { final int[][] DIRS = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}}; final int MOD = 1_000_000_007; // dp[i][j] := the number of ways to stand on (i, j) int[][] dp = new int[4][3]; Arrays.stream(dp).forEach(A -> Arrays.fill(A, 1)); dp[3][0] = dp[3][2] = 0; for (int k = 0; k < n - 1; ++k) { int[][] newDp = new int[4][3]; for (int i = 0; i < 4; ++i) for (int j = 0; j < 3; ++j) { if (isNotNumericCell(i, j)) continue; for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x >= 4 || y < 0 || y >= 3) continue; if (isNotNumericCell(x, y)) continue; newDp[i][j] = (newDp[i][j] + dp[x][y]) % MOD; } } dp = newDp; } int ans = 0; for (int[] row : dp) for (final int a : row) ans = (ans + a) % MOD; return ans; } private boolean isNotNumericCell(int i, int j) { return i == 3 && (j == 0 || j == 2); } }
class Solution { public: int knightDialer(int n) { constexpr int kDirs[8][2] = {{1, 2}, {2, 1}, {2, -1}, {1, -2}, {-1, -2}, {-2, -1}, {-2, 1}, {-1, 2}}; constexpr int kMod = 1'000'000'007; // dp[i][j] := the number of ways to stand on (i, j) vector<vector<int>> dp(4, vector<int>(3, 1)); dp[3][0] = dp[3][2] = 0; for (int k = 0; k < n - 1; ++k) { vector<vector<int>> newDp(4, vector<int>(3)); for (int i = 0; i < 4; ++i) for (int j = 0; j < 3; ++j) { if (isNotNumericCell(i, j)) continue; for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x >= 4 || y < 0 || y >= 3) continue; if (isNotNumericCell(x, y)) continue; newDp[i][j] = (newDp[i][j] + dp[x][y]) % kMod; } } dp = std::move(newDp); } int ans = 0; for (const vector<int>& row : dp) for (const int a : row) ans = (ans + a) % kMod; return ans; } private: bool isNotNumericCell(int i, int j) { return i == 3 && (j == 0 || j == 2); } };
939
Minimum Area Rectangle
2
minAreaRect
You are given an array of points in the X-Y plane `points` where `points[i] = [xi, yi]`. Return the minimum area of a rectangle formed from these points, with sides parallel to the X and Y axes. If there is not any such rectangle, return `0`.
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 minAreaRect(self, points: List[List[int]]) -> int: ans = math.inf xToYs = collections.defaultdict(set) for x, y in points: xToYs[x].add(y) for i in range(len(points)): for j in range(i): x1, y1 = points[i] x2, y2 = points[j] if x1 == x2 or y1 == y2: continue if y2 in xToYs[x1] and y1 in xToYs[x2]: ans = min(ans, abs(x1 - x2) * abs(y1 - y2)) return ans if ans < math.inf else 0
class Solution { public int minAreaRect(int[][] points) { int ans = Integer.MAX_VALUE; Map<Integer, Set<Integer>> xToYs = new HashMap<>(); for (int[] p : points) { xToYs.putIfAbsent(p[0], new HashSet<>()); xToYs.get(p[0]).add(p[1]); } for (int i = 1; i < points.length; ++i) for (int j = 0; j < i; ++j) { int[] p = points[i]; int[] q = points[j]; if (p[0] == q[0] || p[1] == q[1]) continue; if (xToYs.get(p[0]).contains(q[1]) && xToYs.get(q[0]).contains(p[1])) ans = Math.min(ans, Math.abs(p[0] - q[0]) * Math.abs(p[1] - q[1])); } return ans == Integer.MAX_VALUE ? 0 : ans; } }
class Solution { public: int minAreaRect(vector<vector<int>>& points) { int ans = INT_MAX; unordered_map<int, unordered_set<int>> xToYs; for (const vector<int>& p : points) xToYs[p[0]].insert(p[1]); for (int i = 1; i < points.size(); ++i) for (int j = 0; j < i; ++j) { const vector<int>& p = points[i]; const vector<int>& q = points[j]; if (p[0] == q[0] || p[1] == q[1]) continue; if (xToYs[p[0]].contains(q[1]) && xToYs[q[0]].contains(p[1])) ans = min(ans, abs(p[0] - q[0]) * abs(p[1] - q[1])); } return ans == INT_MAX ? 0 : ans; } };
952
Largest Component Size by Common Factor
3
largestComponentSize
You are given an integer array of unique positive integers `nums`. Consider the following graph: * There are `nums.length` nodes, labeled `nums[0]` to `nums[nums.length - 1]`, * There is an undirected edge between `nums[i]` and `nums[j]` if `nums[i]` and `nums[j]` share a common factor greater than `1`. Return the size of the largest connected component in the graph.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class UnionFind: def __init__(self, n: int): self.id = list(range(n)) self.rank = [0] * n def unionByRank(self, u: int, v: int) -> None: i = self.find(u) j = self.find(v) if i == j: return if self.rank[i] < self.rank[j]: self.id[i] = j elif self.rank[i] > self.rank[j]: self.id[j] = i else: self.id[i] = j self.rank[j] += 1 def find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self.find(self.id[u]) return self.id[u] class Solution: def largestComponentSize(self, nums: List[int]) -> int: ans = 0 uf = UnionFind(max(nums) + 1) count = collections.Counter() for num in nums: for x in range(2, int(math.sqrt(num) + 1)): if num % x == 0: uf.unionByRank(num, x) uf.unionByRank(num, num // x) for num in nums: numRoot = uf.find(num) count[numRoot] += 1 ans = max(ans, count[numRoot]) return ans
class UnionFind { public UnionFind(int n) { id = new int[n]; rank = new int[n]; for (int i = 0; i < n; ++i) id[i] = i; } public void unionByRank(int u, int v) { final int i = find(u); final int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } public int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } private int[] id; private int[] rank; } class Solution { public int largestComponentSize(int[] nums) { final int n = Arrays.stream(nums).max().getAsInt(); int ans = 0; UnionFind uf = new UnionFind(n + 1); Map<Integer, Integer> count = new HashMap<>(); for (final int num : nums) for (int x = 2; x <= (int) Math.sqrt(num); ++x) if (num % x == 0) { uf.unionByRank(num, x); uf.unionByRank(num, num / x); } for (final int num : nums) ans = Math.max(ans, count.merge(uf.find(num), 1, Integer::sum)); return ans; } }
class UnionFind { public: UnionFind(int n) : id(n), rank(n) { iota(id.begin(), id.end(), 0); } void unionByRank(int u, int v) { const int i = find(u); const int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } private: vector<int> id; vector<int> rank; }; class Solution { public: int largestComponentSize(vector<int>& nums) { const int n = ranges::max(nums); int ans = 0; UnionFind uf(n + 1); unordered_map<int, int> count; for (const int num : nums) for (int x = 2; x <= sqrt(num); ++x) if (num % x == 0) { uf.unionByRank(num, x); uf.unionByRank(num, num / x); } for (const int num : nums) ans = max(ans, ++count[uf.find(num)]); return ans; } };
963
Minimum Area Rectangle II
2
minAreaFreeRect
You are given an array of points in the X-Y plane `points` where `points[i] = [xi, yi]`. Return the minimum area of any rectangle formed from these points, with sides not necessarily parallel to the X and Y axes. If there is not any such rectangle, return `0`. Answers within `10-5` of the actual answer will be accepted.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator from math import sqrt class Solution: def minAreaFreeRect(self, points: List[List[int]]) -> float: ans = math.inf centerToPoints = collections.defaultdict(list) for ax, ay in points: for bx, by in points: center = ((ax + bx) / 2, (ay + by) / 2) centerToPoints[center].append((ax, ay, bx, by)) def dist(px: int, py: int, qx: int, qy: int) -> float: return (px - qx)**2 + (py - qy)**2 for points in centerToPoints.values(): for ax, ay, _, _ in points: for cx, cy, dx, dy in points: if (cx - ax) * (dx - ax) + (cy - ay) * (dy - ay) == 0: squaredArea = dist(ax, ay, cx, cy) * dist(ax, ay, dx, dy) if squaredArea > 0: ans = min(ans, squaredArea) return 0 if ans == math.inf else sqrt(ans)
class Solution { public double minAreaFreeRect(int[][] points) { long ans = Long.MAX_VALUE; // For each A, B pair points, {hash(A, B): (ax, ay, bx, by)}. Map<Integer, List<int[]>> centerToPoints = new HashMap<>(); for (int[] A : points) for (int[] B : points) { int center = hash(A, B); if (centerToPoints.get(center) == null) centerToPoints.put(center, new ArrayList<>()); centerToPoints.get(center).add(new int[] {A[0], A[1], B[0], B[1]}); } // For all pair points "that share the same center". for (List<int[]> pointPairs : centerToPoints.values()) for (int[] ab : pointPairs) for (int[] cd : pointPairs) { final int ax = ab[0], ay = ab[1]; final int cx = cd[0], cy = cd[1]; final int dx = cd[2], dy = cd[3]; // AC is perpendicular to AD. // AC dot AD = (cx - ax, cy - ay) dot (dx - ax, dy - ay) == 0. if ((cx - ax) * (dx - ax) + (cy - ay) * (dy - ay) == 0) { final long squaredArea = dist(ax, ay, cx, cy) * dist(ax, ay, dx, dy); if (squaredArea > 0) ans = Math.min(ans, squaredArea); } } return ans == Long.MAX_VALUE ? 0 : Math.sqrt(ans); } private int hash(int[] p, int[] q) { return ((p[0] + q[0]) << 16) + (p[1] + q[1]); } private long dist(long px, long py, long qx, long qy) { return (px - qx) * (px - qx) + (py - qy) * (py - qy); } }
class Solution { public: double minAreaFreeRect(vector<vector<int>>& points) { long ans = LONG_MAX; // For each A, B pair points, {hash(A, B): (ax, ay, bx, by)}. unordered_map<int, vector<tuple<int, int, int, int>>> centerToPoints; for (const vector<int>& A : points) for (const vector<int>& B : points) { const int center = hash(A, B); centerToPoints[center].emplace_back(A[0], A[1], B[0], B[1]); } // For all pair points "that share the same center". for (const auto& [_, points] : centerToPoints) for (const auto& [ax, ay, bx, by] : points) for (const auto& [cx, cy, dx, dy] : points) // AC is perpendicular to AD. // AC dot AD = (cx - ax, cy - ay) dot (dx - ax, dy - ay) == 0. if ((cx - ax) * (dx - ax) + (cy - ay) * (dy - ay) == 0) { const long squaredArea = dist(ax, ay, cx, cy) * dist(ax, ay, dx, dy); if (squaredArea > 0) ans = min(ans, squaredArea); } return ans == LONG_MAX ? 0 : sqrt(ans); } private: int hash(const vector<int>& p, const vector<int>& q) { return ((long)(p[0] + q[0]) << 16) + (p[1] + q[1]); } long dist(int px, int py, int qx, int qy) { return (px - qx) * (px - qx) + (py - qy) * (py - qy); } };
990
Satisfiability of Equality Equations
2
equationsPossible
You are given an array of strings `equations` that represent relationships between variables where each string `equations[i]` is of length `4` and takes one of two different forms: `"xi==yi"` or `"xi!=yi"`.Here, `xi` and `yi` are lowercase letters (not necessarily different) that represent one-letter variable names. Return `true` if it is possible to assign integers to variable names so as to satisfy all the given equations, or `false` otherwise.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class UnionFind: def __init__(self, n: int): self.id = list(range(n)) def union(self, u: int, v: int) -> None: self.id[self.find(u)] = self.find(v) 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 equationsPossible(self, equations: List[str]) -> bool: uf = UnionFind(26) for x, op, _, y in equations: if op == '=': uf.union(ord(x) - ord('a'), ord(y) - ord('a')) for x, op, _, y in equations: if op == '!': if uf.find(ord(x) - ord('a')) == uf.find(ord(y) - ord('a')): return False return True
class UnionFind { public UnionFind(int n) { id = new int[n]; rank = new int[n]; for (int i = 0; i < n; ++i) id[i] = i; } public void unionByRank(int u, int v) { final int i = find(u); final int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } public int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } private int[] id; private int[] rank; } class Solution { public boolean equationsPossible(String[] equations) { UnionFind uf = new UnionFind(26); for (final String e : equations) if (e.charAt(1) == '=') { final int x = e.charAt(0) - 'a'; final int y = e.charAt(3) - 'a'; uf.unionByRank(x, y); } for (final String e : equations) if (e.charAt(1) == '!') { final int x = e.charAt(0) - 'a'; final int y = e.charAt(3) - 'a'; if (uf.find(x) == uf.find(y)) return false; } return true; } }
class UnionFind { public: UnionFind(int n) : id(n) { iota(id.begin(), id.end(), 0); } void union_(int u, int v) { id[find(u)] = find(v); } int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } private: vector<int> id; }; class Solution { public: bool equationsPossible(vector<string>& equations) { UnionFind uf(26); for (const string& e : equations) if (e[1] == '=') { const int x = e[0] - 'a'; const int y = e[3] - 'a'; uf.union_(x, y); } for (const string& e : equations) if (e[1] == '!') { const int x = e[0] - 'a'; const int y = e[3] - 'a'; if (uf.find(x) == uf.find(y)) return false; } return true; } };
999
Available Captures for Rook
1
numRookCaptures
On an `8 x 8` chessboard, there is exactly one white rook `'R'` and some number of white bishops `'B'`, black pawns `'p'`, and empty squares `'.'`. When the rook moves, it chooses one of four cardinal directions (north, east, south, or west), then moves in that direction until it chooses to stop, reaches the edge of the board, captures a black pawn, or is blocked by a white bishop. A rook is considered attacking a pawn if the rook can capture the pawn on the rook's turn. The number of available captures for the white rook is the number of pawns that the rook is attacking. Return the number of available captures for the white rook.
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 numRookCaptures(self, board: List[List[str]]) -> int: ans = 0 for i in range(8): for j in range(8): if board[i][j] == 'R': i0 = i j0 = j for d in [[1, 0], [0, 1], [-1, 0], [0, -1]]: i = i0 + d[0] j = j0 + d[1] while 0 <= i < 8 and 0 <= j < 8: if board[i][j] == 'p': ans += 1 if board[i][j] != '.': break i += d[0] j += d[1] return ans
class Solution { public int numRookCaptures(char[][] board) { int ans = 0; int i0 = 0; int j0 = 0; for (int i = 0; i < 8; ++i) for (int j = 0; j < 8; ++j) if (board[i][j] == 'R') { i0 = i; j0 = j; } for (int[] d : new int[][] {{1, 0}, {0, 1}, {-1, 0}, {0, -1}}) for (int i = i0 + d[0], j = j0 + d[1]; 0 <= i && i < 8 && 0 <= j && j < 8; i += d[0], j += d[1]) { if (board[i][j] == 'p') ++ans; if (board[i][j] != '.') break; } return ans; } }
class Solution { public: int numRookCaptures(vector<vector<char>>& board) { int ans = 0; int i0 = 0; int j0 = 0; for (int i = 0; i < 8; ++i) for (int j = 0; j < 8; ++j) if (board[i][j] == 'R') { i0 = i; j0 = j; } for (const vector<int>& d : vector<vector<int>>({{1, 0}, {0, 1}, {-1, 0}, {0, -1}})) for (int i = i0 + d[0], j = j0 + d[1]; 0 <= i && i < 8 && 0 <= j && j < 8; i += d[0], j += d[1]) { if (board[i][j] == 'p') ++ans; if (board[i][j] != '.') break; } return ans; } };
1,001
Grid Illumination
3
gridIllumination
There is a 2D `grid` of size `n x n` where each cell of this grid has a lamp that is initially turned off. You are given a 2D array of lamp positions `lamps`, where `lamps[i] = [rowi, coli]` indicates that the lamp at `grid[rowi][coli]` is turned on. Even if the same lamp is listed more than once, it is turned on. When a lamp is turned on, it illuminates its cell and all other cells in the same row, column, or diagonal. You are also given another 2D array `queries`, where `queries[j] = [rowj, colj]`. For the `jth` query, determine whether `grid[rowj][colj]` is illuminated or not. After answering the `jth` query, turn off the lamp at `grid[rowj][colj]` and its 8 adjacent lamps if they exist. A lamp is adjacent if its cell shares either a side or corner with `grid[rowj][colj]`. Return an array of integers `ans`, where `ans[j]` should be `1` if the cell in the `jth` query was illuminated, or `0` if the lamp was 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 gridIllumination(self, n: int, lamps: List[List[int]], queries: List[List[int]]) -> List[int]: ans = [] rows = collections.Counter() cols = collections.Counter() diag1 = collections.Counter() diag2 = collections.Counter() lampsSet = set() for i, j in lamps: if (i, j) not in lampsSet: lampsSet.add((i, j)) rows[i] += 1 cols[j] += 1 diag1[i + j] += 1 diag2[i - j] += 1 for i, j in queries: if rows[i] or cols[j] or diag1[i + j] or diag2[i - j]: ans.append(1) for y in range(max(0, i - 1), min(n, i + 2)): for x in range(max(0, j - 1), min(n, j + 2)): if (y, x) in lampsSet: lampsSet.remove((y, x)) rows[y] -= 1 cols[x] -= 1 diag1[y + x] -= 1 diag2[y - x] -= 1 else: ans.append(0) return ans
class Solution { public int[] gridIllumination(int n, int[][] lamps, int[][] queries) { List<Integer> ans = new ArrayList<>(); Map<Integer, Integer> rows = new HashMap<>(); Map<Integer, Integer> cols = new HashMap<>(); Map<Integer, Integer> diag1 = new HashMap<>(); Map<Integer, Integer> diag2 = new HashMap<>(); Set<Long> lampsSet = new HashSet<>(); for (int[] lamp : lamps) { final int i = lamp[0]; final int j = lamp[1]; if (lampsSet.add(hash(i, j))) { rows.merge(i, 1, Integer::sum); cols.merge(j, 1, Integer::sum); diag1.merge(i + j, 1, Integer::sum); diag2.merge(i - j, 1, Integer::sum); } } for (int[] query : queries) { final int i = query[0]; final int j = query[1]; if (rows.getOrDefault(i, 0) > 0 || cols.getOrDefault(j, 0) > 0 || diag1.getOrDefault(i + j, 0) > 0 || diag2.getOrDefault(i - j, 0) > 0) { ans.add(1); for (int y = Math.max(0, i - 1); y < Math.min(n, i + 2); ++y) for (int x = Math.max(0, j - 1); x < Math.min(n, j + 2); ++x) if (lampsSet.remove(hash(y, x))) { rows.merge(y, 1, Integer::sum); cols.merge(x, 1, Integer::sum); diag1.merge(y + x, 1, Integer::sum); diag2.merge(y - x, 1, Integer::sum); } } else { ans.add(0); } } return ans.stream().mapToInt(Integer::intValue).toArray(); } private long hash(int i, int j) { return ((long) i << 32) + j; } }
class Solution { public: vector<int> gridIllumination(int n, vector<vector<int>>& lamps, vector<vector<int>>& queries) { vector<int> ans; unordered_map<int, int> rows; unordered_map<int, int> cols; unordered_map<int, int> diag1; unordered_map<int, int> diag2; unordered_set<pair<int, int>, PairHash> lampsSet; for (const vector<int>& lamp : lamps) { const int i = lamp[0]; const int j = lamp[1]; if (lampsSet.insert({i, j}).second) { ++rows[i]; ++cols[j]; ++diag1[i + j]; ++diag2[i - j]; } } for (const vector<int>& query : queries) { const int i = query[0]; const int j = query[1]; if (rows[i] || cols[j] || diag1[i + j] || diag2[i - j]) { ans.push_back(1); for (int y = max(0, i - 1); y < min(n, i + 2); ++y) for (int x = max(0, j - 1); x < min(n, j + 2); ++x) if (lampsSet.erase({y, x})) { --rows[y]; --cols[x]; --diag1[y + x]; --diag2[y - x]; } } else { ans.push_back(0); } } return ans; } private: struct PairHash { size_t operator()(const pair<int, int>& p) const { return p.first ^ p.second; } }; };
1,093
Statistics from a Large Sample
2
sampleStats
You are given a large sample of integers in the range `[0, 255]`. Since the sample is so large, it is represented by an array `count` where `count[k]` is the number of times that `k` appears in the sample. Calculate the following statistics: * `minimum`: The minimum element in the sample. * `maximum`: The maximum element in the sample. * `mean`: The average of the sample, calculated as the total sum of all elements divided by the total number of elements. * `median`: * If the sample has an odd number of elements, then the `median` is the middle element once the sample is sorted. * If the sample has an even number of elements, then the `median` is the average of the two middle elements once the sample is sorted. * `mode`: The number that appears the most in the sample. It is guaranteed to be unique. Return the statistics of the sample as an array of floating-point numbers `[minimum, maximum, mean, median, mode]`. Answers within `10-5` of the actual answer will be accepted.
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 sampleStats(self, count: List[int]) -> List[float]: minimum = next((i for i, num in enumerate(count) if num), None) maximum = next((i for i, num in reversed(list(enumerate(count))) if num), None) n = sum(count) mean = sum(i * c / n for i, c in enumerate(count)) mode = count.index(max(count)) numCount = 0 leftMedian = 0 for i, c in enumerate(count): numCount += c if numCount >= n / 2: leftMedian = i break numCount = 0 rightMedian = 0 for i, c in reversed(list(enumerate(count))): numCount += c if numCount >= n / 2: rightMedian = i break return [minimum, maximum, mean, (leftMedian + rightMedian) / 2, mode]
class Solution { public double[] sampleStats(int[] count) { final int n = Arrays.stream(count).sum(); return new double[] { getMinimum(count), // getMaximum(count), // getMean(count, n), // (getLeftMedian(count, n) + getRightMedian(count, n)) / 2.0, // getMode(count), }; } private double getMinimum(int[] count) { for (int i = 0; i < count.length; ++i) if (count[i] > 0) return i; return -1; } private double getMaximum(int[] count) { for (int i = count.length - 1; i >= 0; --i) if (count[i] > 0) return i; return -1; } private double getMean(int[] count, double n) { double mean = 0; for (int i = 0; i < count.length; ++i) mean += ((long) i * (long) count[i]) / n; return mean; } private double getLeftMedian(int[] count, double n) { int numCount = 0; for (int i = 0; i < count.length; ++i) { numCount += count[i]; if (numCount >= n / 2) return i; } return -1; } private double getRightMedian(int[] count, double n) { int numCount = 0; for (int i = count.length - 1; i >= 0; --i) { numCount += count[i]; if (numCount >= n / 2) return i; } return -1; } private double getMode(int[] count) { int mode = -1; int maxCount = 0; for (int i = 0; i < count.length; ++i) if (count[i] > maxCount) { maxCount = count[i]; mode = i; } return mode; } }
class Solution { public: vector<double> sampleStats(vector<int>& count) { const int n = accumulate(count.begin(), count.end(), 0); const double mode = ranges::max_element(count) - count.begin(); return { getMinimum(count), getMaximum(count), getMean(count, n), (getLeftMedian(count, n) + getRightMedian(count, n)) / 2.0, mode, }; } private: double getMinimum(const vector<int>& count) { for (int i = 0; i < count.size(); ++i) if (count[i]) return i; return -1; } double getMaximum(const vector<int>& count) { for (int i = count.size() - 1; i >= 0; --i) if (count[i]) return i; return -1; } double getMean(const vector<int>& count, double n) { double mean = 0; for (long i = 0; i < count.size(); ++i) mean += (i * count[i]) / n; return mean; } double getLeftMedian(const vector<int>& count, double n) { int numCount = 0; for (int i = 0; i < count.size(); ++i) { numCount += count[i]; if (numCount >= n / 2) return i; } return -1; } double getRightMedian(const vector<int>& count, double n) { int numCount = 0; for (int i = count.size() - 1; i >= 0; --i) { numCount += count[i]; if (numCount >= n / 2) return i; } return -1; } };
1,129
Shortest Path with Alternating Colors
2
shortestAlternatingPaths
You are given an integer `n`, the number of nodes in a directed graph where the nodes are labeled from `0` to `n - 1`. Each edge is red or blue in this graph, and there could be self-edges and parallel edges. You are given two arrays `redEdges` and `blueEdges` where: * `redEdges[i] = [ai, bi]` indicates that there is a directed red edge from node `ai` to node `bi` in the graph, and * `blueEdges[j] = [uj, vj]` indicates that there is a directed blue edge from node `uj` to node `vj` in the graph. Return an array `answer` of length `n`, where each `answer[x]` is the length of the shortest path from node `0` to node `x` such that the edge colors alternate along the path, or `-1` if such a path does not exist.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator from enum import Enum class Color(Enum): kInit = 0 kRed = 1 kBlue = 2 class Solution: def shortestAlternatingPaths(self, n: int, redEdges: List[List[int]], blueEdges: List[List[int]]) -> List[int]: ans = [-1] * n graph = [[] for _ in range(n)] q = collections.deque([(0, Color.kInit)]) for u, v in redEdges: graph[u].append((v, Color.kRed)) for u, v in blueEdges: graph[u].append((v, Color.kBlue)) step = 0 while q: for _ in range(len(q)): u, prevColor = q.popleft() if ans[u] == -1: ans[u] = step for i, (v, edgeColor) in enumerate(graph[u]): if v == -1 or edgeColor == prevColor: continue q.append((v, edgeColor)) graph[u][i] = (-1, edgeColor) step += 1 return ans
enum Color { INIT, RED, BLUE } class Solution { public int[] shortestAlternatingPaths(int n, int[][] redEdges, int[][] blueEdges) { int[] ans = new int[n]; Arrays.fill(ans, -1); // graph[u] := [(v, edgeColor)] List<Pair<Integer, Color>>[] graph = new List[n]; // [(u, prevColor)] Queue<Pair<Integer, Color>> q = new ArrayDeque<>(List.of(new Pair<>(0, Color.INIT))); Arrays.setAll(graph, i -> new ArrayList<>()); for (int[] edge : redEdges) { final int u = edge[0]; final int v = edge[1]; graph[u].add(new Pair<>(v, Color.RED)); } for (int[] edge : blueEdges) { final int u = edge[0]; final int v = edge[1]; graph[u].add(new Pair<>(v, Color.BLUE)); } for (int step = 0; !q.isEmpty(); ++step) for (int sz = q.size(); sz > 0; --sz) { final int u = q.peek().getKey(); Color prevColor = q.poll().getValue(); ans[u] = ans[u] == -1 ? step : ans[u]; for (int i = 0; i < graph[u].size(); ++i) { Pair<Integer, Color> node = graph[u].get(i); final int v = node.getKey(); Color edgeColor = node.getValue(); if (v == -1 || edgeColor == prevColor) continue; q.add(new Pair<>(v, edgeColor)); // Mark (u, v) as used. graph[u].set(i, new Pair<>(-1, edgeColor)); } } return ans; } }
enum class Color { kInit, kRed, kBlue }; class Solution { public: vector<int> shortestAlternatingPaths(int n, vector<vector<int>>& redEdges, vector<vector<int>>& blueEdges) { vector<int> ans(n, -1); vector<vector<pair<int, Color>>> graph(n); // graph[u] := [(v, edgeColor)] queue<pair<int, Color>> q{{{0, Color::kInit}}}; // [(u, prevColor)] for (const vector<int>& edge : redEdges) { const int u = edge[0]; const int v = edge[1]; graph[u].emplace_back(v, Color::kRed); } for (const vector<int>& edge : blueEdges) { const int u = edge[0]; const int v = edge[1]; graph[u].emplace_back(v, Color::kBlue); } for (int step = 0; !q.empty(); ++step) for (int sz = q.size(); sz > 0; --sz) { const auto [u, prevColor] = q.front(); q.pop(); ans[u] = ans[u] == -1 ? step : ans[u]; for (auto& [v, edgeColor] : graph[u]) { if (v == -1 || edgeColor == prevColor) continue; q.emplace(v, edgeColor); v = -1; // Mark (u, v) as used. } } return ans; } };
1,139
Largest 1-Bordered Square
2
largest1BorderedSquare
Given a 2D `grid` of `0`s and `1`s, return the number of elements in the largest square subgrid that has all `1`s on its border, or `0` if such a subgrid doesn't exist in the `grid`.
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 largest1BorderedSquare(self, grid: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) leftOnes = [[0] * n for _ in range(m)] topOnes = [[0] * n for _ in range(m)] for i in range(m): for j in range(n): if grid[i][j] == 1: if j==0: leftOnes[i][j]=1 else: leftOnes[i][j]=1+leftOnes[i][j-1] if i==0: topOnes[i][j]=1 else: topOnes[i][j]=1+topOnes[i-1][j] for sz in range(min(m, n), 0, -1): for i in range(m - sz + 1): for j in range(n - sz + 1): x = i + sz - 1 y = j + sz - 1 if min(leftOnes[i][y], leftOnes[x][y], topOnes[x][j], topOnes[x][y]) >= sz: return sz * sz return 0
class Solution { public int largest1BorderedSquare(int[][] grid) { final int m = grid.length; final int n = grid[0].length; // leftOnes[i][j] := consecutive 1s in the left of grid[i][j] int[][] leftOnes = new int[m][n]; // topOnes[i][j] := consecutive 1s in the top of grid[i][j] int[][] topOnes = new int[m][n]; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 1) { leftOnes[i][j] = j == 0 ? 1 : 1 + leftOnes[i][j - 1]; topOnes[i][j] = i == 0 ? 1 : 1 + topOnes[i - 1][j]; } for (int sz = Math.min(m, n); sz > 0; --sz) for (int i = 0; i + sz - 1 < m; ++i) for (int j = 0; j + sz - 1 < n; ++j) { final int x = i + sz - 1; final int y = j + sz - 1; // If grid[i..x][j..y] has all 1s on its border. if (Math.min(leftOnes[i][y], leftOnes[x][y]) >= sz && Math.min(topOnes[x][j], topOnes[x][y]) >= sz) return sz * sz; } return 0; } };
class Solution { public: int largest1BorderedSquare(vector<vector<int>>& grid) { const int m = grid.size(); const int n = grid[0].size(); // leftOnes[i][j] := consecutive 1s in the left of grid[i][j] vector<vector<int>> leftOnes(m, vector<int>(n)); // topOnes[i][j] := consecutive 1s in the top of grid[i][j] vector<vector<int>> topOnes(m, vector<int>(n)); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 1) { leftOnes[i][j] = j == 0 ? 1 : 1 + leftOnes[i][j - 1]; topOnes[i][j] = i == 0 ? 1 : 1 + topOnes[i - 1][j]; } for (int sz = min(m, n); sz > 0; --sz) for (int i = 0; i + sz - 1 < m; ++i) for (int j = 0; j + sz - 1 < n; ++j) { const int x = i + sz - 1; const int y = j + sz - 1; // If grid[i..x][j..y] has all 1s on its border. if (min(leftOnes[i][y], leftOnes[x][y]) >= sz && min(topOnes[x][j], topOnes[x][y]) >= sz) return sz * sz; } return 0; } };
1,162
As Far from Land as Possible
2
maxDistance
Given an `n x n` `grid` containing only values `0` and `1`, where `0` represents water and `1` represents land, find a water cell such that its distance to the nearest land cell is maximized, and return the distance. If no land or water exists in the grid, return `-1`. The distance used in this problem is the Manhattan distance: the distance between two cells `(x0, y0)` and `(x1, y1)` is `|x0 - x1| + |y0 - y1|`.
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 maxDistance(self, grid: List[List[int]]) -> int: dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) m = len(grid) n = len(grid[0]) q = collections.deque() water = 0 for i in range(m): for j in range(n): if grid[i][j] == 0: water += 1 else: q.append((i, j)) if water == 0 or water == m * n: return -1 ans = 0 d = 0 while q: for _ in range(len(q)): i, j = q.popleft() ans = d for dx, dy in dirs: x = i + dx y = j + dy if x < 0 or x == m or y < 0 or y == n: continue if grid[x][y] > 0: continue q.append((x, y)) grid[x][y] = 2 d += 1 return ans
class Solution { public int maxDistance(int[][] grid) { final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; final int m = grid.length; final int n = grid[0].length; Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(); int water = 0; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 0) ++water; else q.offer(new Pair<>(i, j)); if (water == 0 || water == m * n) return -1; int ans = 0; for (int d = 0; !q.isEmpty(); ++d) for (int sz = q.size(); sz > 0; --sz) { Pair<Integer, Integer> pair = q.poll(); final int i = pair.getKey(); final int j = pair.getValue(); ans = d; for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == m || y < 0 || y == n) continue; if (grid[x][y] > 0) continue; q.offer(new Pair<>(x, y)); grid[x][y] = 2; // Mark as visited. } } return ans; } }
class Solution { public: int maxDistance(vector<vector<int>>& grid) { constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; const int m = grid.size(); const int n = grid[0].size(); queue<pair<int, int>> q; int water = 0; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 0) ++water; else q.emplace(i, j); if (water == 0 || water == m * n) return -1; int ans = 0; for (int d = 0; !q.empty(); ++d) for (int sz = q.size(); sz > 0; --sz) { const auto [i, j] = q.front(); q.pop(); ans = d; for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == m || y < 0 || y == n) continue; if (grid[x][y] > 0) continue; q.emplace(x, y); grid[x][y] = 2; // Mark as visited. } } return ans; } };
1,202
Smallest String With Swaps
2
smallestStringWithSwaps
You are given a string `s`, and an array of pairs of indices in the string `pairs` where `pairs[i] = [a, b]` indicates 2 indices(0-indexed) of the string. You can swap the characters at any pair of indices in the given `pairs` any number of times. Return the lexicographically smallest string that `s` can be changed to after using the swaps.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class UnionFind: def __init__(self, n: int): self.id = list(range(n)) self.rank = [0] * n def unionByRank(self, u: int, v: int) -> None: i = self.find(u) j = self.find(v) if i == j: return if self.rank[i] < self.rank[j]: self.id[i] = j elif self.rank[i] > self.rank[j]: self.id[j] = i else: self.id[i] = j self.rank[j] += 1 def find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self.find(self.id[u]) return self.id[u] class Solution: def smallestStringWithSwaps(self, s: str, pairs: List[List[int]]) -> str: ans = '' uf = UnionFind(len(s)) map = collections.defaultdict(list) for a, b in pairs: uf.unionByRank(a, b) for i, c in enumerate(s): map[uf.find(i)].append(c) for key in map.keys(): map[key].sort(reverse=True) for i in range(len(s)): ans += map[uf.find(i)].pop() return ans
class UnionFind { public UnionFind(int n) { id = new int[n]; rank = new int[n]; for (int i = 0; i < n; ++i) id[i] = i; } public void unionByRank(int u, int v) { final int i = find(u); final int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } public int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } private int[] id; private int[] rank; } class Solution { public String smallestStringWithSwaps(String s, List<List<Integer>> pairs) { StringBuilder sb = new StringBuilder(); UnionFind uf = new UnionFind(s.length()); Map<Integer, Queue<Character>> indexToLetters = new HashMap<>(); for (List<Integer> pair : pairs) { final int a = pair.get(0); final int b = pair.get(1); uf.unionByRank(a, b); } for (int i = 0; i < s.length(); ++i) indexToLetters.computeIfAbsent(uf.find(i), k -> new PriorityQueue<>()).offer(s.charAt(i)); for (int i = 0; i < s.length(); ++i) sb.append(indexToLetters.get(uf.find(i)).poll()); return sb.toString(); } }
class UnionFind { public: UnionFind(int n) : id(n), rank(n) { iota(id.begin(), id.end(), 0); } void unionByRank(int u, int v) { const int i = find(u); const int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } private: vector<int> id; vector<int> rank; }; class Solution { public: string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) { string ans; UnionFind uf(s.length()); unordered_map<int, priority_queue<char, vector<char>, greater<>>> indexToLetters; for (const vector<int>& pair : pairs) { const int a = pair[0]; const int b = pair[1]; uf.unionByRank(a, b); } for (int i = 0; i < s.length(); ++i) indexToLetters[uf.find(i)].push(s[i]); for (int i = 0; i < s.length(); ++i) ans += indexToLetters[uf.find(i)].top(), indexToLetters[uf.find(i)].pop(); return ans; } };
1,210
Minimum Moves to Reach Target with Rotations
3
minimumMoves
In an `n*n` grid, there is a snake that spans 2 cells and starts moving from the top left corner at `(0, 0)` and `(0, 1)`. The grid has empty cells represented by zeros and blocked cells represented by ones. The snake wants to reach the lower right corner at `(n-1, n-2)` and `(n-1, n-1)`. In one move the snake can: * Move one cell to the right if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is. * Move down one cell if there are no blocked cells there. This move keeps the horizontal/vertical position of the snake as it is. * Rotate clockwise if it's in a horizontal position and the two cells under it are both empty. In that case the snake moves from `(r, c)` and `(r, c+1)` to `(r, c)` and `(r+1, c)`. * Rotate counterclockwise if it's in a vertical position and the two cells to its right are both empty. In that case the snake moves from `(r, c)` and `(r+1, c)` to `(r, c)` and `(r, c+1)`. Return the minimum number of moves to reach the target. If there is no way to reach the target, 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 from enum import IntEnum class Pos(IntEnum): kHorizontal = 0 kVertical = 1 class Solution: def minimumMoves(self, grid: List[List[int]]) -> int: n = len(grid) ans = 0 q = collections.deque([(0, 0, Pos.kHorizontal)]) seen = {(0, 0, Pos.kHorizontal)} def canMoveRight(x: int, y: int, pos: Pos) -> bool: if pos == Pos.kHorizontal: return y + 2 < n and not grid[x][y + 2] return y + 1 < n and not grid[x][y + 1] and not grid[x + 1][y + 1] def canMoveDown(x: int, y: int, pos: Pos) -> bool: if pos == Pos.kVertical: return x + 2 < n and not grid[x + 2][y] return x + 1 < n and not grid[x + 1][y] and not grid[x + 1][y + 1] def canRotateClockwise(x: int, y: int, pos: Pos) -> bool: return pos == Pos.kHorizontal and x + 1 < n and \ not grid[x + 1][y + 1] and not grid[x + 1][y] def canRotateCounterclockwise(x: int, y: int, pos: Pos) -> bool: return pos == Pos.kVertical and y + 1 < n and \ not grid[x + 1][y + 1] and not grid[x][y + 1] while q: for _ in range(len(q)): x, y, pos = q.popleft() if x == n - 1 and y == n - 2 and pos == Pos.kHorizontal: return ans if canMoveRight(x, y, pos) and (x, y + 1, pos) not in seen: q.append((x, y + 1, pos)) seen.add((x, y + 1, pos)) if canMoveDown(x, y, pos) and (x + 1, y, pos) not in seen: q.append((x + 1, y, pos)) seen.add((x + 1, y, pos)) newPos = Pos.kVertical if pos == Pos.kHorizontal else Pos.kHorizontal if (canRotateClockwise(x, y, pos) or canRotateCounterclockwise(x, y, pos)) and (x, y, newPos) not in seen: q.append((x, y, newPos)) seen.add((x, y, newPos)) ans += 1 return -1
enum Pos { HORIZONTAL, VERTICAL } class Solution { public int minimumMoves(int[][] grid) { record T(int x, int y, Pos pos) {} final int n = grid.length; Queue<T> q = new ArrayDeque<>(List.of(new T(0, 0, Pos.HORIZONTAL))); boolean[][][] seen = new boolean[n][n][2]; seen[0][0][Pos.HORIZONTAL.ordinal()] = true; for (int step = 0; !q.isEmpty(); ++step) for (int sz = q.size(); sz > 0; --sz) { final int x = q.peek().x; final int y = q.peek().y; final Pos pos = q.poll().pos; if (x == n - 1 && y == n - 2 && pos == Pos.HORIZONTAL) return step; if (canMoveRight(grid, x, y, pos) && !seen[x][y + 1][pos.ordinal()]) { q.offer(new T(x, y + 1, pos)); seen[x][y + 1][pos.ordinal()] = true; } if (canMoveDown(grid, x, y, pos) && !seen[x + 1][y][pos.ordinal()]) { q.offer(new T(x + 1, y, pos)); seen[x + 1][y][pos.ordinal()] = true; } final Pos newPos = pos == Pos.HORIZONTAL ? Pos.VERTICAL : Pos.HORIZONTAL; if ((canRotateClockwise(grid, x, y, pos) || canRotateCounterclockwise(grid, x, y, pos)) && !seen[x][y][newPos.ordinal()]) { q.offer(new T(x, y, newPos)); seen[x][y][newPos.ordinal()] = true; } } return -1; } private boolean canMoveRight(int[][] grid, int x, int y, Pos pos) { if (pos == Pos.HORIZONTAL) return y + 2 < grid.length && grid[x][y + 2] == 0; return y + 1 < grid.length && grid[x][y + 1] == 0 && grid[x + 1][y + 1] == 0; } private boolean canMoveDown(int[][] grid, int x, int y, Pos pos) { if (pos == Pos.VERTICAL) return x + 2 < grid.length && grid[x + 2][y] == 0; return x + 1 < grid.length && grid[x + 1][y] == 0 && grid[x + 1][y + 1] == 0; } private boolean canRotateClockwise(int[][] grid, int x, int y, Pos pos) { return pos == Pos.HORIZONTAL && x + 1 < grid.length && grid[x + 1][y + 1] == 0 && grid[x + 1][y] == 0; } private boolean canRotateCounterclockwise(int[][] grid, int x, int y, Pos pos) { return pos == Pos.VERTICAL && y + 1 < grid.length && grid[x + 1][y + 1] == 0 && grid[x][y + 1] == 0; } }
enum class Pos { kHorizontal, kVertical }; class Solution { public: int minimumMoves(vector<vector<int>>& grid) { const int n = grid.size(); queue<tuple<int, int, Pos>> q{{{0, 0, Pos::kHorizontal}}}; vector<vector<vector<bool>>> seen(n, vector<vector<bool>>(n, vector<bool>(2))); seen[0][0][static_cast<int>(Pos::kHorizontal)] = true; auto canMoveRight = [&](int x, int y, Pos pos) -> bool { if (pos == Pos::kHorizontal) return y + 2 < n && !grid[x][y + 2]; return y + 1 < n && !grid[x][y + 1] && !grid[x + 1][y + 1]; }; auto canMoveDown = [&](int x, int y, Pos pos) -> bool { if (pos == Pos::kVertical) return x + 2 < n && !grid[x + 2][y]; return x + 1 < n && !grid[x + 1][y] && !grid[x + 1][y + 1]; }; auto canRotateClockwise = [&](int x, int y, Pos pos) -> bool { return pos == Pos::kHorizontal && x + 1 < n && !grid[x + 1][y + 1] && !grid[x + 1][y]; }; auto canRotateCounterclockwise = [&](int x, int y, Pos pos) -> bool { return pos == Pos::kVertical && y + 1 < n && !grid[x + 1][y + 1] && !grid[x][y + 1]; }; for (int step = 0; !q.empty(); ++step) for (int sz = q.size(); sz > 0; --sz) { const auto [x, y, pos] = q.front(); q.pop(); if (x == n - 1 && y == n - 2 && pos == Pos::kHorizontal) return step; if (canMoveRight(x, y, pos) && !seen[x][y + 1][static_cast<int>(pos)]) { q.emplace(x, y + 1, pos); seen[x][y + 1][static_cast<int>(pos)] = true; } if (canMoveDown(x, y, pos) && !seen[x + 1][y][static_cast<int>(pos)]) { q.emplace(x + 1, y, pos); seen[x + 1][y][static_cast<int>(pos)] = true; } const Pos newPos = pos == Pos::kHorizontal ? Pos::kVertical : Pos::kHorizontal; if ((canRotateClockwise(x, y, pos) || canRotateCounterclockwise(x, y, pos)) && !seen[x][y][static_cast<int>(newPos)]) { q.emplace(x, y, newPos); seen[x][y][static_cast<int>(newPos)] = true; } } return -1; } };
1,253
Reconstruct a 2-Row Binary Matrix
2
reconstructMatrix
Given the following details of a matrix with `n` columns and `2` rows : * The matrix is a binary matrix, which means each element in the matrix can be `0` or `1`. * The sum of elements of the 0-th(upper) row is given as `upper`. * The sum of elements of the 1-st(lower) row is given as `lower`. * The sum of elements in the i-th column(0-indexed) is `colsum[i]`, where `colsum` is given as an integer array with length `n`. Your task is to reconstruct the matrix with `upper`, `lower` and `colsum`. Return it as a 2-D integer array. If there are more than one valid solution, any of them will be accepted. If no valid solution exists, return an empty 2-D array.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def reconstructMatrix(self, upper: int, lower: int, colsum: List[int]) -> List[List[int]]: if upper + lower != sum(colsum): return [] if min(upper, lower) < colsum.count(2): return [] ans = [[0] * len(colsum) for _ in range(2)] for j, c in enumerate(colsum): if c == 2: ans[0][j] = 1 ans[1][j] = 1 upper -= 1 lower -= 1 for j, c in enumerate(colsum): if c == 1 and upper > 0: ans[0][j] = 1 c -= 1 upper -= 1 if c == 1 and lower > 0: ans[1][j] = 1 lower -= 1 return ans
class Solution { public List<List<Integer>> reconstructMatrix(int upper, int lower, int[] colsum) { if (upper + lower != Arrays.stream(colsum).sum()) return new ArrayList<>(); int count = 0; for (int c : colsum) if (c == 2) ++count; if (Math.min(upper, lower) < count) return new ArrayList<>(); int[][] ans = new int[2][colsum.length]; for (int j = 0; j < colsum.length; ++j) if (colsum[j] == 2) { ans[0][j] = 1; ans[1][j] = 1; --upper; --lower; } for (int j = 0; j < colsum.length; ++j) { if (colsum[j] == 1 && upper > 0) { ans[0][j] = 1; --colsum[j]; --upper; } if (colsum[j] == 1 && lower > 0) { ans[1][j] = 1; --lower; } } return new ArrayList(Arrays.asList(ans[0], ans[1])); } }
class Solution { public: vector<vector<int>> reconstructMatrix(int upper, int lower, vector<int>& colsum) { if (upper + lower != accumulate(colsum.begin(), colsum.end(), 0)) return {}; if (min(upper, lower) < ranges::count_if(colsum, [](int c) { return c == 2; })) return {}; vector<vector<int>> ans(2, vector<int>(colsum.size())); for (int j = 0; j < colsum.size(); ++j) if (colsum[j] == 2) { ans[0][j] = 1; ans[1][j] = 1; --upper; --lower; } for (int j = 0; j < colsum.size(); ++j) { if (colsum[j] == 1 && upper > 0) { ans[0][j] = 1; --colsum[j]; --upper; } if (colsum[j] == 1 && lower > 0) { ans[1][j] = 1; --lower; } } return ans; } };
1,254
Number of Closed Islands
2
closedIsland
Given a 2D `grid` consists of `0s` (land) and `1s` (water). An island is a maximal 4-directionally connected group of `0s` and a closed island is an island totally (all left, top, right, bottom) surrounded by `1s.` Return the number of closed islands.
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 closedIsland(self, grid: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) def dfs(i: int, j: int) -> None: if i < 0 or i == m or j < 0 or j == n: return if grid[i][j] == 1: return grid[i][j] = 1 dfs(i + 1, j) dfs(i - 1, j) dfs(i, j + 1) dfs(i, j - 1) for i in range(m): for j in range(n): if i * j == 0 or i == m - 1 or j == n - 1: if grid[i][j] == 0: dfs(i, j) ans = 0 for i in range(m): for j in range(n): if grid[i][j] == 0: dfs(i, j) ans += 1 return ans
class Solution { public int closedIsland(int[][] grid) { final int m = grid.length; final int n = grid[0].length; // Remove the lands connected to the edge. 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 (grid[i][j] == 0) dfs(grid, i, j); int ans = 0; // Reduce to 200. Number of Islands for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 0) { dfs(grid, i, j); ++ans; } return ans; } private void dfs(int[][] grid, int i, int j) { if (i < 0 || i == grid.length || j < 0 || j == grid[0].length) return; if (grid[i][j] == 1) return; grid[i][j] = 1; dfs(grid, i + 1, j); dfs(grid, i - 1, j); dfs(grid, i, j + 1); dfs(grid, i, j - 1); } }
class Solution { public: int closedIsland(vector<vector<int>>& grid) { const int m = grid.size(); const int n = grid[0].size(); // Remove the lands connected to the edge. 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 (grid[i][j] == 0) dfs(grid, i, j); int ans = 0; // Reduce to 200. Number of Islands for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 0) { dfs(grid, i, j); ++ans; } return ans; } private: void dfs(vector<vector<int>>& grid, int i, int j) { if (i < 0 || i == grid.size() || j < 0 || j == grid[0].size()) return; if (grid[i][j] == 1) return; grid[i][j] = 1; dfs(grid, i + 1, j); dfs(grid, i - 1, j); dfs(grid, i, j + 1); dfs(grid, i, j - 1); }; };
1,263
Minimum Moves to Move a Box to Their Target Location
3
minPushBox
A storekeeper is a game in which the player pushes boxes around in a warehouse trying to get them to target locations. The game is represented by an `m x n` grid of characters `grid` where each element is a wall, floor, or box. Your task is to move the box `'B'` to the target position `'T'` under the following rules: * The character `'S'` represents the player. The player can move up, down, left, right in `grid` if it is a floor (empty cell). * The character `'.'` represents the floor which means a free cell to walk. * The character `'#'` represents the wall which means an obstacle (impossible to walk there). * There is only one box `'B'` and one target cell `'T'` in the `grid`. * The box can be moved to an adjacent free cell by standing next to the box and then moving in the direction of the box. This is a push. * The player cannot walk through the box. Return the minimum number of pushes to move the box to the target. If there is no way to reach the target, 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 from collections import deque class Solution: def minPushBox(self, grid: List[List[str]]) -> int: for i in range(len(grid)): for j in range(len(grid[0])): if grid[i][j] == "T": target = (i,j) if grid[i][j] == "B": box = (i,j) if grid[i][j] == "S": person = (i,j) def valid(x,y): return 0<=x<len(grid) and 0<=y<len(grid[0]) and grid[x][y]!='#' def check(curr,dest,box): que = deque([curr]) v = set() while que: pos = que.popleft() if pos == dest: return True new_pos = [(pos[0]+1,pos[1]),(pos[0]-1,pos[1]),(pos[0],pos[1]+1),(pos[0],pos[1]-1)] for x,y in new_pos: if valid(x,y) and (x,y) not in v and (x,y)!=box: v.add((x,y)) que.append((x,y)) return False q = deque([(0,box,person)]) vis = {box+person} while q : dist, box, person = q.popleft() if box == target: return dist b_coord = [(box[0]+1,box[1]),(box[0]-1,box[1]),(box[0],box[1]+1),(box[0],box[1]-1)] p_coord = [(box[0]-1,box[1]),(box[0]+1,box[1]),(box[0],box[1]-1),(box[0],box[1]+1)] for new_box,new_person in zip(b_coord,p_coord): if valid(*new_box) and new_box+box not in vis: if valid(*new_person) and check(person,new_person,box): vis.add(new_box+box) q.append((dist+1,new_box,box)) return -1
class Solution { public int minPushBox(char[][] grid) { record T(int boxX, int boxY, int playerX, int playerY) {} final int m = grid.length; final int n = grid[0].length; int[] box = {-1, -1}; int[] player = {-1, -1}; int[] target = {-1, -1}; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 'B') box = new int[] {i, j}; else if (grid[i][j] == 'S') player = new int[] {i, j}; else if (grid[i][j] == 'T') target = new int[] {i, j}; Queue<T> q = new ArrayDeque<>(List.of(new T(box[0], box[1], player[0], player[1]))); boolean[][][][] seen = new boolean[m][n][m][n]; seen[box[0]][box[1]][player[0]][player[1]] = true; for (int step = 0; !q.isEmpty(); ++step) for (int sz = q.size(); sz > 0; --sz) { final int boxX = q.peek().boxX; final int boxY = q.peek().boxY; final int playerX = q.peek().playerX; final int playerY = q.poll().playerY; if (boxX == target[0] && boxY == target[1]) return step; for (int k = 0; k < 4; ++k) { final int nextBoxX = boxX + DIRS[k][0]; final int nextBoxY = boxY + DIRS[k][1]; if (isInvalid(grid, nextBoxX, nextBoxY)) continue; if (seen[nextBoxX][nextBoxY][boxX][boxY]) continue; final int fromX = boxX + DIRS[(k + 2) % 4][0]; final int fromY = boxY + DIRS[(k + 2) % 4][1]; if (isInvalid(grid, fromX, fromY)) continue; if (canGoTo(grid, playerX, playerY, fromX, fromY, boxX, boxY)) { seen[nextBoxX][nextBoxY][boxX][boxY] = true; q.offer(new T(nextBoxX, nextBoxY, boxX, boxY)); } } } return -1; } private static final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // Returns true if (playerX, playerY) can go to (fromX, fromY). private boolean canGoTo(char[][] grid, int playerX, int playerY, int fromX, int fromY, int boxX, int boxY) { Queue<Pair<Integer, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(playerX, playerY))); boolean[][] seen = new boolean[grid.length][grid[0].length]; seen[playerX][playerY] = true; while (!q.isEmpty()) { final int i = q.peek().getKey(); final int j = q.poll().getValue(); if (i == fromX && j == fromY) return true; for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (isInvalid(grid, x, y)) continue; if (seen[x][y]) continue; if (x == boxX && y == boxY) continue; q.offer(new Pair<>(x, y)); seen[x][y] = true; } } return false; } private boolean isInvalid(char[][] grid, int playerX, int playerY) { return playerX < 0 || playerX == grid.length || playerY < 0 || playerY == grid[0].length || grid[playerX][playerY] == '#'; } }
class Solution { public: int minPushBox(vector<vector<char>>& grid) { const int m = grid.size(); const int n = grid[0].size(); vector<int> box; vector<int> player; vector<int> target; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 'B') box = {i, j}; else if (grid[i][j] == 'S') player = {i, j}; else if (grid[i][j] == 'T') target = {i, j}; // (boxX, boxY, playerX, playerY) queue<tuple<int, int, int, int>> q{ {{box[0], box[1], player[0], player[1]}}}; vector<vector<vector<vector<bool>>>> seen( m, vector<vector<vector<bool>>>( n, vector<vector<bool>>(m, vector<bool>(n)))); seen[box[0]][box[1]][player[0]][player[1]] = true; for (int step = 0; !q.empty(); ++step) for (int sz = q.size(); sz > 0; --sz) { const auto [boxX, boxY, playerX, playerY] = q.front(); q.pop(); if (boxX == target[0] && boxY == target[1]) return step; for (int k = 0; k < 4; ++k) { const int nextBoxX = boxX + kDirs[k % 4][0]; const int nextBoxY = boxY + kDirs[k % 4][1]; if (isInvalid(grid, nextBoxX, nextBoxY)) continue; if (seen[nextBoxX][nextBoxY][boxX][boxY]) continue; const int fromX = boxX + kDirs[(k + 2) % 4][0]; const int fromY = boxY + kDirs[(k + 2) % 4][1]; if (isInvalid(grid, fromX, fromY)) continue; if (canGoTo(grid, playerX, playerY, fromX, fromY, boxX, boxY)) { seen[nextBoxX][nextBoxY][boxX][boxY] = true; q.emplace(nextBoxX, nextBoxY, boxX, boxY); } } } return -1; } private: static constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; // Returns true if (playerX, playerY) can go to (fromX, fromY). bool canGoTo(const vector<vector<char>>& grid, int playerX, int playerY, int fromX, int fromY, int boxX, int boxY) { queue<pair<int, int>> q{{{playerX, playerY}}}; vector<vector<bool>> seen(grid.size(), vector<bool>(grid[0].size())); seen[playerX][playerY] = true; while (!q.empty()) { const auto [i, j] = q.front(); q.pop(); if (i == fromX && j == fromY) return true; for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (isInvalid(grid, x, y)) continue; if (seen[x][y]) continue; if (x == boxX && y == boxY) continue; q.emplace(x, y); seen[x][y] = true; } } return false; } bool isInvalid(const vector<vector<char>>& grid, int playerX, int playerY) { return playerX < 0 || playerX == grid.size() || playerY < 0 || playerY == grid[0].size() || grid[playerX][playerY] == '#'; } };
1,267
Count Servers that Communicate
2
countServers
You are given a map of a server center, represented as a `m * n` integer matrix `grid`, where 1 means that on that cell there is a server and 0 means that it is no server. Two servers are said to communicate if they are on the same row or on the same column. Return the number of servers that communicate with any other server.
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 countServers(self, grid: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) ans = 0 rows = [0] * m cols = [0] * n for i in range(m): for j in range(n): if grid[i][j] == 1: rows[i] += 1 cols[j] += 1 for i in range(m): for j in range(n): if grid[i][j] == 1 and (rows[i] > 1 or cols[j] > 1): ans += 1 return ans
class Solution { public int countServers(int[][] grid) { final int m = grid.length; final int n = grid[0].length; int ans = 0; int[] rows = new int[m]; int[] cols = new int[n]; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 1) { ++rows[i]; ++cols[j]; } for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 1 && (rows[i] > 1 || cols[j] > 1)) ++ans; return ans; } }
class Solution { public: int countServers(vector<vector<int>>& grid) { const int m = grid.size(); const int n = grid[0].size(); int ans = 0; vector<int> rows(m); vector<int> cols(n); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 1) { ++rows[i]; ++cols[j]; } for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (grid[i][j] == 1 && (rows[i] > 1 || cols[j] > 1)) ++ans; return ans; } };
1,284
Minimum Number of Flips to Convert Binary Matrix to Zero Matrix
3
minFlips
Given a `m x n` binary matrix `mat`. In one step, you can choose one cell and flip it and all the four neighbors of it if they exist (Flip is changing `1` to `0` and `0` to `1`). A pair of cells are called neighbors if they share one edge. Return the minimum number of steps required to convert `mat` to a zero matrix or `-1` if you cannot. A binary matrix is a matrix with all cells equal to `0` or `1` only. A zero matrix is a matrix with all cells equal to `0`.
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 minFlips(self, mat: List[List[int]]) -> int: m = len(mat) n = len(mat[0]) hash = self._getHash(mat, m, n) if hash == 0: return 0 dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) step = 0 q = collections.deque([hash]) seen = {hash} while q: step += 1 for _ in range(len(q)): curr = q.popleft() for i in range(m): for j in range(n): next = curr ^ 1 << (i * n + 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 next ^= 1 << (x * n + y) if next == 0: return step if next in seen: continue q.append(next) seen.add(next) return -1 def _getHash(self, mat: List[List[int]], m: int, n: int) -> int: hash = 0 for i in range(m): for j in range(n): if mat[i][j]: hash |= 1 << (i * n + j) return hash
class Solution { public int minFlips(int[][] mat) { final int m = mat.length; final int n = mat[0].length; final int hash = getHash(mat, m, n); if (hash == 0) return 0; final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; Queue<Integer> q = new ArrayDeque<>(List.of(hash)); Set<Integer> seen = new HashSet<>(Arrays.asList(hash)); for (int step = 1; !q.isEmpty(); ++step) { for (int sz = q.size(); sz > 0; --sz) { final int curr = q.poll(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int next = curr ^ 1 << (i * n + j); // Flie the four neighbors. 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; next ^= 1 << (x * n + y); } if (next == 0) return step; if (seen.contains(next)) continue; q.offer(next); seen.add(next); } } } } return -1; } private int getHash(int[][] mat, int m, int n) { int hash = 0; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (mat[i][j] == 1) hash |= 1 << (i * n + j); return hash; } }
class Solution { public: int minFlips(vector<vector<int>>& mat) { const int m = mat.size(); const int n = mat[0].size(); const int hash = getHash(mat, m, n); if (hash == 0) return 0; constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; queue<int> q{{hash}}; unordered_set<int> seen{hash}; for (int step = 1; !q.empty(); ++step) { for (int sz = q.size(); sz > 0; --sz) { const int curr = q.front(); q.pop(); for (int i = 0; i < m; ++i) { for (int j = 0; j < n; ++j) { int next = curr ^ 1 << (i * n + j); // Flie the four neighbors. 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; next ^= 1 << (x * n + y); } if (next == 0) return step; if (seen.contains(next)) continue; q.push(next); seen.insert(next); } } } } return -1; } private: int getHash(const vector<vector<int>>& mat, int m, int n) { int hash = 0; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (mat[i][j]) hash |= 1 << (i * n + j); return hash; } };
1,293
Shortest Path in a Grid with Obstacles Elimination
3
shortestPath
You are given an `m x n` integer matrix `grid` where each cell is either `0` (empty) or `1` (obstacle). You can move up, down, left, or right from and to an empty cell in one step. Return the minimum number of steps to walk from the upper left corner `(0, 0)` to the lower right corner `(m - 1, n - 1)` given that you can eliminate at most `k` obstacles. If it is not possible to find such walk 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 shortestPath(self, grid: List[List[int]], k: int) -> int: m = len(grid) n = len(grid[0]) if m == 1 and n == 1: return 0 dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) steps = 0 q = collections.deque([(0, 0, k)]) seen = {(0, 0, k)} while q: steps += 1 for _ in range(len(q)): i, j, eliminate = q.popleft() for l in range(4): x = i + dirs[l][0] y = j + dirs[l][1] if x < 0 or x == m or y < 0 or y == n: continue if x == m - 1 and y == n - 1: return steps if grid[x][y] == 1 and eliminate == 0: continue newEliminate = eliminate - grid[x][y] if (x, y, newEliminate) in seen: continue q.append((x, y, newEliminate)) seen.add((x, y, newEliminate)) return -1
class Solution { public int shortestPath(int[][] grid, int k) { record T(int i, int j, int eliminate) {} final int m = grid.length; final int n = grid[0].length; if (m == 1 && n == 1) return 0; final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; Queue<T> q = new ArrayDeque<>(List.of(new T(0, 0, k))); boolean[][][] seen = new boolean[m][n][k + 1]; seen[0][0][k] = true; for (int step = 1; !q.isEmpty(); ++step) for (int sz = q.size(); sz > 0; --sz) { final int i = q.peek().i; final int j = q.peek().j; final int eliminate = q.poll().eliminate; for (int l = 0; l < 4; ++l) { final int x = i + DIRS[l][0]; final int y = j + DIRS[l][1]; if (x < 0 || x == m || y < 0 || y == n) continue; if (x == m - 1 && y == n - 1) return step; if (grid[x][y] == 1 && eliminate == 0) continue; final int newEliminate = eliminate - grid[x][y]; if (seen[x][y][newEliminate]) continue; q.offer(new T(x, y, newEliminate)); seen[x][y][newEliminate] = true; } } return -1; } }
class Solution { public: int shortestPath(vector<vector<int>>& grid, int k) { const int m = grid.size(); const int n = grid[0].size(); if (m == 1 && n == 1) return 0; constexpr int kDirs[4][2] = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; queue<tuple<int, int, int>> q{{{0, 0, k}}}; // (i, j, eliminate) vector<vector<vector<bool>>> seen( m, vector<vector<bool>>(n, vector<bool>(k + 1))); seen[0][0][k] = true; for (int step = 1; !q.empty(); ++step) for (int sz = q.size(); sz > 0; --sz) { const auto [i, j, eliminate] = 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 (x == m - 1 && y == n - 1) return step; if (grid[x][y] == 1 && eliminate == 0) continue; const int newEliminate = eliminate - grid[x][y]; if (seen[x][y][newEliminate]) continue; q.emplace(x, y, newEliminate); seen[x][y][newEliminate] = true; } } return -1; } };
1,301
Number of Paths with Max Score
3
pathsWithMaxScore
You are given a square `board` of characters. You can move on the board starting at the bottom right square marked with the character `'S'`. You need to reach the top left square marked with the character `'E'`. The rest of the squares are labeled either with a numeric character `1, 2, ..., 9` or with an obstacle `'X'`. In one move you can go up, left or up-left (diagonally) only if there is no obstacle there. Return a list of two integers: the first integer is the maximum sum of numeric characters you can collect, and the second is the number of such paths that you can take to get that maximum sum, taken modulo `10^9 + 7`. In case there is no path, return `[0, 0]`.
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 pathsWithMaxScore(self, board: List[str]) -> List[int]: kMod = 1_000_000_007 n = len(board) dirs = ((0, 1), (1, 0), (1, 1)) dp = [[-1] * (n + 1) for _ in range(n + 1)] count = [[0] * (n + 1) for _ in range(n + 1)] dp[0][0] = 0 dp[n - 1][n - 1] = 0 count[n - 1][n - 1] = 1 for i in reversed(range(n)): for j in reversed(range(n)): if board[i][j] == 'S' or board[i][j] == 'X': continue for dx, dy in dirs: x = i + dx y = j + dy if dp[i][j] < dp[x][y]: dp[i][j] = dp[x][y] count[i][j] = count[x][y] elif dp[i][j] == dp[x][y]: count[i][j] += count[x][y] count[i][j] %= kMod if dp[i][j] != -1 and board[i][j] != 'E': dp[i][j] += int(board[i][j]) dp[i][j] %= kMod return [dp[0][0], count[0][0]]
class Solution { public int[] pathsWithMaxScore(List<String> board) { final int MOD = 1_000_000_007; final int[][] DIRS = {{0, 1}, {1, 0}, {1, 1}}; final int n = board.size(); // dp[i][j] := the maximum sum from (n - 1, n - 1) to (i, j) int[][] dp = new int[n + 1][n + 1]; Arrays.stream(dp).forEach(A -> Arrays.fill(A, -1)); // count[i][j] := the number of paths to get dp[i][j] from (n - 1, n - 1) to (i, j) int[][] count = new int[n + 1][n + 1]; dp[0][0] = 0; dp[n - 1][n - 1] = 0; count[n - 1][n - 1] = 1; for (int i = n - 1; i >= 0; --i) for (int j = n - 1; j >= 0; --j) { if (board.get(i).charAt(j) == 'S' || board.get(i).charAt(j) == 'X') continue; for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (dp[i][j] < dp[x][y]) { dp[i][j] = dp[x][y]; count[i][j] = count[x][y]; } else if (dp[i][j] == dp[x][y]) { count[i][j] += count[x][y]; count[i][j] %= MOD; } } // If there's path(s) from 'S' to (i, j) and the cell is not 'E'. if (dp[i][j] != -1 && board.get(i).charAt(j) != 'E') { dp[i][j] += board.get(i).charAt(j) - '0'; dp[i][j] %= MOD; } } return new int[] {dp[0][0], count[0][0]}; } }
class Solution { public: vector<int> pathsWithMaxScore(vector<string>& board) { constexpr int kMod = 1'000'000'007; constexpr int kDirs[3][2] = {{0, 1}, {1, 0}, {1, 1}}; const int n = board.size(); // dp[i][j] := the maximum sum from (n - 1, n - 1) to (i, j) vector<vector<int>> dp(n + 1, vector<int>(n + 1, -1)); // count[i][j] := the number of paths to get dp[i][j] from (n - 1, n - 1) to // (i, j) vector<vector<int>> count(n + 1, vector<int>(n + 1)); dp[0][0] = 0; dp[n - 1][n - 1] = 0; count[n - 1][n - 1] = 1; for (int i = n - 1; i >= 0; --i) for (int j = n - 1; j >= 0; --j) { if (board[i][j] == 'S' || board[i][j] == 'X') continue; for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (dp[i][j] < dp[x][y]) { dp[i][j] = dp[x][y]; count[i][j] = count[x][y]; } else if (dp[i][j] == dp[x][y]) { count[i][j] += count[x][y]; count[i][j] %= kMod; } } // If there's path(s) from 'S' to (i, j) and the cell is not 'E'. if (dp[i][j] != -1 && board[i][j] != 'E') { dp[i][j] += board[i][j] - '0'; dp[i][j] %= kMod; } } return {dp[0][0], count[0][0]}; } };
1,334
Find the City With the Smallest Number of Neighbors at a Threshold Distance
2
findTheCity
There are `n` cities numbered from `0` to `n-1`. Given the array `edges` where `edges[i] = [fromi, toi, weighti]` represents a bidirectional and weighted edge between cities `fromi` and `toi`, and given the integer `distanceThreshold`. Return the city with the smallest number of cities that are reachable through some path and whose distance is at most `distanceThreshold`, If there are multiple such cities, return the city with the greatest number. Notice that the distance of a path connecting cities i and j is equal to the sum of the edges' weights along that path.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def findTheCity(self, n: int, edges: List[List[int]], distanceThreshold: int) -> int: ans = -1 minCitiesCount = n dist = self._floydWarshall(n, edges, distanceThreshold) for i in range(n): citiesCount = sum(dist[i][j] <= distanceThreshold for j in range(n)) if citiesCount <= minCitiesCount: ans = i minCitiesCount = citiesCount return ans def _floydWarshall(self, n: int, edges: List[List[int]], distanceThreshold: int) -> List[List[int]]: dist = [[distanceThreshold + 1] * n for _ in range(n)] for i in range(n): dist[i][i] = 0 for u, v, w in edges: dist[u][v] = w dist[v][u] = w for k in range(n): for i in range(n): for j in range(n): dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) return dist
class Solution { public int findTheCity(int n, int[][] edges, int distanceThreshold) { int ans = -1; int minCitiesCount = n; int[][] dist = floydWarshall(n, edges, distanceThreshold); for (int i = 0; i < n; ++i) { int citiesCount = 0; for (int j = 0; j < n; ++j) if (dist[i][j] <= distanceThreshold) ++citiesCount; if (citiesCount <= minCitiesCount) { ans = i; minCitiesCount = citiesCount; } } return ans; } private int[][] floydWarshall(int n, int[][] edges, int distanceThreshold) { int[][] dist = new int[n][n]; Arrays.stream(dist).forEach(A -> Arrays.fill(A, distanceThreshold + 1)); for (int i = 0; i < n; ++i) dist[i][i] = 0; for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; final int w = edge[2]; dist[u][v] = w; dist[v][u] = w; } for (int k = 0; k < n; ++k) for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); return dist; } }
class Solution { public: int findTheCity(int n, vector<vector<int>>& edges, int distanceThreshold) { int ans = -1; int minCitiesCount = n; const vector<vector<int>> dist = floydWarshall(n, edges, distanceThreshold); for (int i = 0; i < n; ++i) { int citiesCount = 0; for (int j = 0; j < n; ++j) if (dist[i][j] <= distanceThreshold) ++citiesCount; if (citiesCount <= minCitiesCount) { ans = i; minCitiesCount = citiesCount; } } return ans; } private: vector<vector<int>> floydWarshall(int n, const vector<vector<int>>& edges, int distanceThreshold) { vector<vector<int>> dist(n, vector<int>(n, distanceThreshold + 1)); for (int i = 0; i < n; ++i) dist[i][i] = 0; for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; const int w = edge[2]; dist[u][v] = w; dist[v][u] = w; } for (int k = 0; k < n; ++k) for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); return dist; } };
1,340
Jump Game V
3
maxJumps
Given an array of integers `arr` and an integer `d`. In one step you can jump from index `i` to index: * `i + x` where: `i + x < arr.length` and ` 0 < x <= d`. * `i - x` where: `i - x >= 0` and ` 0 < x <= d`. In addition, you can only jump from index `i` to index `j` if `arr[i] > arr[j]` and `arr[i] > arr[k]` for all indices `k` between `i` and `j` (More formally `min(i, j) < k < max(i, j)`). You can choose any index of the array and start jumping. Return the maximum number of indices you can visit. Notice that you can not jump outside of the array at any time.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def maxJumps(self, arr: List[int], d: int) -> int: n = len(arr) dp = [1] * n stack = [] for i in range(n + 1): while stack and (i == n or arr[stack[-1]] < arr[i]): indices = [stack.pop()] while stack and arr[stack[-1]] == arr[indices[0]]: indices.append(stack.pop()) for j in indices: if i < n and i - j <= d: dp[i] = max(dp[i], dp[j] + 1) if stack and j - stack[-1] <= d: dp[stack[-1]] = max(dp[stack[-1]], dp[j] + 1) stack.append(i) return max(dp)
class Solution { public int maxJumps(int[] arr, int d) { final int n = arr.length; // dp[i] := the maximum jumps starting from arr[i] int[] dp = new int[n]; // a dcreasing stack that stores indices Deque<Integer> stack = new ArrayDeque<>(); for (int i = 0; i <= n; ++i) { while (!stack.isEmpty() && (i == n || arr[stack.peek()] < arr[i])) { List<Integer> indices = new ArrayList<>(List.of(stack.pop())); while (!stack.isEmpty() && arr[stack.peek()] == arr[indices.get(0)]) indices.add(stack.pop()); for (final int j : indices) { if (i < n && i - j <= d) // Can jump from i to j. dp[i] = Math.max(dp[i], dp[j] + 1); if (!stack.isEmpty() && j - stack.peek() <= d) // Can jump from stack.peek() to j dp[stack.peek()] = Math.max(dp[stack.peek()], dp[j] + 1); } } stack.push(i); } return Arrays.stream(dp).max().getAsInt() + 1; } }
class Solution { public: int maxJumps(vector<int>& arr, int d) { const int n = arr.size(); // dp[i] := the maximum jumps starting from arr[i] vector<int> dp(n, 1); // a dcreasing stack that stores indices stack<int> stack; for (int i = 0; i <= n; ++i) { while (!stack.empty() && (i == n || arr[stack.top()] < arr[i])) { vector<int> indices{stack.top()}; stack.pop(); while (!stack.empty() && arr[stack.top()] == arr[indices[0]]) indices.push_back(stack.top()), stack.pop(); for (const int j : indices) { if (i < n && i - j <= d) // Can jump from i to j. dp[i] = max(dp[i], dp[j] + 1); if (!stack.empty() && j - stack.top() <= d) // Can jump from stack[-1] to j. dp[stack.top()] = max(dp[stack.top()], dp[j] + 1); } } stack.push(i); } return ranges::max(dp); } };
1,345
Jump Game IV
3
minJumps
Given an array of integers `arr`, you are initially positioned at the first index of the array. In one step you can jump from index `i` to index: * `i + 1` where: `i + 1 < arr.length`. * `i - 1` where: `i - 1 >= 0`. * `j` where: `arr[i] == arr[j]` and `i != j`. Return the minimum number of steps to reach the last index of the array. Notice that you can not jump outside of the array at any time.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minJumps(self, arr: List[int]) -> int: n = len(arr) graph = collections.defaultdict(list) step = 0 q = collections.deque([0]) seen = {0} for i, a in enumerate(arr): graph[a].append(i) while q: for _ in range(len(q)): i = q.popleft() if i == n - 1: return step seen.add(i) u = arr[i] if i + 1 < n: graph[u].append(i + 1) if i - 1 >= 0: graph[u].append(i - 1) for v in graph[u]: if v in seen: continue q.append(v) graph[u].clear() step += 1
class Solution { public int minJumps(int[] arr) { final int n = arr.length; // {a: indices} Map<Integer, List<Integer>> graph = new HashMap<>(); Queue<Integer> q = new ArrayDeque<>(List.of(0)); boolean[] seen = new boolean[n]; seen[0] = true; for (int i = 0; i < n; ++i) { graph.putIfAbsent(arr[i], new ArrayList<>()); graph.get(arr[i]).add(i); } for (int step = 0; !q.isEmpty(); ++step) { for (int sz = q.size(); sz > 0; --sz) { final int i = q.poll(); if (i == n - 1) return step; seen[i] = true; final int u = arr[i]; if (i + 1 < n) graph.get(u).add(i + 1); if (i - 1 >= 0) graph.get(u).add(i - 1); for (final int v : graph.get(u)) { if (seen[v]) continue; q.offer(v); } graph.get(u).clear(); } } throw new IllegalArgumentException(); } }
class Solution { public: int minJumps(vector<int>& arr) { const int n = arr.size(); // {a: indices} unordered_map<int, vector<int>> graph; queue<int> q{{0}}; vector<bool> seen(n); seen[0] = true; for (int i = 0; i < n; ++i) graph[arr[i]].push_back(i); for (int step = 0; !q.empty(); ++step) { for (int sz = q.size(); sz > 0; --sz) { const int i = q.front(); q.pop(); if (i == n - 1) return step; seen[i] = true; const int u = arr[i]; if (i + 1 < n) graph[u].push_back(i + 1); if (i - 1 >= 0) graph[u].push_back(i - 1); for (const int v : graph[u]) { if (seen[v]) continue; q.push(v); } graph[u].clear(); } } throw; } };
1,377
Frog Position After T Seconds
3
frogPosition
Given an undirected tree consisting of `n` vertices numbered from `1` to `n`. A frog starts jumping from vertex 1. In one second, the frog jumps from its current vertex to another unvisited vertex if they are directly connected. The frog can not jump back to a visited vertex. In case the frog can jump to several vertices, it jumps randomly to one of them with the same probability. Otherwise, when the frog can not jump to any unvisited vertex, it jumps forever on the same vertex. The edges of the undirected tree are given in the array `edges`, where `edges[i] = [ai, bi]` means that exists an edge connecting the vertices `ai` and `bi`. Return the probability that after `t` seconds the frog is on the vertex `target`. Answers within `10-5` of the actual answer will be accepted.
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 frogPosition(self, n: int, edges: List[List[int]], t: int, target: int) -> float: tree = [[] for _ in range(n + 1)] q = collections.deque([1]) seen = [False] * (n + 1) prob = [0] * (n + 1) prob[1] = 1 seen[1] = True for u, v in edges: tree[u].append(v) tree[v].append(u) for _ in range(t): for _ in range(len(q)): a = q.popleft() nChildren = sum(not seen[b] for b in tree[a]) for b in tree[a]: if seen[b]: continue seen[b] = True prob[b] = prob[a] / nChildren q.append(b) if nChildren > 0: prob[a] = 0 return prob[target]
class Solution { public double frogPosition(int n, int[][] edges, int t, int target) { List<Integer>[] tree = new List[n + 1]; Queue<Integer> q = new ArrayDeque<>(List.of(1)); boolean[] seen = new boolean[n + 1]; double[] prob = new double[n + 1]; seen[1] = true; prob[1] = 1.0; for (int i = 1; i <= n; ++i) tree[i] = new ArrayList<>(); for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; tree[u].add(v); tree[v].add(u); } while (!q.isEmpty() && t-- > 0) for (int sz = q.size(); sz > 0; --sz) { final int a = q.poll(); int nChildren = 0; for (final int b : tree[a]) if (!seen[b]) ++nChildren; for (final int b : tree[a]) { if (seen[b]) continue; seen[b] = true; prob[b] = prob[a] / nChildren; q.add(b); } if (nChildren > 0) prob[a] = 0.0; } return prob[target]; } }
class Solution { public: double frogPosition(int n, vector<vector<int>>& edges, int t, int target) { vector<vector<int>> tree(n + 1); queue<int> q{{1}}; vector<bool> seen(n + 1); vector<double> prob(n + 1); seen[1] = true; prob[1] = 1.0; for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; tree[u].push_back(v); tree[v].push_back(u); } while (!q.empty() && t-- > 0) for (int sz = q.size(); sz > 0; --sz) { const int a = q.front(); q.pop(); const int nChildren = ranges::count_if(tree[a], [&seen](int b) { return !seen[b]; }); for (const int b : tree[a]) { if (seen[b]) continue; seen[b] = true; prob[b] = prob[a] / nChildren; q.push(b); } if (nChildren > 0) prob[a] = 0.0; } return prob[target]; } };
1,417
Reformat The String
1
reformat
You are given an alphanumeric string `s`. (Alphanumeric string is a string consisting of lowercase English letters and digits). You have to find a permutation of the string where no letter is followed by another letter and no digit is followed by another digit. That is, no two adjacent characters have the same type. Return the reformatted string or return an empty string if it is impossible to reformat the 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 reformat(self, s: str) -> str: A=[] for c in s: if c.isalpha(): A.append(c) B=[] for c in s: if c.isdigit(): B.append(c) if len(A) < len(B): A, B = B, A if len(A) - len(B) > 1: return '' ans = [] for i in range(len(B)): ans.append(A[i]) ans.append(B[i]) if len(A) == len(B) + 1: ans.append(A[-1]) return ''.join(ans)
class Solution { public String reformat(String s) { List<Character> A = new ArrayList<>(); List<Character> B = new ArrayList<>(); for (final char c : s.toCharArray()) if (Character.isAlphabetic(c)) A.add(c); else B.add(c); if (A.size() < B.size()) { List<Character> temp = A; A = B; B = temp; } if (A.size() - B.size() > 1) return ""; StringBuilder sb = new StringBuilder(); for (int i = 0; i < B.size(); ++i) { sb.append(A.get(i)); sb.append(B.get(i)); } if (A.size() > B.size()) sb.append(A.get(A.size() - 1)); return sb.toString(); } }
class Solution { public: string reformat(string s) { vector<char> A; vector<char> B; for (const char c : s) isalpha(c) ? A.push_back(c) : B.push_back(c); if (A.size() < B.size()) swap(A, B); if (A.size() - B.size() > 1) return ""; string ans; for (int i = 0; i < B.size(); ++i) ans += string{A[i], B[i]}; if (A.size() > B.size()) ans += A.back(); return ans; } };
1,462
Course Schedule IV
2
checkIfPrerequisite
There are a total of `numCourses` courses you have to take, labeled from `0` to `numCourses - 1`. You are given an array `prerequisites` where `prerequisites[i] = [ai, bi]` indicates that you must take course `ai` first if you want to take course `bi`. * For example, the pair `[0, 1]` indicates that you have to take course `0` before you can take course `1`. Prerequisites can also be indirect. If course `a` is a prerequisite of course `b`, and course `b` is a prerequisite of course `c`, then course `a` is a prerequisite of course `c`. You are also given an array `queries` where `queries[j] = [uj, vj]`. For the `jth` query, you should answer whether course `uj` is a prerequisite of course `vj` or not. Return a boolean array `answer`, where `answer[j]` is the answer to the `jth` query.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def checkIfPrerequisite(self, numCourses: int, prerequisites: List[List[int]], queries: List[List[int]]) -> List[bool]: graph = [[] for _ in range(numCourses)] isPrerequisite = [[False] * numCourses for _ in range(numCourses)] for u, v in prerequisites: graph[u].append(v) for i in range(numCourses): self._dfs(graph, i, isPrerequisite[i]) return [isPrerequisite[u][v] for u, v in queries] def _dfs(self, graph: List[List[int]], u: int, used: List[bool]) -> None: for v in graph[u]: if used[v]: continue used[v] = True self._dfs(graph, v, used)
class Solution { public List<Boolean> checkIfPrerequisite(int numCourses, int[][] prerequisites, int[][] queries) { List<Boolean> ans = new ArrayList<>(); List<Integer>[] graph = new List[numCourses]; for (int i = 0; i < numCourses; ++i) graph[i] = new ArrayList<>(); for (int[] prerequisite : prerequisites) { final int u = prerequisite[0]; final int v = prerequisite[1]; graph[u].add(v); } // isPrerequisite[i][j] := true if course i is a prerequisite of course j boolean[][] isPrerequisite = new boolean[numCourses][numCourses]; // DFS from every course. for (int i = 0; i < numCourses; ++i) dfs(graph, i, isPrerequisite[i]); for (int[] query : queries) { final int u = query[0]; final int v = query[1]; ans.add(isPrerequisite[u][v]); } return ans; } public void dfs(List<Integer>[] graph, int u, boolean[] used) { for (final int v : graph[u]) { if (used[v]) continue; used[v] = true; dfs(graph, v, used); } } }
class Solution { public: vector<bool> checkIfPrerequisite(int numCourses, vector<vector<int>>& prerequisites, vector<vector<int>>& queries) { vector<bool> ans; vector<vector<int>> graph(numCourses); // isPrerequisite[i][j] := true if course i is a prerequisite of course j vector<vector<bool>> isPrerequisite(numCourses, vector<bool>(numCourses)); for (const vector<int>& prerequisite : prerequisites) { const int u = prerequisite[0]; const int v = prerequisite[1]; graph[u].push_back(v); } // DFS from every course. for (int i = 0; i < numCourses; ++i) dfs(graph, i, isPrerequisite[i]); for (const vector<int>& query : queries) { const int u = query[0]; const int v = query[1]; ans.push_back(isPrerequisite[u][v]); } return ans; } void dfs(const vector<vector<int>>& graph, int u, vector<bool>& used) { for (const int v : graph[u]) { if (used[v]) continue; used[v] = true; dfs(graph, v, used); } } };
1,489
Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree
3
findCriticalAndPseudoCriticalEdges
Given a weighted undirected connected graph with `n` vertices numbered from `0` to `n - 1`, and an array `edges` where `edges[i] = [ai, bi, weighti]` represents a bidirectional and weighted edge between nodes `ai` and `bi`. A minimum spanning tree (MST) is a subset of the graph's edges that connects all vertices without cycles and with the minimum possible total edge weight. Find all the critical and pseudo-critical edges in the given graph's minimum spanning tree (MST). An MST edge whose deletion from the graph would cause the MST weight to increase is called a critical edge. On the other hand, a pseudo- critical edge is that which can appear in some MSTs but not all. Note that you can return the indices of the edges in any order.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator, Union class UnionFind: def __init__(self, n: int): self.id = list(range(n)) self.rank = [0] * n def unionByRank(self, u: int, v: int) -> None: i = self.find(u) j = self.find(v) if i == j: return if self.rank[i] < self.rank[j]: self.id[i] = j elif self.rank[i] > self.rank[j]: self.id[j] = i else: self.id[i] = j self.rank[j] += 1 def find(self, u: int) -> int: if self.id[u] != u: self.id[u] = self.find(self.id[u]) return self.id[u] class Solution: def findCriticalAndPseudoCriticalEdges(self, n: int, edges: List[List[int]]) -> List[List[int]]: criticalEdges = [] pseudoCriticalEdges = [] for i in range(len(edges)): edges[i].append(i) edges.sort(key=lambda x: x[2]) def getMSTWeight(firstEdge: List[int], deletedEdgeIndex: int) -> Union[int, float]: mstWeight = 0 uf = UnionFind(n) if firstEdge: uf.unionByRank(firstEdge[0], firstEdge[1]) mstWeight += firstEdge[2] for u, v, weight, index in edges: if index == deletedEdgeIndex: continue if uf.find(u) == uf.find(v): continue uf.unionByRank(u, v) mstWeight += weight root = uf.find(0) if any(uf.find(i) != root for i in range(n)): return math.inf return mstWeight mstWeight = getMSTWeight([], -1) for edge in edges: index = edge[3] if getMSTWeight([], index) > mstWeight: criticalEdges.append(index) elif getMSTWeight(edge, -1) == mstWeight: pseudoCriticalEdges.append(index) return [criticalEdges, pseudoCriticalEdges]
class UnionFind { public UnionFind(int n) { id = new int[n]; rank = new int[n]; for (int i = 0; i < n; ++i) id[i] = i; } public void unionByRank(int u, int v) { final int i = find(u); final int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } public int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } private int[] id; private int[] rank; } class Solution { public List<List<Integer>> findCriticalAndPseudoCriticalEdges(int n, int[][] edges) { List<Integer> criticalEdges = new ArrayList<>(); List<Integer> pseudoCriticalEdges = new ArrayList<>(); // Record the index information, so edges[i] := (u, v, weight, index). for (int i = 0; i < edges.length; ++i) edges[i] = new int[] {edges[i][0], edges[i][1], edges[i][2], i}; // Sort by the weight. Arrays.sort(edges, Comparator.comparingInt(edge -> edge[2])); final int mstWeight = getMSTWeight(n, edges, new int[] {}, -1); for (int[] edge : edges) { final int index = edge[3]; // Deleting the `edge` increases the MST's weight or makes the MST // invalid. if (getMSTWeight(n, edges, new int[] {}, index) > mstWeight) criticalEdges.add(index); // If an edge can be in any MST, we can always add `edge` to the edge set. else if (getMSTWeight(n, edges, edge, -1) == mstWeight) pseudoCriticalEdges.add(index); } return List.of(criticalEdges, pseudoCriticalEdges); } private int getMSTWeight(int n, int[][] edges, int[] firstEdge, int deletedEdgeIndex) { int mstWeight = 0; UnionFind uf = new UnionFind(n); if (firstEdge.length == 4) { uf.unionByRank(firstEdge[0], firstEdge[1]); mstWeight += firstEdge[2]; } for (int[] edge : edges) { final int u = edge[0]; final int v = edge[1]; final int weight = edge[2]; final int index = edge[3]; if (index == deletedEdgeIndex) continue; if (uf.find(u) == uf.find(v)) continue; uf.unionByRank(u, v); mstWeight += weight; } final int root = uf.find(0); for (int i = 0; i < n; ++i) if (uf.find(i) != root) return Integer.MAX_VALUE; return mstWeight; } }
class UnionFind { public: UnionFind(int n) : id(n), rank(n) { iota(id.begin(), id.end(), 0); } void unionByRank(int u, int v) { const int i = find(u); const int j = find(v); if (i == j) return; if (rank[i] < rank[j]) { id[i] = j; } else if (rank[i] > rank[j]) { id[j] = i; } else { id[i] = j; ++rank[j]; } } int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } private: vector<int> id; vector<int> rank; }; class Solution { public: vector<vector<int>> findCriticalAndPseudoCriticalEdges( int n, vector<vector<int>>& edges) { vector<int> criticalEdges; vector<int> pseudoCriticalEdges; // Record the index information, so edges[i] := (u, v, weight, index). for (int i = 0; i < edges.size(); ++i) edges[i].push_back(i); // Sort by the weight. ranges::sort(edges, ranges::less{}, [](const vector<int>& edge) { return edge[2]; }); const int mstWeight = getMSTWeight(n, edges, {}, -1); for (const vector<int>& edge : edges) { const int index = edge[3]; // Deleting the `edge` increases the MST's weight or makes the MST // invalid. if (getMSTWeight(n, edges, {}, index) > mstWeight) criticalEdges.push_back(index); // If an edge can be in any MST, we can always add `edge` to the edge set. else if (getMSTWeight(n, edges, edge, -1) == mstWeight) pseudoCriticalEdges.push_back(index); } return {criticalEdges, pseudoCriticalEdges}; } private: int getMSTWeight(int n, const vector<vector<int>>& edges, const vector<int>& firstEdge, int deletedEdgeIndex) { int mstWeight = 0; UnionFind uf(n); if (!firstEdge.empty()) { uf.unionByRank(firstEdge[0], firstEdge[1]); mstWeight += firstEdge[2]; } for (const vector<int>& edge : edges) { const int u = edge[0]; const int v = edge[1]; const int weight = edge[2]; const int index = edge[3]; if (index == deletedEdgeIndex) continue; if (uf.find(u) == uf.find(v)) continue; uf.unionByRank(u, v); mstWeight += weight; } const int root = uf.find(0); for (int i = 0; i < n; ++i) if (uf.find(i) != root) return INT_MAX; return mstWeight; } };
1,573
Number of Ways to Split a String
2
numWays
Given a binary string `s`, you can split `s` into 3 non-empty strings `s1`, `s2`, and `s3` where `s1 + s2 + s3 = s`. Return the number of ways `s` can be split such that the number of ones is the same in `s1`, `s2`, and `s3`. Since the answer may be too large, return it modulo `109 + 7`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def numWays(self, s: str) -> int: kMod = 1_000_000_007 ones = s.count('1') if ones % 3 != 0: return 0 if ones == 0: n = len(s) return (n - 1) * (n - 2) // 2 % kMod s1End = -1 s2Start = -1 s2End = -1 s3Start = -1 onesSoFar = 0 for i, c in enumerate(s): if c == '1': onesSoFar += 1 if s1End == -1 and onesSoFar == ones // 3: s1End = i elif s2Start == -1 and onesSoFar == ones // 3 + 1: s2Start = i if s2End == -1 and onesSoFar == ones // 3 * 2: s2End = i elif s3Start == -1 and onesSoFar == ones // 3 * 2 + 1: s3Start = i return (s2Start - s1End) * (s3Start - s2End) % kMod
class Solution { public int numWays(String s) { final int MOD = 1_000_000_007; final int ones = (int) s.chars().filter(c -> c == '1').count(); if (ones % 3 != 0) return 0; if (ones == 0) { final long n = s.length(); return (int) ((n - 1) * (n - 2) / 2 % MOD); } int s1End = -1; int s2Start = -1; int s2End = -1; int s3Start = -1; int onesSoFar = 0; for (int i = 0; i < s.length(); ++i) { if (s.charAt(i) == '1') ++onesSoFar; if (s1End == -1 && onesSoFar == ones / 3) s1End = i; else if (s2Start == -1 && onesSoFar == ones / 3 + 1) s2Start = i; if (s2End == -1 && onesSoFar == ones / 3 * 2) s2End = i; else if (s3Start == -1 && onesSoFar == ones / 3 * 2 + 1) s3Start = i; } return (int) ((long) (s2Start - s1End) * (s3Start - s2End) % MOD); } }
class Solution { public: int numWays(string s) { constexpr int kMod = 1'000'000'007; const int ones = ranges::count(s, '1'); if (ones % 3 != 0) return 0; if (ones == 0) { const long n = s.size(); return (n - 1) * (n - 2) / 2 % kMod; } int s1End = -1; int s2Start = -1; int s2End = -1; int s3Start = -1; int onesSoFar = 0; for (int i = 0; i < s.length(); ++i) { if (s[i] == '1') ++onesSoFar; if (s1End == -1 && onesSoFar == ones / 3) s1End = i; else if (s2Start == -1 && onesSoFar == ones / 3 + 1) s2Start = i; if (s2End == -1 && onesSoFar == ones / 3 * 2) s2End = i; else if (s3Start == -1 && onesSoFar == ones / 3 * 2 + 1) s3Start = i; } return static_cast<long>(s2Start - s1End) * (s3Start - s2End) % kMod; } };
1,574
Shortest Subarray to be Removed to Make Array Sorted
2
findLengthOfShortestSubarray
Given an integer array `arr`, remove a subarray (can be empty) from `arr` such that the remaining elements in `arr` are non-decreasing. Return the length of the shortest subarray to remove. A subarray is a contiguous subsequence of the array.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def findLengthOfShortestSubarray(self, arr: List[int]) -> int: n = len(arr) l = 0 r = n - 1 while l < n - 1 and arr[l + 1] >= arr[l]: l += 1 while r > 0 and arr[r - 1] <= arr[r]: r -= 1 ans = min(n - 1 - l, r) i = l j = n - 1 while i >= 0 and j >= r and j > i: if arr[i] <= arr[j]: j -= 1 else: i -= 1 ans = min(ans, j - i) return ans
class Solution { public int findLengthOfShortestSubarray(int[] arr) { final int n = arr.length; int l = 0; int r = n - 1; // arr[0..l] is non-decreasing prefix. while (l < n - 1 && arr[l + 1] >= arr[l]) ++l; // arr[r..n - 1] is non-decreasing suffix. while (r > 0 && arr[r - 1] <= arr[r]) --r; // Remove arr[l + 1..n - 1] or arr[0..r - 1] int ans = Math.min(n - 1 - l, r); // Since arr[0..l] and arr[r..n - 1] are non-decreasing, we place pointers // at the rightmost indices, l and n - 1, and greedily shrink them toward // the leftmost indices, 0 and r, respectively. By removing arr[i + 1..j], // we ensure that `arr` becomes non-decreasing. int i = l; int j = n - 1; while (i >= 0 && j >= r && j > i) { if (arr[i] <= arr[j]) --j; else --i; ans = Math.min(ans, j - i); } return ans; } }
class Solution { public: int findLengthOfShortestSubarray(vector<int>& arr) { const int n = arr.size(); int l = 0; int r = n - 1; // arr[0..l] is non-decreasing. while (l < n - 1 && arr[l + 1] >= arr[l]) ++l; // arr[r..n - 1] is non-decreasing. while (r > 0 && arr[r - 1] <= arr[r]) --r; // Remove arr[l + 1..n - 1] or arr[0..r - 1]. int ans = min(n - 1 - l, r); // Since arr[0..l] and arr[r..n - 1] are non-decreasing, we place pointers // at the rightmost indices, l and n - 1, and greedily shrink them toward // the leftmost indices, 0 and r, respectively. By removing arr[i + 1..j], // we ensure that `arr` becomes non-decreasing. int i = l; int j = n - 1; while (i >= 0 && j >= r && j > i) { if (arr[i] <= arr[j]) --j; else --i; ans = min(ans, j - i); } return ans; } };
1,579
Remove Max Number of Edges to Keep Graph Fully Traversable
3
maxNumEdgesToRemove
Alice and Bob have an undirected graph of `n` nodes and three types of edges: * Type 1: Can be traversed by Alice only. * Type 2: Can be traversed by Bob only. * Type 3: Can be traversed by both Alice and Bob. Given an array `edges` where `edges[i] = [typei, ui, vi]` represents a bidirectional edge of type `typei` between nodes `ui` and `vi`, find the maximum number of edges you can remove so that after removing the edges, the graph can still be fully traversed by both Alice and Bob. The graph is fully traversed by Alice and Bob if starting from any node, they can reach all other nodes. Return the maximum number of edges you can remove, or return `-1` if Alice and Bob cannot fully traverse the graph.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class UnionFind: def __init__(self, n: int): self.count = n 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 self.count -= 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 maxNumEdgesToRemove(self, n: int, edges: List[List[int]]) -> int: alice = UnionFind(n) bob = UnionFind(n) requiredEdges = 0 for type, u, v in sorted(edges, reverse=True): u -= 1 v -= 1 if type == 3: if alice.unionByRank(u, v) | bob.unionByRank(u, v): requiredEdges += 1 elif type == 2: if bob.unionByRank(u, v): requiredEdges += 1 else: if alice.unionByRank(u, v): requiredEdges += 1 if alice.count == 1 and bob.count == 1: return len(edges) - requiredEdges else: return -1
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 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]; } --count; return true; } 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 maxNumEdgesToRemove(int n, int[][] edges) { UnionFind alice = new UnionFind(n); UnionFind bob = new UnionFind(n); int requiredEdges = 0; // Greedily put type 3 edges in the front. Arrays.sort(edges, Comparator.comparingInt(edge -> - edge[0])); for (int[] edge : edges) { final int type = edge[0]; final int u = edge[1] - 1; final int v = edge[2] - 1; switch (type) { case 3: // Can be traversed by Alice and Bob. // Note that we should use | instead of || because if the first // expression is true, short-circuiting will skip the second // expression. if (alice.unionByRank(u, v) | bob.unionByRank(u, v)) ++requiredEdges; break; case 2: // Can be traversed by Bob. if (bob.unionByRank(u, v)) ++requiredEdges; break; case 1: // Can be traversed by Alice. if (alice.unionByRank(u, v)) ++requiredEdges; } } return alice.getCount() == 1 && bob.getCount() == 1 ? edges.length - requiredEdges : -1; } }
class UnionFind { public: UnionFind(int n) : count(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]; } --count; return true; } 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 maxNumEdgesToRemove(int n, vector<vector<int>>& edges) { UnionFind alice(n); UnionFind bob(n); int requiredEdges = 0; // Greedily put type 3 edges in the front. ranges::sort(edges, ranges::greater{}, [](const vector<int>& edge) { return edge[0]; }); for (const vector<int>& edge : edges) { const int type = edge[0]; const int u = edge[1] - 1; const int v = edge[2] - 1; switch (type) { case 3: // Can be traversed by Alice and Bob. // Note that we should use | instead of || because if the first // expression is true, short-circuiting will skip the second // expression. if (alice.unionByRank(u, v) | bob.unionByRank(u, v)) ++requiredEdges; break; case 2: // Can be traversed by Bob. if (bob.unionByRank(u, v)) ++requiredEdges; break; case 1: // Can be traversed by Alice. if (alice.unionByRank(u, v)) ++requiredEdges; break; } } return alice.getCount() == 1 && bob.getCount() == 1 ? edges.size() - requiredEdges : -1; } };
1,582
Special Positions in a Binary Matrix
1
numSpecial
Given an `m x n` binary matrix `mat`, return the number of special positions in `mat`. A position `(i, j)` is called special if `mat[i][j] == 1` and all other elements in row `i` and column `j` are `0` (rows and columns are 0-indexed).
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 numSpecial(self, mat: List[List[int]]) -> int: m = len(mat) n = len(mat[0]) ans = 0 rowOnes = [0] * m colOnes = [0] * n for i in range(m): for j in range(n): if mat[i][j] == 1: rowOnes[i] += 1 colOnes[j] += 1 for i in range(m): for j in range(n): if mat[i][j] == 1 and rowOnes[i] == 1 and colOnes[j] == 1: ans += 1 return ans
class Solution { public int numSpecial(int[][] mat) { final int m = mat.length; final int n = mat[0].length; int ans = 0; int[] rowOnes = new int[m]; int[] colOnes = new int[n]; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (mat[i][j] == 1) { ++rowOnes[i]; ++colOnes[j]; } for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (mat[i][j] == 1 && rowOnes[i] == 1 && colOnes[j] == 1) ++ans; return ans; } }
class Solution { public: int numSpecial(vector<vector<int>>& mat) { const int m = mat.size(); const int n = mat[0].size(); int ans = 0; vector<int> rowOnes(m); vector<int> colOnes(n); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (mat[i][j] == 1) { ++rowOnes[i]; ++colOnes[j]; } for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (mat[i][j] == 1 && rowOnes[i] == 1 && colOnes[j] == 1) ++ans; return ans; } };
1,583
Count Unhappy Friends
2
unhappyFriends
You are given a list of `preferences` for `n` friends, where `n` is always even. For each person `i`, `preferences[i]` contains a list of friends sorted in the order of preference. In other words, a friend earlier in the list is more preferred than a friend later in the list. Friends in each list are denoted by integers from `0` to `n-1`. All the friends are divided into pairs. The pairings are given in a list `pairs`, where `pairs[i] = [xi, yi]` denotes `xi` is paired with `yi` and `yi` is paired with `xi`. However, this pairing may cause some of the friends to be unhappy. A friend `x` is unhappy if `x` is paired with `y` and there exists a friend `u` who is paired with `v` but: * `x` prefers `u` over `y`, and * `u` prefers `x` over `v`. Return the number of unhappy friends.
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 unhappyFriends(self, n: int, preferences: List[List[int]], pairs: List[List[int]]) -> int: ans = 0 matches = [0] * n prefer = [{} for _ in range(n)] for x, y in pairs: matches[x] = y matches[y] = x for i in range(n): for j in range(n - 1): prefer[i][preferences[i][j]] = j for x in range(n): for u in prefer[x].keys(): y = matches[x] v = matches[u] if prefer[x][u] < prefer[x][y] and prefer[u][x] < prefer[u][v]: ans += 1 break return ans
class Solution { public int unhappyFriends(int n, int[][] preferences, int[][] pairs) { int ans = 0; int[] matches = new int[n]; Map<Integer, Integer>[] prefer = new Map[n]; for (int[] pair : pairs) { final int x = pair[0]; final int y = pair[1]; matches[x] = y; matches[y] = x; } for (int i = 0; i < n; ++i) prefer[i] = new HashMap<>(); for (int i = 0; i < n; ++i) for (int j = 0; j < n - 1; ++j) prefer[i].put(preferences[i][j], j); for (int x = 0; x < n; ++x) for (final int u : preferences[x]) { final int y = matches[x]; final int v = matches[u]; if (prefer[x].get(u) < prefer[x].get(y) && prefer[u].get(x) < prefer[u].get(v)) { ++ans; break; } } return ans; } }
class Solution { public: int unhappyFriends(int n, vector<vector<int>>& preferences, vector<vector<int>>& pairs) { int ans = 0; vector<int> matches(n); vector<unordered_map<int, int>> prefer(n); for (const vector<int>& pair : pairs) { const int x = pair[0]; const int y = pair[1]; matches[x] = y; matches[y] = x; } for (int i = 0; i < n; ++i) for (int j = 0; j < n - 1; ++j) prefer[i][preferences[i][j]] = j; for (int x = 0; x < n; ++x) for (const auto& [u, _] : prefer[x]) { const int y = matches[x]; const int v = matches[u]; if (prefer[x][u] < prefer[x][y] && prefer[u][x] < prefer[u][v]) { ++ans; break; } } return ans; } };
1,591
Strange Printer II
3
isPrintable
There is a strange printer with the following two special requirements: * On each turn, the printer will print a solid rectangular pattern of a single color on the grid. This will cover up the existing colors in the rectangle. * Once the printer has used a color for the above operation, the same color cannot be used again. You are given a `m x n` matrix `targetGrid`, where `targetGrid[row][col]` is the color in the position `(row, col)` of the grid. Return `true` if it is possible to print the matrix `targetGrid`, otherwise, return `false`.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator from enum import Enum class State(Enum): kInit = 0 kVisiting = 1 kVisited = 2 class Solution: def isPrintable(self, targetGrid: List[List[int]]) -> bool: kMaxColor = 60 m = len(targetGrid) n = len(targetGrid[0]) graph = [set() for _ in range(kMaxColor + 1)] for color in range(1, kMaxColor + 1): minI = m minJ = n maxI = -1 maxJ = -1 for i in range(m): for j in range(n): if targetGrid[i][j] == color: minI = min(minI, i) minJ = min(minJ, j) maxI = max(maxI, i) maxJ = max(maxJ, j) for i in range(minI, maxI + 1): for j in range(minJ, maxJ + 1): if targetGrid[i][j] != color: graph[color].add(targetGrid[i][j]) states = [State.kInit] * (kMaxColor + 1) def hasCycle(u: int) -> bool: if states[u] == State.kVisiting: return True if states[u] == State.kVisited: return False states[u] = State.kVisiting if any(hasCycle(v) for v in graph[u]): return True states[u] = State.kVisited return False for i in range(1, kMaxColor + 1): if hasCycle(i): return False return True
enum State { INIT, VISITING, VISITED } class Solution { public boolean isPrintable(int[][] targetGrid) { final int MAX_COLOR = 60; final int m = targetGrid.length; final int n = targetGrid[0].length; // graph[u] := {v1, v2} means v1 and v2 cover u Set<Integer>[] graph = new HashSet[MAX_COLOR + 1]; for (int color = 1; color <= MAX_COLOR; ++color) { // Get the rectangle of the current color. int minI = m; int minJ = n; int maxI = -1; int maxJ = -1; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (targetGrid[i][j] == color) { minI = Math.min(minI, i); minJ = Math.min(minJ, j); maxI = Math.max(maxI, i); maxJ = Math.max(maxJ, j); } // Add any color covering the current as the children. graph[color] = new HashSet<>(); for (int i = minI; i <= maxI; ++i) for (int j = minJ; j <= maxJ; ++j) if (targetGrid[i][j] != color) { graph[color].add(targetGrid[i][j]); } } State[] states = new State[MAX_COLOR + 1]; for (int color = 1; color <= MAX_COLOR; ++color) if (hasCycle(graph, color, states)) return false; return true; } private boolean hasCycle(Set<Integer>[] graph, int u, State[] states) { if (states[u] == State.VISITING) return true; if (states[u] == State.VISITED) return false; states[u] = State.VISITING; for (int v : graph[u]) if (hasCycle(graph, v, states)) return true; states[u] = State.VISITED; return false; } }
enum class State { kInit, kVisiting, kVisited }; class Solution { public: bool isPrintable(vector<vector<int>>& targetGrid) { constexpr int kMaxColor = 60; const int m = targetGrid.size(); const int n = targetGrid[0].size(); // graph[u] := {v1, v2} means v1 and v2 cover u vector<unordered_set<int>> graph(kMaxColor + 1); for (int color = 1; color <= kMaxColor; ++color) { // Get the rectangle of the current color. int minI = m; int minJ = n; int maxI = -1; int maxJ = -1; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) if (targetGrid[i][j] == color) { minI = min(minI, i); minJ = min(minJ, j); maxI = max(maxI, i); maxJ = max(maxJ, j); } // Add any color covering the current as the children. for (int i = minI; i <= maxI; ++i) for (int j = minJ; j <= maxJ; ++j) if (targetGrid[i][j] != color) graph[color].insert(targetGrid[i][j]); } vector<State> states(kMaxColor + 1); for (int color = 1; color <= kMaxColor; ++color) if (hasCycle(graph, color, states)) return false; return true; } private: bool hasCycle(const vector<unordered_set<int>>& graph, int u, vector<State>& states) { if (states[u] == State::kVisiting) return true; if (states[u] == State::kVisited) return false; states[u] = State::kVisiting; for (const int v : graph[u]) if (hasCycle(graph, v, states)) return true; states[u] = State::kVisited; return false; } };
1,604
Alert Using Same Key-Card Three or More Times in a One Hour Period
2
alertNames
LeetCode company workers use key-cards to unlock office doors. Each time a worker uses their key-card, the security system saves the worker's name and the time when it was used. The system emits an alert if any worker uses the key-card three or more times in a one-hour period. You are given a list of strings `keyName` and `keyTime` where `[keyName[i], keyTime[i]]` corresponds to a person's name and the time when their key-card was used in a single day. Access times are given in the 24-hour time format "HH:MM", such as `"23:51"` and `"09:49"`. Return a list of unique worker names who received an alert for frequent keycard use. Sort the names in ascending order alphabetically. Notice that `"10:00"` \- `"11:00"` is considered to be within a one-hour period, while `"22:51"` \- `"23:52"` is not considered to be within a one-hour period.
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 alertNames(self, keyName: List[str], keyTime: List[str]) -> List[str]: nameToMinutes = collections.defaultdict(list) for name, time in zip(keyName, keyTime): minutes = self._getMinutes(time) nameToMinutes[name].append(minutes) res=[] for name, minutes in nameToMinutes.items(): if self._hasAlert(minutes): res.append(name) return sorted(res) def _hasAlert(self, minutes: List[int]) -> bool: if len(minutes) > 70: return True minutes.sort() for i in range(2, len(minutes)): if minutes[i - 2] + 60 >= minutes[i]: return True return False def _getMinutes(self, time: str) -> int: h, m = map(int, time.split(':')) return 60 * h + m
class Solution { public List<String> alertNames(String[] keyName, String[] keyTime) { List<String> ans = new ArrayList<>(); HashMap<String, List<Integer>> nameToMinutes = new HashMap<>(); for (int i = 0; i < keyName.length; i++) { final int minutes = getMinutes(keyTime[i]); nameToMinutes.putIfAbsent(keyName[i], new ArrayList<>()); nameToMinutes.get(keyName[i]).add(minutes); } for (Map.Entry<String, List<Integer>> entry : nameToMinutes.entrySet()) { final String name = entry.getKey(); List<Integer> minutes = entry.getValue(); if (hasAlert(minutes)) ans.add(name); } Collections.sort(ans); return ans; } private boolean hasAlert(List<Integer> minutes) { if (minutes.size() > 70) return true; Collections.sort(minutes); for (int i = 2; i < minutes.size(); i++) if (minutes.get(i - 2) + 60 >= minutes.get(i)) return true; return false; } private int getMinutes(String time) { final int h = Integer.parseInt(time.substring(0, 2)); final int m = Integer.parseInt(time.substring(3)); return 60 * h + m; } }
class Solution { public: vector<string> alertNames(vector<string>& keyName, vector<string>& keyTime) { vector<string> ans; unordered_map<string, vector<int>> nameToMinutes; for (int i = 0; i < keyName.size(); ++i) { const int minutes = getMinutes(keyTime[i]); nameToMinutes[keyName[i]].push_back(minutes); } for (auto& [name, minutes] : nameToMinutes) if (hasAlert(minutes)) ans.push_back(name); ranges::sort(ans); return ans; } private: // Returns true if any worker uses the key-card three or more times in an // one-hour period. bool hasAlert(vector<int>& minutes) { if (minutes.size() > 70) return true; ranges::sort(minutes); for (int i = 2; i < minutes.size(); ++i) if (minutes[i - 2] + 60 >= minutes[i]) return true; return false; } int getMinutes(const string& time) { const int h = stoi(time.substr(0, 2)); const int m = stoi(time.substr(3)); return 60 * h + m; } };
1,615
Maximal Network Rank
2
maximalNetworkRank
There is an infrastructure of `n` cities with some number of `roads` connecting these cities. Each `roads[i] = [ai, bi]` indicates that there is a bidirectional road between cities `ai` and `bi`. The network rank of two different cities is defined as the total number of directly connected roads to either city. If a road is directly connected to both cities, it is only counted once. The maximal network rank of the infrastructure is the maximum network rank of all pairs of different cities. Given the integer `n` and the array `roads`, return the maximal network rank of the entire infrastructure.
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 maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int: degrees = [0] * n for u, v in roads: degrees[u] += 1 degrees[v] += 1 maxDegree1 = 0 maxDegree2 = 0 for degree in degrees: if degree > maxDegree1: maxDegree2 = maxDegree1 maxDegree1 = degree elif degree > maxDegree2: maxDegree2 = degree countMaxDegree1 = 0 countMaxDegree2 = 0 for degree in degrees: if degree == maxDegree1: countMaxDegree1 += 1 elif degree == maxDegree2: countMaxDegree2 += 1 if countMaxDegree1 == 1: edgeCount = self._getEdgeCount(roads, degrees, maxDegree1, maxDegree2) + self._getEdgeCount(roads, degrees, maxDegree2, maxDegree1) return maxDegree1 + maxDegree2 - (countMaxDegree2 == edgeCount) else: edgeCount = self._getEdgeCount(roads, degrees, maxDegree1, maxDegree1) maxPossibleEdgeCount = countMaxDegree1 * (countMaxDegree1 - 1) // 2 return 2 * maxDegree1 - (maxPossibleEdgeCount == edgeCount) def _getEdgeCount(self, roads: List[List[int]], degrees: List[int], degreeU: int, degreeV: int) -> int: edgeCount = 0 for u, v in roads: if degrees[u] == degreeU and degrees[v] == degreeV: edgeCount += 1 return edgeCount
class Solution { public int maximalNetworkRank(int n, int[][] roads) { int[] degrees = new int[n]; for (int[] road : roads) { final int u = road[0]; final int v = road[1]; ++degrees[u]; ++degrees[v]; } // Find the first maximum and the second maximum degrees. int maxDegree1 = 0; int maxDegree2 = 0; for (final int degree : degrees) if (degree > maxDegree1) { maxDegree2 = maxDegree1; maxDegree1 = degree; } else if (degree > maxDegree2) { maxDegree2 = degree; } // There can be multiple nodes with `maxDegree1` or `maxDegree2`. // Find the counts of such nodes. int countMaxDegree1 = 0; int countMaxDegree2 = 0; for (final int degree : degrees) if (degree == maxDegree1) ++countMaxDegree1; else if (degree == maxDegree2) ++countMaxDegree2; if (countMaxDegree1 == 1) { // 1. If there is only one node with degree = `maxDegree1`, then we'll // need to use the node with degree = `maxDegree2`. The answer in general // will be (maxDegree1 + maxDegree2), but if the two nodes that we're // considering are connected, then we'll have to subtract 1. final int edgeCount = getEdgeCount(roads, degrees, maxDegree1, maxDegree2) + getEdgeCount(roads, degrees, maxDegree2, maxDegree1); return maxDegree1 + maxDegree2 - (countMaxDegree2 == edgeCount ? 1 : 0); } else { // 2. If there are more than one node with degree = `maxDegree1`, then we // can consider `maxDegree1` twice, and we don't need to use `maxDegree2`. // The answer in general will be 2 * maxDegree1, but if the two nodes that // we're considering are connected, then we'll have to subtract 1. final int edgeCount = getEdgeCount(roads, degrees, maxDegree1, maxDegree1); final int maxPossibleEdgeCount = countMaxDegree1 * (countMaxDegree1 - 1) / 2; return 2 * maxDegree1 - (maxPossibleEdgeCount == edgeCount ? 1 : 0); } } // Returns the number of edges (u, v) where degress[u] == degreeU and // degrees[v] == degreeV. private int getEdgeCount(int[][] roads, int[] degrees, int degreeU, int degreeV) { int edgeCount = 0; for (int[] road : roads) { final int u = road[0]; final int v = road[1]; if (degrees[u] == degreeU && degrees[v] == degreeV) ++edgeCount; } return edgeCount; } }
class Solution { public: int maximalNetworkRank(int n, vector<vector<int>>& roads) { vector<int> degrees(n); for (const vector<int>& road : roads) { const int u = road[0]; const int v = road[1]; ++degrees[u]; ++degrees[v]; } // Find the first maximum and the second maximum degrees. int maxDegree1 = 0; int maxDegree2 = 0; for (const int degree : degrees) { if (degree > maxDegree1) { maxDegree2 = maxDegree1; maxDegree1 = degree; } else if (degree > maxDegree2) { maxDegree2 = degree; } } // There can be multiple nodes with `maxDegree1` or `maxDegree2`. // Find the counts of such nodes. int countMaxDegree1 = 0; int countMaxDegree2 = 0; for (const int degree : degrees) if (degree == maxDegree1) ++countMaxDegree1; else if (degree == maxDegree2) ++countMaxDegree2; if (countMaxDegree1 == 1) { // 1. If there is only one node with degree = `maxDegree1`, then we'll // need to use the node with degree = `maxDegree2`. The answer in general // will be (maxDegree1 + maxDegree2), but if the two nodes that we're // considering are connected, then we'll have to subtract 1. const int edgeCount = getEdgeCount(roads, degrees, maxDegree1, maxDegree2) + getEdgeCount(roads, degrees, maxDegree2, maxDegree1); return maxDegree1 + maxDegree2 - (countMaxDegree2 == edgeCount ? 1 : 0); } else { // 2. If there are more than one node with degree = `maxDegree1`, then we // can consider `maxDegree1` twice, and we don't need to use `maxDegree2`. // The answer in general will be 2 * maxDegree1, but if the two nodes that // we're considering are connected, then we'll have to subtract 1. const int edgeCount = getEdgeCount(roads, degrees, maxDegree1, maxDegree1); const int maxPossibleEdgeCount = countMaxDegree1 * (countMaxDegree1 - 1) / 2; return 2 * maxDegree1 - (maxPossibleEdgeCount == edgeCount ? 1 : 0); } } private: // Returns the number of edges (u, v) where degress[u] == degreeU and // degrees[v] == degreeV. int getEdgeCount(const vector<vector<int>>& roads, const vector<int>& degrees, int degreeU, int degreeV) { int edgeCount = 0; for (const vector<int>& road : roads) { const int u = road[0]; const int v = road[1]; if (degrees[u] == degreeU && degrees[v] == degreeV) ++edgeCount; } return edgeCount; } };
1,616
Split Two Strings to Make Palindrome
2
checkPalindromeFormation
You are given two strings `a` and `b` of the same length. Choose an index and split both strings at the same index, splitting `a` into two strings: `aprefix` and `asuffix` where `a = aprefix + asuffix`, and splitting `b` into two strings: `bprefix` and `bsuffix` where `b = bprefix + bsuffix`. Check if `aprefix + bsuffix` or `bprefix + asuffix` forms a palindrome. When you split a string `s` into `sprefix` and `ssuffix`, either `ssuffix` or `sprefix` is allowed to be empty. For example, if `s = "abc"`, then `"" + "abc"`, `"a" + "bc"`, `"ab" + "c"` , and `"abc" + ""` are valid splits. Return `true` if it is possible to form a palindrome string, otherwise return `false`. Notice that `x + y` denotes the concatenation of strings `x` and `y`.
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 checkPalindromeFormation(self, a: str, b: str) -> bool: return self._check(a, b) or self._check(b, a) def _check(self, a: str, b: str) -> bool: i, j = 0, len(a) - 1 while i < j: if a[i] != b[j]: return self._isPalindrome(a, i, j) or self._isPalindrome(b, i, j) i += 1 j -= 1 return True def _isPalindrome(self, s: str, i: int, j: int) -> bool: while i < j: if s[i] != s[j]: return False i += 1 j -= 1 return True
class Solution { public boolean checkPalindromeFormation(String a, String b) { return check(a, b) || check(b, a); } private boolean check(String a, String b) { for (int i = 0, j = a.length() - 1; i < j; ++i, --j) if (a.charAt(i) != b.charAt(j)) // a[0:i] + a[i..j] + b[j + 1:] or // a[0:i] + b[i..j] + b[j + 1:] return isPalindrome(a, i, j) || isPalindrome(b, i, j); return true; } private boolean isPalindrome(String s, int i, int j) { while (i < j) if (s.charAt(i++) != s.charAt(j--)) return false; return true; } }
class Solution { public: bool checkPalindromeFormation(string a, string b) { return check(a, b) || check(b, a); } private: bool check(const string& a, const string& b) { for (int i = 0, j = a.length() - 1; i < j; ++i, --j) if (a[i] != b[j]) // a[0:i] + a[i..j] + b[j + 1:] or // a[0:i] + b[i..j] + b[j + 1:] return isPalindrome(a, i, j) || isPalindrome(b, i, j); return true; } bool isPalindrome(const string& s, int i, int j) { while (i < j) if (s[i++] != s[j--]) return false; return true; } };
1,617
Count Subtrees With Max Distance Between Cities
3
countSubgraphsForEachDiameter
There are `n` cities numbered from `1` to `n`. You are given an array `edges` of size `n-1`, where `edges[i] = [ui, vi]` represents a bidirectional edge between cities `ui` and `vi`. There exists a unique path between each pair of cities. In other words, the cities form a tree. A subtree is a subset of cities where every city is reachable from every other city in the subset, where the path between each pair passes through only the cities from the subset. Two subtrees are different if there is a city in one subtree that is not present in the other. For each `d` from `1` to `n-1`, find the number of subtrees in which the maximum distance between any two cities in the subtree is equal to `d`. Return an array of size `n-1` where the `dth` element (1-indexed) is the number of subtrees in which the maximum distance between any two cities is equal to `d`. Notice that the distance between the two cities is the number of edges in the path between them.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def countSubgraphsForEachDiameter(self, n: int, edges: List[List[int]]) -> List[int]: maxMask = 1 << n dist = self._floydWarshall(n, edges) ans = [0] * (n - 1) for mask in range(maxMask): maxDist = self._getMaxDist(mask, dist, n) if maxDist > 0: ans[maxDist - 1] += 1 return ans def _floydWarshall(self, n: int, edges: List[List[int]]) -> List[List[int]]: dist = [[n] * n for _ in range(n)] for i in range(n): dist[i][i] = 0 for u, v in edges: dist[u - 1][v - 1] = 1 dist[v - 1][u - 1] = 1 for k in range(n): for i in range(n): for j in range(n): dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]) return dist def _getMaxDist(self, mask: int, dist: List[List[int]], n: int) -> int: maxDist = 0 edgeCount = 0 cityCount = 0 for u in range(n): if (mask >> u) & 1 == 0: continue cityCount += 1 for v in range(u + 1, n): if (mask >> v) & 1 == 0: continue if dist[u][v] == 1: edgeCount += 1 maxDist = max(maxDist, dist[u][v]) if edgeCount == cityCount - 1: return maxDist else: return 0
class Solution { public int[] countSubgraphsForEachDiameter(int n, int[][] edges) { final int maxMask = 1 << n; final int[][] dist = floydWarshall(n, edges); int[] ans = new int[n - 1]; // mask := the subset of the cities for (int mask = 0; mask < maxMask; ++mask) { int maxDist = getMaxDist(mask, dist, n); if (maxDist > 0) ++ans[maxDist - 1]; } return ans; } private int[][] floydWarshall(int n, int[][] edges) { int[][] dist = new int[n][n]; for (int i = 0; i < n; ++i) Arrays.fill(dist[i], n); for (int i = 0; i < n; ++i) dist[i][i] = 0; for (int[] edge : edges) { final int u = edge[0] - 1; final int v = edge[1] - 1; dist[u][v] = 1; dist[v][u] = 1; } for (int k = 0; k < n; ++k) for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) dist[i][j] = Math.min(dist[i][j], dist[i][k] + dist[k][j]); return dist; } private int getMaxDist(int mask, int[][] dist, int n) { int maxDist = 0; int edgeCount = 0; int cityCount = 0; for (int u = 0; u < n; ++u) { if ((mask >> u & 1) == 0) // u is not in the subset. continue; ++cityCount; for (int v = u + 1; v < n; ++v) { if ((mask >> v & 1) == 0) // v is not in the subset. continue; if (dist[u][v] == 1) // u and v are connected. ++edgeCount; maxDist = Math.max(maxDist, dist[u][v]); } } return edgeCount == cityCount - 1 ? maxDist : 0; } }
class Solution { public: vector<int> countSubgraphsForEachDiameter(int n, vector<vector<int>>& edges) { const int maxMask = 1 << n; const vector<vector<int>> dist = floydWarshall(n, edges); vector<int> ans(n - 1); // mask := the subset of the cities for (int mask = 0; mask < maxMask; ++mask) { const int maxDist = getMaxDist(mask, dist, n); if (maxDist > 0) ++ans[maxDist - 1]; } return ans; } private: vector<vector<int>> floydWarshall(int n, const vector<vector<int>>& edges) { vector<vector<int>> dist(n, vector<int>(n, n)); for (int i = 0; i < n; ++i) dist[i][i] = 0; for (const vector<int>& edge : edges) { const int u = edge[0] - 1; const int v = edge[1] - 1; dist[u][v] = 1; dist[v][u] = 1; } for (int k = 0; k < n; ++k) for (int i = 0; i < n; ++i) for (int j = 0; j < n; ++j) dist[i][j] = min(dist[i][j], dist[i][k] + dist[k][j]); return dist; } int getMaxDist(int mask, const vector<vector<int>>& dist, int n) { int maxDist = 0; int edgeCount = 0; int cityCount = 0; for (int u = 0; u < n; ++u) { if ((mask >> u & 1) == 0) // u is not in the subset. continue; ++cityCount; for (int v = u + 1; v < n; ++v) { if ((mask >> v & 1) == 0) // v is not in the subset. continue; if (dist[u][v] == 1) // u and v are connected. ++edgeCount; maxDist = max(maxDist, dist[u][v]); } } return edgeCount == cityCount - 1 ? maxDist : 0; } };
1,627
Graph Connectivity With Threshold
3
areConnected
We have `n` cities labeled from `1` to `n`. Two different cities with labels `x` and `y` are directly connected by a bidirectional road if and only if `x` and `y` share a common divisor strictly greater than some `threshold`. More formally, cities with labels `x` and `y` have a road between them if there exists an integer `z` such that all of the following are true: * `x % z == 0`, * `y % z == 0`, and * `z > threshold`. Given the two integers, `n` and `threshold`, and an array of `queries`, you must determine for each `queries[i] = [ai, bi]` if cities `ai` and `bi` are connected directly or indirectly. (i.e. there is some path between them). Return an array `answer`, where `answer.length == queries.length` and `answer[i]` is `true` if for the `ith` query, there is a path between `ai` and `bi`, or `answer[i]` is `false` if there is no path.
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 areConnected(self, n: int, threshold: int, queries: List[List[int]]) -> List[bool]: uf = UnionFind(n + 1) for z in range(threshold + 1, n + 1): for x in range(z * 2, n + 1, z): uf.unionByRank(z, x) return [uf.find(a) == uf.find(b) for a, b in queries]
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; } public int find(int u) { return id[u] == u ? u : (id[u] = find(id[u])); } private int[] id; private int[] rank; } class Solution { public List<Boolean> areConnected(int n, int threshold, int[][] queries) { List<Boolean> ans = new ArrayList<>(); UnionFind uf = new UnionFind(n + 1); for (int z = threshold + 1; z <= n; ++z) for (int x = z * 2; x <= n; x += z) uf.unionByRank(z, x); for (int[] query : queries) { final int a = query[0]; final int b = query[1]; ans.add(uf.find(a) == uf.find(b)); } return ans; } }
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; } int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } private: vector<int> id; vector<int> rank; }; class Solution { public: vector<bool> areConnected(int n, int threshold, vector<vector<int>>& queries) { vector<bool> ans; UnionFind uf(n + 1); for (int z = threshold + 1; z <= n; ++z) for (int x = z * 2; x <= n; x += z) uf.unionByRank(z, x); for (const vector<int>& query : queries) { const int a = query[0]; const int b = query[1]; ans.push_back(uf.find(a) == uf.find(b)); } return ans; } };
1,631
Path With Minimum Effort
2
minimumEffortPath
You are a hiker preparing for an upcoming hike. You are given `heights`, a 2D array of size `rows x columns`, where `heights[row][col]` represents the height of cell `(row, col)`. You are situated in the top-left cell, `(0, 0)`, and you hope to travel to the bottom-right cell, `(rows-1, columns-1)` (i.e., 0-indexed). You can move up, down, left, or right, and you wish to find a route that requires the minimum effort. A route's effort is the maximum absolute difference in heights between two consecutive cells of the route. Return the minimum effort required to travel from the top-left cell to the bottom-right cell.
import math import itertools import bisect import collections import string import heapq import functools import sortedcontainers from typing import List, Dict, Tuple, Iterator class Solution: def minimumEffortPath(self, heights: List[List[int]]) -> int: dirs = ((0, 1), (1, 0), (0, -1), (-1, 0)) m = len(heights) n = len(heights[0]) diff = [[math.inf] * n for _ in range(m)] seen = set() minHeap = [(0, 0, 0)] diff[0][0] = 0 while minHeap: d, i, j = heapq.heappop(minHeap) if i == m - 1 and j == n - 1: return d seen.add((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 (x, y) in seen: continue newDiff = abs(heights[i][j] - heights[x][y]) maxDiff = max(diff[i][j], newDiff) if diff[x][y] > maxDiff: diff[x][y] = maxDiff heapq.heappush(minHeap, (diff[x][y], x, y))
class Solution { public int minimumEffortPath(int[][] heights) { // d := the maximum difference of (i, j) and its neighbors record T(int i, int j, int d) {} final int[][] DIRS = {{0, 1}, {1, 0}, {0, -1}, {-1, 0}}; final int m = heights.length; final int n = heights[0].length; Queue<T> minHeap = new PriorityQueue<>(Comparator.comparingInt(T::d)); // dist[i][j] := the maximum absolute difference to reach (i, j) int[][] diff = new int[m][n]; Arrays.stream(diff).forEach(A -> Arrays.fill(A, Integer.MAX_VALUE)); boolean[][] seen = new boolean[m][n]; minHeap.offer(new T(0, 0, 0)); diff[0][0] = 0; while (!minHeap.isEmpty()) { final int i = minHeap.peek().i; final int j = minHeap.peek().j; final int d = minHeap.poll().d; if (i == m - 1 && j == n - 1) return d; seen[i][j] = true; for (int[] dir : DIRS) { final int x = i + dir[0]; final int y = j + dir[1]; if (x < 0 || x == m || y < 0 || y == n) continue; if (seen[x][y]) continue; final int newDiff = Math.abs(heights[i][j] - heights[x][y]); final int maxDiff = Math.max(diff[i][j], newDiff); if (diff[x][y] > maxDiff) { diff[x][y] = maxDiff; minHeap.offer(new T(x, y, maxDiff)); } } } throw new IllegalArgumentException(); } }
struct T { int i; int j; int d; // the maximum difference of (i, j) and its neighbors }; class Solution { public: int minimumEffortPath(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(); auto compare = [](const T& a, const T& b) { return a.d > b.d; }; priority_queue<T, vector<T>, decltype(compare)> minHeap(compare); // diff[i][j] := the maximum absolute difference to reach (i, j) vector<vector<int>> diff(m, vector<int>(n, INT_MAX)); vector<vector<bool>> seen(m, vector<bool>(n)); minHeap.emplace(0, 0, 0); diff[0][0] = 0; while (!minHeap.empty()) { const auto [i, j, d] = minHeap.top(); minHeap.pop(); if (i == m - 1 && j == n - 1) return d; seen[i][j] = true; for (const auto& [dx, dy] : kDirs) { const int x = i + dx; const int y = j + dy; if (x < 0 || x == m || y < 0 || y == n) continue; if (seen[x][y]) continue; const int newDiff = abs(heights[i][j] - heights[x][y]); const int maxDiff = max(diff[i][j], newDiff); if (diff[x][y] > maxDiff) { diff[x][y] = maxDiff; minHeap.emplace(x, y, maxDiff); } } } throw; } };
1,632
Rank Transform of a Matrix
3
matrixRankTransform
Given an `m x n` `matrix`, return a new matrix `answer` where `answer[row][col]` is the rank of `matrix[row][col]`. The rank is an integer that represents how large an element is compared to other elements. It is calculated using the following rules: * The rank is an integer starting from `1`. * If two elements `p` and `q` are in the same row or column, then: * If `p < q` then `rank(p) < rank(q)` * If `p == q` then `rank(p) == rank(q)` * If `p > q` then `rank(p) > rank(q)` * The rank should be as small as possible. The test cases are generated so that `answer` is unique under the given rules.
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): self.id = {} def union(self, u: int, v: int) -> None: self.id.setdefault(u, u) self.id.setdefault(v, v) i = self._find(u) j = self._find(v) if i != j: self.id[i] = j def getGroupIdToValues(self) -> Dict[int, List[int]]: groupIdToValues = collections.defaultdict(list) for u in self.id.keys(): groupIdToValues[self._find(u)].append(u) return groupIdToValues 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 matrixRankTransform(self, matrix: List[List[int]]) -> List[List[int]]: m = len(matrix) n = len(matrix[0]) ans = [[0] * n for _ in range(m)] valToGrids = collections.defaultdict(list) maxRankSoFar = [0] * (m + n) for i, row in enumerate(matrix): for j, val in enumerate(row): valToGrids[val].append((i, j)) for _, grids in sorted(valToGrids.items()): uf = UnionFind() for i, j in grids: uf.union(i, j + m) for values in uf.getGroupIdToValues().values(): maxRank = max(maxRankSoFar[i] for i in values) for i in values: maxRankSoFar[i] = maxRank + 1 for i, j in grids: ans[i][j] = maxRankSoFar[i] return ans
class UnionFind { public void union(int u, int v) { id.putIfAbsent(u, u); id.putIfAbsent(v, v); final int i = find(u); final int j = find(v); if (i != j) id.put(i, j); } public Map<Integer, List<Integer>> getGroupIdToValues() { Map<Integer, List<Integer>> groupIdToValues = new HashMap<>(); for (Map.Entry<Integer, Integer> entry : id.entrySet()) { final int u = entry.getKey(); final int i = find(u); groupIdToValues.putIfAbsent(i, new ArrayList<>()); groupIdToValues.get(i).add(u); } return groupIdToValues; } private Map<Integer, Integer> id = new HashMap<>(); private int find(int u) { return id.getOrDefault(u, u) == u ? u : find(id.get(u)); } } class Solution { public int[][] matrixRankTransform(int[][] matrix) { final int m = matrix.length; final int n = matrix[0].length; int[][] ans = new int[m][n]; // {val: [(i, j)]} TreeMap<Integer, List<Pair<Integer, Integer>>> valToGrids = new TreeMap<>(); // rank[i] := the maximum rank of the row or column so far int[] maxRankSoFar = new int[m + n]; for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) { final int val = matrix[i][j]; valToGrids.putIfAbsent(val, new ArrayList<>()); valToGrids.get(val).add(new Pair<>(i, j)); } for (Map.Entry<Integer, List<Pair<Integer, Integer>>> entry : valToGrids.entrySet()) { final int val = entry.getKey(); List<Pair<Integer, Integer>> grids = entry.getValue(); UnionFind uf = new UnionFind(); for (Pair<Integer, Integer> grid : grids) { final int i = grid.getKey(); final int j = grid.getValue(); // Union i-th row with j-th col. uf.union(i, j + m); } for (List<Integer> values : uf.getGroupIdToValues().values()) { // Get the maximum rank of all the included rows and columns. int maxRank = 0; for (final int i : values) maxRank = Math.max(maxRank, maxRankSoFar[i]); // Update all the rows and columns to maxRank + 1. for (final int i : values) maxRankSoFar[i] = maxRank + 1; } for (Pair<Integer, Integer> grid : grids) { final int i = grid.getKey(); final int j = grid.getValue(); ans[i][j] = maxRankSoFar[i]; } } return ans; } }
class UnionFind { public: void union_(int u, int v) { if (!id.contains(u)) id[u] = u; if (!id.contains(v)) id[v] = v; const int i = find(u); const int j = find(v); if (i != j) id[i] = j; } unordered_map<int, vector<int>> getGroupIdToValues() { unordered_map<int, vector<int>> groupIdToValues; for (const auto& [u, _] : id) groupIdToValues[find(u)].push_back(u); return groupIdToValues; } private: unordered_map<int, int> id; int find(int u) { return id[u] == u ? u : id[u] = find(id[u]); } }; class Solution { public: vector<vector<int>> matrixRankTransform(vector<vector<int>>& matrix) { const int m = matrix.size(); const int n = matrix[0].size(); vector<vector<int>> ans(m, vector<int>(n)); // {val: [(i, j)]} map<int, vector<pair<int, int>>> valToGrids; // rank[i] := the maximum rank of the row or column so far vector<int> maxRankSoFar(m + n); for (int i = 0; i < m; ++i) for (int j = 0; j < n; ++j) valToGrids[matrix[i][j]].emplace_back(i, j); for (const auto& [val, grids] : valToGrids) { UnionFind uf; for (const auto& [i, j] : grids) // Union i-th row with j-th col. uf.union_(i, j + m); for (const auto& [groupId, values] : uf.getGroupIdToValues()) { // Get the maximum rank of all the included rows and columns. int maxRank = 0; for (const int i : values) maxRank = max(maxRank, maxRankSoFar[i]); // Update all the rows and columns to maxRank + 1. for (const int i : values) maxRankSoFar[i] = maxRank + 1; } for (const auto& [i, j] : grids) ans[i][j] = maxRankSoFar[i]; } return ans; } };
1,654
Minimum Jumps to Reach Home
2
minimumJumps
A certain bug's home is on the x-axis at position `x`. Help them get there from position `0`. The bug jumps according to the following rules: * It can jump exactly `a` positions forward (to the right). * It can jump exactly `b` positions backward (to the left). * It cannot jump backward twice in a row. * It cannot jump to any `forbidden` positions. The bug may jump forward beyond its home, but it cannot jump to positions numbered with negative integers. Given an array of integers `forbidden`, where `forbidden[i]` means that the bug cannot jump to the position `forbidden[i]`, and integers `a`, `b`, and `x`, return the minimum number of jumps needed for the bug to reach its home. If there is no possible sequence of jumps that lands the bug on position `x`, 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 from enum import Enum class Direction(Enum): kForward = 0 kBackward = 1 class Solution: def minimumJumps(self, forbidden: List[int], a: int, b: int, x: int) -> int: furthest = max(x + a + b, max(pos + a + b for pos in forbidden)) seenForward = {pos for pos in forbidden} seenBackward = {pos for pos in forbidden} q = collections.deque([(Direction.kForward, 0)]) ans = 0 while q: for _ in range(len(q)): dir, pos = q.popleft() if pos == x: return ans forward = pos + a backward = pos - b if forward <= furthest and forward not in seenForward: seenForward.add(forward) q.append((Direction.kForward, forward)) if dir == Direction.kForward and backward >= 0 and backward not in seenBackward: seenBackward.add(backward) q.append((Direction.kBackward, backward)) ans += 1 return -1
enum Direction { FORWARD, BACKWARD } class Solution { public int minimumJumps(int[] forbidden, int a, int b, int x) { int furthest = x + a + b; Set<Integer> seenForward = new HashSet<>(); Set<Integer> seenBackward = new HashSet<>(); for (final int pos : forbidden) { seenForward.add(pos); seenBackward.add(pos); furthest = Math.max(furthest, pos + a + b); } // (direction, position) Queue<Pair<Direction, Integer>> q = new ArrayDeque<>(List.of(new Pair<>(Direction.FORWARD, 0))); for (int ans = 0; !q.isEmpty(); ++ans) for (int sz = q.size(); sz > 0; --sz) { Direction dir = q.peek().getKey(); final int pos = q.poll().getValue(); if (pos == x) return ans; final int forward = pos + a; final int backward = pos - b; if (forward <= furthest && seenForward.add(forward)) q.offer(new Pair<>(Direction.FORWARD, forward)); // It cannot jump backward twice in a row. if (dir == Direction.FORWARD && backward >= 0 && seenBackward.add(backward)) q.offer(new Pair<>(Direction.BACKWARD, backward)); } return -1; } }
enum class Direction { kForward, kBackward }; class Solution { public: int minimumJumps(vector<int>& forbidden, int a, int b, int x) { int furthest = x + a + b; unordered_set<int> seenForward; unordered_set<int> seenBackward; for (const int pos : forbidden) { seenForward.insert(pos); seenBackward.insert(pos); furthest = max(furthest, pos + a + b); } // (direction, position) queue<pair<Direction, int>> q{{{Direction::kForward, 0}}}; for (int ans = 0; !q.empty(); ++ans) for (int sz = q.size(); sz > 0; --sz) { const auto [dir, pos] = q.front(); q.pop(); if (pos == x) return ans; const int forward = pos + a; const int backward = pos - b; if (forward <= furthest && seenForward.insert(forward).second) q.emplace(Direction::kForward, forward); // It cannot jump backward twice in a row. if (dir == Direction::kForward && backward >= 0 && seenBackward.insert(backward).second) q.emplace(Direction::kBackward, backward); } return -1; } };