Dataset Viewer
Auto-converted to Parquet Duplicate
task_num
int64
title
string
difficulty
int64
func_name
string
description
string
solution_code
string
tests
list
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...
[ "from data.code_4 import Solution\ndef run_main():\n solution = Solution()\n nums1 = [1, 3]\n nums2 = [2]\n solution.findMedianSortedArrays(nums1, nums2)\n", "from data.code_4 import Solution\ndef run_main():\n solution = Solution()\n nums1 = [1, 2]\n nums2 = [3, 4]\n solution.findMedianSo...
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)] ...
[ "from data.code_10 import Solution\ndef run_main():\n solution = Solution()\n s = \"aa\"\n p = \"a\"\n solution.isMatch(s, p)\n", "from data.code_10 import Solution\ndef run_main():\n solution = Solution()\n s = \"aa\"\n p = \"a*\"\n solution.isMatch(s, p)\n", "from data.code_10 import S...
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()...
[ "from data.code_15 import Solution\ndef run_main():\n solution = Solution()\n nums = [-1, 0, 1, 2, -1, -4]\n solution.threeSum(nums)\n", "from data.code_15 import Solution\ndef run_main():\n solution = Solution()\n nums = [0, 1, 1]\n solution.threeSum(nums)\n", "from data.code_15 import Soluti...
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)] ...
[ "from data.code_44 import Solution\ndef run_main():\n solution = Solution()\n s = \"aa\"\n p = \"a\"\n solution.isMatch(s, p)\n", "from data.code_44 import Solution\ndef run_main():\n solution = Solution()\n s = \"aa\"\n p = \"*\"\n solution.isMatch(s, p)\n", "from data.code_44 import So...
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 =...
[ "from data.code_54 import Solution\ndef run_main():\n solution = Solution()\n matrix = [[1,2,3],[4,5,6],[7,8,9]]\n solution.spiralOrder(matrix)\n", "from data.code_54 import Solution\ndef run_main():\n solution = Solution()\n matrix = [[1,2,3,4],[5,6,7,8],[9,10,11,12]]\n solution.spiralOrder(mat...
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...
[ "from data.code_65 import Solution\ndef run_main():\n solution = Solution()\n s = \"0\"\n print(solution.isNumber(s))\n", "from data.code_65 import Solution\ndef run_main():\n solution = Solution()\n s = \"e\"\n print(solution.isNumber(s))\n", "from data.code_65 import Solution\ndef run_main()...
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 ...
[ "from data.code_73 import Solution\ndef run_main():\n solution = Solution()\n matrix = [[1,1,1],[1,0,1],[1,1,1]]\n solution.setZeroes(matrix)\n", "from data.code_73 import Solution\ndef run_main():\n solution = Solution()\n matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]\n solution.setZeroes(matrix)\n"...
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...
[ "from data.code_97 import Solution\ndef run_main():\n solution = Solution()\n s1 = \"aabcc\"\n s2 = \"dbbca\"\n s3 = \"aadbbcbcac\"\n solution.isInterleave(s1, s2, s3)\n", "from data.code_97 import Solution\ndef run_main():\n solution = Solution()\n s1 = \"aabcc\"\n s2 = \"dbbca\"\n s3 ...
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...
[ "from data.code_126 import Solution\ndef run_main():\n solution = Solution()\n beginWord = \"hit\"\n endWord = \"cog\"\n wordList = [\"hot\",\"dot\",\"dog\",\"lot\",\"log\",\"cog\"]\n solution.findLadders(beginWord, endWord, wordList)\n", "from data.code_126 import Solution\ndef run_main():\n so...
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...
[ "from data.code_130 import Solution\ndef run_main():\n solution = Solution()\n board = [[\"X\",\"X\",\"X\",\"X\"],\n [\"X\",\"O\",\"O\",\"X\"],\n [\"X\",\"X\",\"O\",\"X\"],\n [\"X\",\"O\",\"X\",\"X\"]]\n solution.solve(board)\n", "from data.code_130 import Solution\nde...
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] ...
[ "from data.code_132 import Solution\ndef run_main():\n solution = Solution()\n s = \"aab\"\n solution.minCut(s)\n", "from data.code_132 import Solution\ndef run_main():\n solution = Solution()\n s = \"a\"\n solution.minCut(s)\n", "from data.code_132 import Solution\ndef run_main():\n soluti...
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 [] ...
[ "from data.code_218 import Solution\ndef run_main():\n solution = Solution()\n buildings = [[2,9,10],[3,7,15],[5,12,12],[15,20,10],[19,24,8]]\n solution.getSkyline(buildings)\n", "from data.code_218 import Solution\ndef run_main():\n solution = Solution()\n buildings = [[0,2,3],[2,5,3]]\n soluti...
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): ...
[ "from data.code_227 import Solution\ndef run_main():\n solution = Solution()\n s = \"3+2*2\"\n solution.calculate(s)\n", "from data.code_227 import Solution\ndef run_main():\n solution = Solution()\n s = \" 3/2 \"\n solution.calculate(s)\n", "from data.code_227 import Solution\ndef run_main():...
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): ...
[ "from data.code_289 import Solution\ndef run_main():\n solution = Solution()\n board = [[0,1,0],[0,0,1],[1,1,1],[0,0,0]]\n solution.gameOfLife(board)", "from data.code_289 import Solution\ndef run_main():\n solution = Solution()\n board = [[1,1],[1,0]]\n solution.gameOfLife(board)" ]
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] ...
[ "from data.code_310 import Solution\ndef run_main():\n solution = Solution()\n n = 4\n edges = [[1,0],[1,2],[1,3]]\n solution.findMinHeightTrees(n, edges)\n", "from data.code_310 import Solution\ndef run_main():\n solution = Solution()\n n = 6\n edges = [[3,0],[3,1],[3,2],[3,4],[5,4]]\n so...
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]...
[ "from data.code_327 import Solution\ndef run_main():\n solution = Solution()\n nums = [-2, 5, -1]\n lower = -2\n upper = 2\n solution.countRangeSum(nums, lower, upper)\n", "from data.code_327 import Solution\ndef run_main():\n solution = Solution()\n nums = [0]\n lower = 0\n upper = 0\n...
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)): ...
[ "from data.code_335 import Solution\ndef run_main():\n solution = Solution()\n distance = [2, 1, 1, 2]\n solution.isSelfCrossing(distance)\n", "from data.code_335 import Solution\ndef run_main():\n solution = Solution()\n distance = [1, 2, 3, 4]\n solution.isSelfCrossing(distance)\n", "from da...
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...
[ "from data.code_336 import Solution\ndef run_main():\n solution = Solution()\n words = [\"abcd\",\"dcba\",\"lls\",\"s\",\"sssll\"]\n solution.palindromePairs(words)\n", "from data.code_336 import Solution\ndef run_main():\n solution = Solution()\n words = [\"bat\",\"tab\",\"cat\"]\n solution.pal...
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...
[ "from data.code_391 import Solution\ndef run_main():\n solution = Solution()\n rectangles = [[1,1,3,3],[3,1,4,2],[3,2,4,4],[1,3,2,4],[2,3,3,4]]\n solution.isRectangleCover(rectangles)\n", "from data.code_391 import Solution\ndef run_main():\n solution = Solution()\n rectangles = [[1,1,2,3],[1,3,2,4...
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...
[ "from data.code_402 import Solution\ndef run_main():\n solution = Solution()\n num = \"1432219\"\n k = 3\n solution.removeKdigits(num, k)\n", "from data.code_402 import Solution\ndef run_main():\n solution = Solution()\n num = \"10200\"\n k = 1\n solution.removeKdigits(num, k)\n", "from ...
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...
[ "from data.code_407 import Solution\ndef run_main():\n solution = Solution()\n heightMap = [[1,4,3,1,3,2],[3,2,1,3,2,4],[2,3,3,2,3,1]]\n solution.trapRainWater(heightMap)\n", "from data.code_407 import Solution\ndef run_main():\n solution = Solution()\n heightMap = [[3,3,3,3,3],\n [...
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 ...
[ "from data.code_417 import Solution\ndef run_main():\n solution = Solution()\n heights = [[1,2,2,3,5],\n [3,2,3,4,4],\n [2,4,5,3,1],\n [6,7,1,4,5],\n [5,1,1,2,4]]\n solution.pacificAtlantic(heights)\n", "from data.code_417 import Solution\ndef run_m...
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...
[ "from data.code_420 import Solution\ndef run_main():\n solution = Solution()\n password = \"a\"\n solution.strongPasswordChecker(password)\n", "from data.code_420 import Solution\ndef run_main():\n solution = Solution()\n password = \"aA1\"\n solution.strongPasswordChecker(password)\n", "from ...
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 ...
[ "from data.code_423 import Solution\ndef run_main():\n solution = Solution()\n s = \"owoztneoer\"\n solution.originalDigits(s)\n", "from data.code_423 import Solution\ndef run_main():\n solution = Solution()\n s = \"fviefuro\"\n solution.originalDigits(s)\n" ]
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)...
[ "from data.code_457 import Solution\ndef run_main():\n solution = Solution()\n nums = [2, -1, 1, 2, 2]\n solution.circularArrayLoop(nums)\n", "from data.code_457 import Solution\ndef run_main():\n solution = Solution()\n nums = [-1, -2, -3, -4, -5, 6]\n solution.circularArrayLoop(nums)\n", "fr...
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: ...
[ "from data.code_524 import Solution\ndef run_main():\n solution = Solution()\n s = \"abpcplea\"\n d = [\"ale\",\"apple\",\"monkey\",\"plea\"]\n solution.findLongestWord(s, d)\n", "from data.code_524 import Solution\ndef run_main():\n solution = Solution()\n s = \"abpcplea\"\n d = [\"a\",\"b\"...
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...
[ "from data.code_542 import Solution\ndef run_main():\n solution = Solution()\n mat = [[0,0,0],[0,1,0],[0,0,0]]\n solution.updateMatrix(mat)\n", "from data.code_542 import Solution\ndef run_main():\n solution = Solution()\n mat = [[0,0,0],[0,1,0],[1,1,1]]\n solution.updateMatrix(mat)\n" ]
547
Number of Provinces
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...
[ "from data.code_547 import Solution\ndef run_main():\n solution = Solution()\n isConnected = [[1,1,0],[1,1,0],[0,0,1]]\n solution.findCircleNum(isConnected)\n", "from data.code_547 import Solution\ndef run_main():\n solution = Solution()\n isConnected = [[1,0,0],[0,1,0],[0,0,1]]\n solution.findC...
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...
[ "from data.code_581 import Solution\ndef run_main():\n solution = Solution()\n nums = [2,6,4,8,10,9,15]\n solution.findUnsortedSubarray(nums)\n", "from data.code_581 import Solution\ndef run_main():\n solution = Solution()\n nums = [1,2,3,4]\n solution.findUnsortedSubarray(nums)\n", "from data...
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 ...
[ "from data.code_591 import Solution\ndef run_main():\n solution = Solution()\n code = \"<DIV>This is the first line <![CDATA[<div>]]></DIV>\"\n solution.isValid(code)\n", "from data.code_591 import Solution\ndef run_main():\n solution = Solution()\n code = \"<DIV>>> ![cdata[]] <![CDATA[<div>]>]]>]...
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: ...
[ "from data.code_648 import Solution\ndef run_main():\n solution = Solution()\n dictionary = [\"cat\",\"bat\",\"rat\"]\n sentence = \"the cattle was rattled by the battery\"\n solution.replaceWords(dictionary, sentence)\n", "from data.code_648 import Solution\ndef run_main():\n solution = Solution()...
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...
[ "from data.code_673 import Solution\ndef run_main():\n solution = Solution()\n nums = [1,3,5,4,7]\n solution.findNumberOfLIS(nums)\n", "from data.code_673 import Solution\ndef run_main():\n solution = Solution()\n nums = [2,2,2,2,2]\n solution.findNumberOfLIS(nums)\n" ]
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) -...
[ "from data.code_684 import Solution\ndef run_main():\n solution = Solution()\n edges = [[1,2],[1,3],[2,3]]\n solution.findRedundantConnection(edges)\n", "from data.code_684 import Solution\ndef run_main():\n solution = Solution()\n edges = [[1,2],[2,3],[3,4],[1,4],[1,5]]\n solution.findRedundant...
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) -...
[ "from data.code_685 import Solution\ndef run_main():\n solution = Solution()\n edges = [[1,2],[1,3],[2,3]]\n solution.findRedundantDirectedConnection(edges)\n", "from data.code_685 import Solution\ndef run_main():\n solution = Solution()\n edges = [[1,2],[2,3],[3,4],[4,1],[1,5]]\n solution.findR...
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), (...
[ "from data.code_688 import Solution\ndef run_main():\n solution = Solution()\n n = 3\n k = 2\n row = 0\n column = 0\n solution.knightProbability(n, k, row, column)\n", "from data.code_688 import Solution\ndef run_main():\n solution = Solution()\n n = 1\n k = 0\n row = 0\n column =...
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 =...
[ "from data.code_689 import Solution\ndef run_main():\n solution = Solution()\n nums = [1, 2, 1, 2, 6, 7, 5, 1]\n k = 2\n solution.maxSumOfThreeSubarrays(nums, k)\n", "from data.code_689 import Solution\ndef run_main():\n solution = Solution()\n nums = [1, 2, 1, 2, 1, 2, 1, 2, 1]\n k = 2\n ...
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...
[ "from data.code_691 import Solution\ndef run_main():\n solution = Solution()\n stickers = [\"with\",\"example\",\"science\"]\n target = \"thehat\"\n solution.minStickers(stickers, target)\n", "from data.code_691 import Solution\ndef run_main():\n solution = Solution()\n stickers = [\"notice\",\"...
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...
[ "from data.code_722 import Solution\ndef run_main():\n solution = Solution()\n source = [\"/*Test program */\", \"int main()\", \"{ \", \" // variable declaration \", \"int a, b, c;\", \"/* This is a test\", \" multiline \", \" comment for \", \" testing */\", \"a = b + c;\", \"}\"]\n solution.remo...
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...
[ "from data.code_730 import Solution\ndef run_main():\n solution = Solution()\n s = \"bccb\"\n solution.countPalindromicSubsequences(s)", "from data.code_730 import Solution\ndef run_main():\n solution = Solution()\n s = \"abcdabcdabcdabcdabcdabcdabcdabcddcbadcbadcbadcbadcbadcbadcbadcba\"\n solut...
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: ...
[ "from data.code_735 import Solution\ndef run_main():\n solution = Solution()\n asteroids = [5, 10, -5]\n solution.asteroidCollision(asteroids)\n", "from data.code_735 import Solution\ndef run_main():\n solution = Solution()\n asteroids = [8, -8]\n solution.asteroidCollision(asteroids)\n", "fro...
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,...
[ "from data.code_743 import Solution\ndef run_main():\n solution = Solution()\n times = [[2,1,1],[2,3,1],[3,4,1]]\n n = 4\n k = 2\n solution.networkDelayTime(times, n, k)\n", "from data.code_743 import Solution\ndef run_main():\n solution = Solution()\n times = [[1,2,1]]\n n = 2\n k = 1\...
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...
[ "from data.code_770 import Solution\ndef run_main():\n solution = Solution()\n expression = \"e + 8 - a + 5\"\n evalvars = [\"e\"]\n evalints = [1]\n print(solution.basicCalculatorIV(expression, evalvars, evalints))\n", "from data.code_770 import Solution\ndef run_main():\n solution = Solution()...
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...
[ "from data.code_777 import Solution\ndef run_main():\n solution = Solution()\n start = \"RXXLRXRXL\"\n result = \"XRLXXRRLX\"\n solution.canTransform(start, result)", "from data.code_777 import Solution\ndef run_main():\n solution = Solution()\n start = \"X\"\n result = \"L\"\n solution.ca...
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(...
[ "from data.code_782 import Solution\ndef run_main():\n solution = Solution()\n board = [[0,1,1,0],[0,1,1,0],[1,0,0,1],[1,0,0,1]]\n solution.movesToChessboard(board)\n", "from data.code_782 import Solution\ndef run_main():\n solution = Solution()\n board = [[0,1],[1,0]]\n solution.movesToChessboa...
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 =...
[ "from data.code_786 import Solution\ndef run_main():\n solution = Solution()\n arr = [1, 2, 3, 5]\n k = 3\n solution.kthSmallestPrimeFraction(arr, k)\n", "from data.code_786 import Solution\ndef run_main():\n solution = Solution()\n arr = [1, 7]\n k = 1\n solution.kthSmallestPrimeFraction(...
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...
[ "from data.code_787 import Solution\ndef run_main():\n solution = Solution()\n n = 4\n flights = [[0,1,100],[1,2,100],[2,0,100],[1,3,600],[2,3,200]]\n src = 0\n dst = 3\n k = 1\n solution.findCheapestPrice(n, flights, src, dst, k)\n", "from data.code_787 import Solution\ndef run_main():\n ...
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...
[ "from data.code_794 import Solution\ndef run_main():\n solution = Solution()\n board = [\"O \",\" \",\" \"]\n solution.validTicTacToe(board)\n", "from data.code_794 import Solution\ndef run_main():\n solution = Solution()\n board = [\"XOX\",\" X \",\" \"]\n solution.validTicTacToe(board)\...
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...
[ "from data.code_805 import Solution\ndef run_main():\n solution = Solution()\n nums = [1, 2, 3, 4, 5, 6, 7, 8]\n solution.splitArraySameAverage(nums)\n", "from data.code_805 import Solution\ndef run_main():\n solution = Solution()\n nums = [3, 1]\n solution.splitArraySameAverage(nums)\n" ]
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...
[ "from data.code_815 import Solution\ndef run_main():\n solution = Solution()\n routes = [[1,2,7],[3,6,7]]\n source = 1\n target = 6\n solution.numBusesToDestination(routes, source, target)\n", "from data.code_815 import Solution\ndef run_main():\n solution = Solution()\n routes = [[7,12],[4,5...
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...
[ "from data.code_838 import Solution\ndef run_main():\n solution = Solution()\n dominoes = \"RR.L\"\n solution.pushDominoes(dominoes)\n", "from data.code_838 import Solution\ndef run_main():\n solution = Solution()\n dominoes = \".L.R...LR..L..\"\n solution.pushDominoes(dominoes)\n" ]
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...
[ "from data.code_845 import Solution\ndef run_main():\n solution = Solution()\n arr = [2,1,4,7,3,2,5]\n solution.longestMountain(arr)\n", "from data.code_845 import Solution\ndef run_main():\n solution = Solution()\n arr = [2,2,2]\n solution.longestMountain(arr)\n" ]
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: ...
[ "from data.code_854 import Solution\ndef run_main():\n solution = Solution()\n s1 = \"ab\"\n s2 = \"ba\"\n solution.kSimilarity(s1, s2)\n", "from data.code_854 import Solution\ndef run_main():\n solution = Solution()\n s1 = \"abc\"\n s2 = \"bca\"\n solution.kSimilarity(s1, s2)\n" ]
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) ...
[ "from data.code_861 import Solution\ndef run_main():\n solution = Solution()\n grid = [[0,0,1,1],[1,0,1,0],[1,1,0,0]]\n solution.matrixScore(grid)\n", "from data.code_861 import Solution\ndef run_main():\n solution = Solution()\n grid = [[0]]\n solution.matrixScore(grid)\n" ]
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...
[ "from data.code_866 import Solution\ndef run_main():\n solution = Solution()\n n = 6\n solution.primePalindrome(n)\n", "from data.code_866 import Solution\ndef run_main():\n solution = Solution()\n n = 8\n solution.primePalindrome(n)\n", "from data.code_866 import Solution\ndef run_main():\n ...
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 ...
[ "from data.code_882 import Solution\ndef run_main():\n solution = Solution()\n edges = [[0,1,10],[0,2,1],[1,2,2]]\n maxMoves = 6\n n = 3\n solution.reachableNodes(edges, maxMoves, n)\n", "from data.code_882 import Solution\ndef run_main():\n solution = Solution()\n edges = [[0,1,4],[1,2,6],[0...
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]) ...
[ "from data.code_909 import Solution\ndef run_main():\n solution = Solution()\n board = [[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,-1,-1,-1,-1,-1],[-1,35,-1,-1,13,-1],[-1,-1,-1,-1,-1,-1],[-1,15,-1,-1,-1,-1]]\n solution.snakesAndLadders(board)", "from data.code_909 import Solution\ndef run_main():\n s...
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...
[ "from data.code_913 import Solution\ndef run_main():\n solution = Solution()\n graph = [[2,5],[3],[0,4,5],[1,4,5],[2,3],[0,2,3]]\n solution.catMouseGame(graph)\n", "from data.code_913 import Solution\ndef run_main():\n solution = Solution()\n graph = [[1,3],[0],[3],[0,2]]\n solution.catMouseGame...
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...
[ "from data.code_923 import Solution\ndef run_main():\n solution = Solution()\n arr = [1,1,2,2,3,3,4,4,5,5]\n target = 8\n solution.threeSumMulti(arr, target)\n", "from data.code_923 import Solution\ndef run_main():\n solution = Solution()\n arr = [1,1,2,2,2,2]\n target = 5\n solution.three...
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 ...
[ "from data.code_927 import Solution\ndef run_main():\n solution = Solution()\n arr = [1,0,1,0,1]\n solution.threeEqualParts(arr)\n", "from data.code_927 import Solution\ndef run_main():\n solution = Solution()\n arr = [1,1,0,1,1]\n solution.threeEqualParts(arr)\n", "from data.code_927 import S...
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)) ...
[ "from data.code_935 import Solution\ndef run_main():\n solution = Solution()\n n = 1\n print(solution.knightDialer(n))\n", "from data.code_935 import Solution\ndef run_main():\n solution = Solution()\n n = 2\n print(solution.knightDialer(n))\n", "from data.code_935 import Solution #extreme lo...
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 ...
[ "from data.code_939 import Solution\ndef run_main():\n solution = Solution()\n points = [[1,1],[1,3],[3,1],[3,3],[2,2]]\n solution.minAreaRect(points)\n", "from data.code_939 import Solution\ndef run_main():\n solution = Solution()\n points = [[1,1],[1,3],[3,1],[3,3],[4,1],[4,3]]\n solution.minA...
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) -...
[ "from data.code_952 import Solution\ndef run_main():\n solution = Solution()\n nums = [4, 6, 15, 35]\n solution.largestComponentSize(nums)\n", "from data.code_952 import Solution\ndef run_main():\n solution = Solution()\n nums = [20, 50, 9, 63]\n solution.largestComponentSize(nums)\n", "from d...
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...
[ "from data.code_963 import Solution\ndef run_main():\n solution = Solution()\n points = [[1,2],[2,1],[1,0],[0,1]]\n solution.minAreaFreeRect(points)\n", "from data.code_963 import Solution\ndef run_main():\n solution = Solution()\n points = [[0,1],[2,1],[1,1],[1,0],[2,0]]\n solution.minAreaFreeR...
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(...
[ "from data.code_990 import Solution\ndef run_main():\n solution = Solution()\n equations = [\"a==b\",\"b!=a\"]\n solution.equationsPossible(equations)\n", "from data.code_990 import Solution\ndef run_main():\n solution = Solution()\n equations = [\"b==a\",\"a==b\"]\n solution.equationsPossible(e...
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): ...
[ "from data.code_999 import Solution\ndef run_main():\n solution = Solution()\n board = [[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"p\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"R\",\".\",\".\",\".\",\"p\"],[\".\",\".\",\".\",\".\",\".\",\".\",\".\",\".\"],[\".\",\".\",\".\",\"....
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...
[ "from data.code_1001 import Solution\ndef run_main():\n solution = Solution()\n n = 5\n lamps = [[0,0],[4,4]]\n queries = [[1,1],[1,0]]\n solution.gridIllumination(n, lamps, queries)\n", "from data.code_1001 import Solution\ndef run_main():\n solution = Solution()\n n = 5\n lamps = [[0,0],...
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) ...
[ "from data.code_1093 import Solution\ndef run_main():\n solution = Solution()\n count = [0,1,3,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0...
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...
[ "from data.code_1129 import Solution\ndef run_main():\n solution = Solution()\n n = 3\n redEdges = [[0,1],[1,2]]\n blueEdges = []\n solution.shortestAlternatingPaths(n, redEdges, blueEdges)\n", "from data.code_1129 import Solution\ndef run_main():\n solution = Solution()\n n = 3\n redEdges...
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] ...
[ "from data.code_1139 import Solution\ndef run_main():\n solution = Solution()\n grid = [[1,1,1],[1,0,1],[1,1,1]]\n solution.largest1BorderedSquare(grid)\n", "from data.code_1139 import Solution\ndef run_main():\n solution = Solution()\n grid = [[1,1,0,0]]\n solution.largest1BorderedSquare(grid)\...
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 =...
[ "from data.code_1162 import Solution\ndef run_main():\n solution = Solution()\n grid = [[1,0,1],[0,0,0],[1,0,1]]\n solution.maxDistance(grid)\n", "from data.code_1162 import Solution\ndef run_main():\n solution = Solution()\n grid = [[1,0,0],[0,0,0],[0,0,0]]\n solution.maxDistance(grid)\n" ]
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) -...
[ "from data.code_1202 import Solution\ndef run_main():\n solution = Solution()\n s = \"dcab\"\n pairs = [[0,3],[1,2]]\n solution.smallestStringWithSwaps(s, pairs)\n", "from data.code_1202 import Solution\ndef run_main():\n solution = Solution()\n s = \"dcab\"\n pairs = [[0,3],[1,2],[0,2]]\n ...
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...
[ "from data.code_1210 import Solution\ndef run_main():\n solution = Solution()\n grid = [\n [0, 0, 0, 0, 0, 1],\n [1, 1, 0, 0, 1, 0],\n [0, 0, 0, 0, 1, 1],\n [0, 0, 1, 0, 1, 0],\n [0, 1, 1, 0, 0, 0],\n [0, 1, 1, 0, 0, 0]\n ]\n solution.minimumMoves(grid)\n", "f...
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...
[ "from data.code_1253 import Solution\ndef run_main():\n solution = Solution()\n upper = 2\n lower = 1\n colsum = [1, 1, 1]\n solution.reconstructMatrix(upper, lower, colsum)\n", "from data.code_1253 import Solution\ndef run_main():\n solution = Solution()\n upper = 2\n lower = 3\n colsu...
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) ->...
[ "from data.code_1254 import Solution\ndef run_main():\n solution = Solution()\n grid = [[1,1,1,1,1,1,1,0],\n [1,0,0,0,0,1,1,0],\n [1,0,1,0,1,1,1,0],\n [1,0,0,0,0,1,0,1],\n [1,1,1,1,1,1,1,0]]\n solution.closedIsland(grid)\n", "from data.code_1254 import Solution...
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...
[ "from data.code_1263 import Solution\ndef run_main():\n solution = Solution()\n grid = [\n [\"#\",\"#\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\"T\",\"#\",\"#\",\"#\",\"#\"],\n [\"#\",\".\",\".\",\"B\",\".\",\"#\"],\n [\"#\",\".\",\"#\",\"#\",\".\",\"#\"],\n [\"#\",\".\",\".\",\...
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 ...
[ "from data.code_1267 import Solution\ndef run_main():\n solution = Solution()\n grid = [[1,0],[0,1]]\n solution.countServers(grid)\n", "from data.code_1267 import Solution\ndef run_main():\n solution = Solution()\n grid = [[1,0],[1,1]]\n solution.countServers(grid)\n", "from data.code_1267 imp...
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) ...
[ "from data.code_1284 import Solution\ndef run_main():\n solution = Solution()\n mat = [[0, 0], [0, 1]]\n solution.minFlips(mat)\n", "from data.code_1284 import Solution\ndef run_main():\n solution = Solution()\n mat = [[0]]\n solution.minFlips(mat)\n", "from data.code_1284 import Solution\ndef...
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 == ...
[ "from data.code_1293 import Solution\ndef run_main():\n solution = Solution()\n grid = [[0,0,0],[1,1,0],[0,0,0],[0,1,1],[0,0,0]]\n k = 1\n solution.shortestPath(grid, k)\n", "from data.code_1293 import Solution\ndef run_main():\n solution = Solution()\n grid = [[0,1,1],[1,1,1],[1,0,0]]\n k = ...
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), ...
[ "from data.code_1301 import Solution\ndef run_main():\n solution = Solution()\n board = [\"E23\",\"2X2\",\"12S\"]\n solution.pathsWithMaxScore(board)\n", "from data.code_1301 import Solution\ndef run_main():\n solution = Solution()\n board = [\"E12\",\"1X1\",\"21S\"]\n solution.pathsWithMaxScore...
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 ...
[ "from data.code_1334 import Solution\ndef run_main():\n solution = Solution()\n n = 4\n edges = [[0,1,3],[1,2,1],[1,3,4],[2,3,1]]\n distanceThreshold = 4\n solution.findTheCity(n, edges, distanceThreshold)\n", "from data.code_1334 import Solution\ndef run_main():\n solution = Solution()\n 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 + ...
[ "from data.code_1340 import Solution\ndef run_main():\n solution = Solution()\n arr = [6,4,14,6,8,13,9,7,10,6,12]\n d = 2\n solution.maxJumps(arr, d)\n", "from data.code_1340 import Solution\ndef run_main():\n solution = Solution()\n arr = [3,3,3,3,3]\n d = 3\n solution.maxJumps(arr, d)\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...
[ "from data.code_1345 import Solution\ndef run_main():\n solution = Solution()\n arr = [100,-23,-23,404,100,23,23,23,3,404]\n solution.minJumps(arr)\n", "from data.code_1345 import Solution\ndef run_main():\n solution = Solution()\n arr = [7]\n solution.minJumps(arr)\n", "from data.code_1345 im...
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)] ...
[ "from data.code_1377 import Solution\ndef run_main():\n solution = Solution()\n n = 7\n edges = [[1,2],[1,3],[1,7],[2,4],[2,6],[3,5]]\n t = 2\n target = 4\n solution.frogPosition(n, edges, t, target)\n", "from data.code_1377 import Solution\ndef run_main():\n solution = Solution()\n n = 7\...
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 ...
[ "from data.code_1417 import Solution\ndef run_main():\n solution = Solution()\n s = \"a0b1c2\"\n solution.reformat(s)\n", "from data.code_1417 import Solution\ndef run_main():\n solution = Solution()\n s = \"leetcode\"\n solution.reformat(s)\n", "from data.code_1417 import Solution\ndef run_ma...
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]: ...
[ "from data.code_1462 import Solution\ndef run_main():\n solution = Solution()\n numCourses = 2\n prerequisites = [[1, 0]]\n queries = [[0, 1], [1, 0]]\n solution.checkIfPrerequisite(numCourses, prerequisites, queries)\n", "from data.code_1462 import Solution\ndef run_main():\n solution = Solutio...
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:...
[ "from data.code_1489 import Solution\ndef run_main():\n solution = Solution()\n n = 5\n edges = [[0,1,1],[1,2,1],[2,3,2],[0,3,2],[0,4,3],[3,4,3],[1,4,6]]\n solution.findCriticalAndPseudoCriticalEdges(n, edges)\n", "from data.code_1489 import Solution\ndef run_main():\n solution = Solution()\n n ...
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 ...
[ "from data.code_1573 import Solution\ndef run_main():\n solution = Solution()\n s = \"10101\"\n solution.numWays(s)\n", "from data.code_1573 import Solution\ndef run_main():\n solution = Solution()\n s = \"1001\"\n solution.numWays(s)\n", "from data.code_1573 import Solution\ndef run_main():\n...
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...
[ "from data.code_1574 import Solution\ndef run_main():\n solution = Solution()\n arr = [1,2,3,10,4,2,3,5]\n solution.findLengthOfShortestSubarray(arr)\n", "from data.code_1574 import Solution\ndef run_main():\n solution = Solution()\n arr = [5,4,3,2,1]\n solution.findLengthOfShortestSubarray(arr)...
End of preview. Expand in Data Studio

LLM Path Test Generation

This dataset contains one row per programming problem. The split is test.

Fields

  • task_num: LeetCode problem id.
  • title: Problem title.
  • difficulty: Numeric difficulty label from the source metadata.
  • func_name: Name of the function under test.
  • description: Problem statement text.
  • solution_code: Full Python source from data/code_<task_num>.py.
  • tests: List of full Python test-runner source files for the problem, ordered by testcase id.

Python File Organization

solution_code is the complete contents of the corresponding solution file:

data/code_<task_num>.py

Each item in tests is the complete contents of a generated test runner:

run_code_generated/run_<task_num>_<testcase_id>.py

The test runners import Solution from data.code_<task_num>, define run_main(), construct inputs, and call the target method.

Downloads last month
12