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