Esempio n. 1
0

class Solution:
    def maxChunksToSorted(self, arr: List[int]) -> int:
        if not arr:
            return 0

        sorted_arr = arr.copy()
        sorted_arr.sort()
        max_l = [None] * len(arr)
        max_l[0] = arr[0]
        for i in range(1, len(arr)):
            max_l[i] = max(max_l[i - 1], arr[i])

        cnt = 0
        min_r = max_l[-1] + 1
        for i in range(len(arr)):
            if max_l[~i] == sorted_arr[~i]:
                if sorted_arr[~i] > min_r:
                    continue

                cnt += 1
                min_r = arr[~i]

        return cnt


assert_value(1, Solution().maxChunksToSorted, arr=[5, 4, 3, 2, 1])
assert_value(4, Solution().maxChunksToSorted, arr=[2, 1, 3, 4, 4])
assert_value(4, Solution().maxChunksToSorted, arr=[2, 1, 4, 4, 3, 5, 7, 6])
Esempio n. 2
0
from test_tool import assert_value


class Solution(object):
    def longestCommonSubsequence(self, text1: str, text2: str) -> str:
        if len(text1) == 0 or len(text2) == 0:
            return ''
        c = []
        for i in range(len(text1) + 1):
            c_inner = [0] * (len(text2) + 1)
            c.append(c_inner)

        for m in range(1, len(text1) + 1):
            for n in range(1, len(text2) + 1):
                if text1[m - 1] == text2[n - 1]:
                    c[m][n] = c[m - 1][n - 1] + 1
                else:
                    c[m][n] = max(c[m - 1][n], c[m][n - 1])

        return c[m][n]


assert_value(4,
             Solution().longestCommonSubsequence,
             text1="ABCBDAB",
             text2="BDCABA")
assert_value(3,
             Solution().longestCommonSubsequence,
             text1="abcde",
             text2="ace")
Esempio n. 3
0
from typing import List
from collections import defaultdict

from test_tool import assert_value


class Solution:
    def bestEvenOddSubsequence(self, arr: List[int]) -> int:
        sum_odd = []
        sum_even = []
        for i in arr:
            if self.is_odd(i):
                prev_sum = 0 if len(sum_even) == 0 else max(sum_even)
                sum_odd.append(prev_sum + i)
            else:
                prev_sum = 0 if len(sum_odd) == 0 else max(sum_odd)
                sum_even.append(prev_sum + i)

        return max(sum_odd[-1:] + sum_even[-1:])

    def is_odd(self, i: int) -> bool:
        return bool(i & 1)


assert_value(15, Solution().bestEvenOddSubsequence, arr=[1, 2, 3, 4, 5])
assert_value(5, Solution().bestEvenOddSubsequence, arr=[2, -2, 1, 3])
Esempio n. 4
0
        options = [i for i in range(1, maxChoosableInteger + 1)]
        options = tuple(options)
        if sum(options) < desiredTotal:
            return False
        return self.check_case(options, desiredTotal, 0, {})

    def check_case(self, options: tuple, desiredTotal: int, currentTotal: int,
                   cache: dict):
        if options in cache:
            return cache[options]
        else:
            cache[options] = False
            if max(options) + currentTotal >= desiredTotal:
                cache[options] = True
            elif options:
                for i, opt in enumerate(options):
                    options_new = (*options[:i], *options[i + 1:])
                    if not self.check_case(options_new, desiredTotal,
                                           currentTotal + opt, cache):
                        cache[options] = True
                        break
            return cache[options]


assert_value(False,
             Solution().canIWin,
             maxChoosableInteger=10,
             desiredTotal=11)
assert_value(True, Solution().canIWin, maxChoosableInteger=10, desiredTotal=0)
assert_value(True, Solution().canIWin, maxChoosableInteger=10, desiredTotal=1)
            if dp[-1] < nums[idx]:
                dp.append(nums[idx])
                continue
            l, r = 0, len(dp) - 1
            loc = r
            while l <= r:
                m = (l + r) // 2
                if dp[m] >= nums[idx]:
                    loc = m
                    r = m - 1
                else:
                    l = m + 1
            dp[loc] = nums[idx]

        return len(dp)

    def lengthOfLIS_DP(self, nums: List[int]) -> int:
        dp = [0] * len(nums)

        for idx in range(len(nums)):
            dp[idx] = 1

            for i in range(idx):
                if nums[idx] > nums[i]:
                    dp[idx] = max(dp[idx], dp[i] + 1)
        return max(dp)


assert_value(4, Solution().lengthOfLIS, nums=[10, 9, 2, 5, 3, 7, 101])
assert_value(3, Solution().lengthOfLIS, nums=[4, 10, 4, 3, 8, 9])
Esempio n. 6
0
'''
165. Compare Version Numbers
https://leetcode.com/problems/compare-version-numbers/
'''
from typing import List

from test_tool import assert_value


class Solution:
    def compareVersion(self, version1: str, version2: str) -> int:
        slot1 = version1.split('.')
        slot2 = version2.split('.')
        for i in range(max(len(slot1), len(slot2))):
            v1 = 0 if i >= len(slot1) else int(slot1[i])
            v2 = 0 if i >= len(slot2) else int(slot2[i])
            if v1 > v2:
                return 1
            if v1 < v2:
                return -1
        return 0


assert_value(0, Solution().compareVersion, version1="1.01", version2="1.001")
assert_value(0, Solution().compareVersion, version1="1.0", version2="1.0.0")
assert_value(-1, Solution().compareVersion, version1="0.1", version2="1.1")
assert_value(1, Solution().compareVersion, version1="1.0.1", version2="1")
assert_value(-1, Solution().compareVersion, version1="7.5.2.4", version2="7.5.3")
            else:
                r = m

        left = l
        # Find the tail
        l, r = mid, len(nums)
        while l < r:
            m = (l + r) >> 1
            if nums[m] <= target:
                l = m + 1
            else:
                r = m
        return [left, l - 1]


assert_value([3, 4],
             Solution().searchRange,
             nums=[5, 7, 7, 8, 8, 10],
             target=8)
assert_value([-1, -1],
             Solution().searchRange,
             nums=[5, 7, 7, 8, 8, 10],
             target=6)
assert_value([-1, -1], Solution().searchRange, nums=[], target=0)
assert_value([0, 0], Solution().searchRange, nums=[1], target=1)
assert_value([0, 0], Solution().searchRange, nums=[1, 3], target=1)
assert_value([2, 5],
             Solution().searchRange,
             nums=[1, 2, 3, 3, 3, 3, 4, 5, 9],
             target=3)
Esempio n. 8
0

def build_nodes(nodes: List[int]) -> ListNode:
    if len(nodes) == 0:
        return []
    if len(nodes) == 1:
        return ListNode(nodes[0])
    return ListNode(nodes[0], build_nodes(nodes[1:]))


def to_array(node: ListNode):
    nodes = []
    while node:
        nodes.append(node.val)
        node = node.next
    return nodes


def test_wrapper(func):
    def func_wrapper(**kwargs):
        res = func(**kwargs)
        return to_array(res)

    return func_wrapper


assert_value([1, 2, 3, 4], test_wrapper(Solution().sortList), head=build_nodes([4, 2, 1, 3]))
assert_value([-1, 0, 3, 4, 5], test_wrapper(Solution().sortList), head=build_nodes([-1, 5, 3, 4, 0]))
assert_value([], test_wrapper(Solution().sortList), head=build_nodes([]))
assert_value([0, 1, 1, 2, 2, 3, 4], test_wrapper(Solution().sortList), head=build_nodes([4, 2, 1, 3, 2, 1, 0]))
Esempio n. 9
0
'''
65. Valid Number
https://leetcode.com/problems/valid-number/
'''
import re
from typing import List

from test_tool import assert_value


class Solution:
    def __init__(self):
        pattern = r"^[+-]?((\d+\.?\d*)|(\.\d+))([eE][+-]?\d+)?$"
        self._prog = re.compile(pattern)

    def isNumber(self, s: str) -> bool:
        return bool(self._prog.search(s))


for case in ["0", ".1", "2", "0089", "-0.1", "+3.14", "4.", "-.9", "2e10", "-90E3", "3e+7", "+6e-1", "53.5e93",
             "-123.456e789"]:
    print(f"{case}:{Solution().isNumber(case)}")
    assert_value(True, Solution().isNumber, s=case)

for case in ["e", ".", "abc", "1a", "1e", "e3", "99e2.5", "--6", "-+3", "95a54e53"]:
    print(f"{case}:{Solution().isNumber(case)}")
    assert_value(False, Solution().isNumber, s=case)
class Solution:
    def smallestDistancePair(self, nums: List[int], k: int) -> int:
        nums = sorted(nums)

        lo = 0
        hi = nums[-1] - nums[0]

        while lo < hi:
            guess = (lo + hi) // 2
            if self.shift_right(nums, guess, k):
                lo = guess + 1
            else:
                hi = guess
        return hi

    def shift_right(self, nums, guess, k):
        i = 0
        j = 1
        cnt = 0
        while i < len(nums):
            while j < len(nums) and nums[j] - nums[i] <= guess:
                j += 1
            cnt += j - i - 1
            i += 1
        return cnt < k


assert_value(0, Solution().smallestDistancePair, nums=[1, 3, 1], k=1)
assert_value(5, Solution().smallestDistancePair, nums=[1, 6, 1], k=3)
assert_value(2, Solution().smallestDistancePair, nums=[9, 10, 7, 10, 6, 1, 5, 4, 9, 8], k=18)
Esempio n. 11
0
            if 'start' == opt_2:
                stack.append((idx_2, t_2))
            else:
                idx_1, t_1 = stack.pop()
                time_cost = t_2 - t_1 + 1
                res[idx_1] += time_cost
                if stack:
                    idx_recursion = stack[-1][0]
                    res[idx_recursion] -= time_cost
            idx += 1

        return res


assert_value([3, 4],
             Solution().exclusiveTime,
             n=2,
             logs=["0:start:0", "1:start:2", "1:end:5", "0:end:6"])
assert_value([8],
             Solution().exclusiveTime,
             n=1,
             logs=[
                 "0:start:0", "0:start:2", "0:end:5", "0:start:6", "0:end:6",
                 "0:end:7"
             ])
assert_value([7, 1],
             Solution().exclusiveTime,
             n=2,
             logs=[
                 "0:start:0", "0:start:2", "0:end:5", "1:start:6", "1:end:6",
                 "0:end:7"
             ])
Esempio n. 12
0
class Solution:
    def minCut(self, s: str) -> int:
        dp = [0] * len(s)
        for i in range(1, len(s)):
            dp[i] = self.check(s[:i + 1])
            for j in range(i):
                dp[i] = min(dp[i], dp[j] + 1 + self.check(s[j + 1:i + 1]))

        return dp[-1]

    def check(self, s):
        if s == s[::-1]:
            return 0
        else:
            return len(s) - 1

        return 0


assert_value(1, Solution().minCut, s="aab")
assert_value(0, Solution().minCut, s="a")
assert_value(1, Solution().minCut, s="ab")
assert_value(0, Solution().minCut, s="bb")
assert_value(1, Solution().minCut, s="abbab")
assert_value(
    1,
    Solution().minCut,
    s="aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaabbaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
)
Esempio n. 13
0
class Solution:
    def quickSort(self, target: List[int]) -> List[int]:
        if len(target) == 1:
            return target
        i = 1
        j = len(target) - 1

        while i < j:
            while target[j] > target[0] and j > 0:
                j -= 1
            while target[i] < target[0] and i < j:
                i += 1
            if i < j:
                target[i], target[j] = target[j], target[i]

        idx = min(i, j)
        if target[0] > target[idx]:
            target[0], target[idx] = target[idx], target[0]

        return self.quickSort(target[:i]) + self.quickSort(target[i:])


assert_value([1, 2, 3, 4, 5, 123],
             Solution().quickSort,
             target=[1, 2, 3, 4, 5, 123])
assert_value([5, 123], Solution().quickSort, target=[5, 123])
assert_value([0, 1, 2, 3, 10, 50],
             Solution().quickSort,
             target=[3, 10, 50, 2, 1, 0])
Esempio n. 14
0
https://leetcode.com/problems/maximum-subarray/
'''
from typing import List

from test_tool import assert_value


class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        m = int(len(nums) / 2)

        if len(nums) == 1:
            return nums[0]

        left = self.maxSubArray(nums[:m])
        right = self.maxSubArray(nums[m:])
        mid_left_arr = nums[:m]
        mid_right_arr = nums[m:]
        for idx in reversed(range(len(mid_left_arr) - 1)):
            mid_left_arr[idx] += mid_left_arr[idx + 1]
        for idx in range(1, len(mid_right_arr)):
            mid_right_arr[idx] += mid_right_arr[idx - 1]

        mid = max(mid_left_arr) + max(mid_right_arr)

        return max(left, right, mid)


assert_value(4, Solution().maxSubArray, nums=[-2, 1, -3, 4])
assert_value(6, Solution().maxSubArray, nums=[-2, 1, -3, 4, -1, 2, 1, -5, 4])
Esempio n. 15
0
        for l in [left_max, left_min]:
            for r in [right_max, right_min]:
                mid = max(mid, l * r)

        return max(left, right, mid)

    def __maxProduct(self, nums: List[int]) -> int:
        dp = [nums[0]]

        for num in nums[1:]:
            dp.append(max(num, dp[-1] * num))

        return max(dp)

    def maxProduct(self, nums: List[int]) -> int:
        maxi, mini, res = 1, 1, -math.inf

        for num in nums:
            acc_maxi = maxi * num
            acc_mini = mini * num
            maxi = max(num, acc_maxi, acc_mini)
            mini = min(num, acc_maxi, acc_mini)

            res = max(res, maxi)
        return res


assert_value(6, Solution().maxProduct, nums=[2, 3, -2, 4])
assert_value(0, Solution().maxProduct, nums=[-2, 0, -1])
assert_value(24, Solution().maxProduct, nums=[-2, 3, -4])
Esempio n. 16
0
        return sorted(scc_map, key=lambda item: len(item[0]), reverse=True)[0][1][0]

    def dfs(self, graph: List[List[int]], i, scc, accessed):
        scc.append(i)
        for j in range(len(graph)):
            if accessed[j]:
                continue
            if not graph[i][j]:
                continue
            accessed[j] = True
            self.dfs(graph, j, scc, accessed)


assert_value(0, Solution().minMalwareSpread, graph=[
    [1, 1, 0],
    [1, 1, 0],
    [0, 0, 1]
], initial=[0, 1])
assert_value(0, Solution().minMalwareSpread, graph=[
    [1, 0, 0],
    [0, 1, 0],
    [0, 0, 1]
], initial=[0, 2])
assert_value(1, Solution().minMalwareSpread, graph=[
    [1, 1, 1],
    [1, 1, 1],
    [1, 1, 1]
], initial=[1, 2])
assert_value(2, Solution().minMalwareSpread, graph=[
    [1, 1, 0],
    [1, 1, 0],
Esempio n. 17
0
    def maxPoints(self, points: List[List[int]]) -> int:
        if len(points) == 1:
            return 1

        slope_cache = defaultdict(set)
        for a in range(len(points) - 1):
            for b in range(a + 1, len(points)):
                p1 = tuple(points[a])
                p2 = tuple(points[b])
                slope = float('inf') if p1[0] == p2[0] else (p1[1] - p2[1]) / (p1[0] - p2[0])
                intercept = p1[0] if p1[0] == p2[0] else p1[1] - slope * p1[0]
                slope_cache[(slope, intercept)] |= set([p1, p2])

        return len(sorted(slope_cache.items(), key=lambda item: len(item[1]), reverse=True)[0][1])


assert_value(1, Solution().maxPoints, points=[[0, 0]])
assert_value(3, Solution().maxPoints, points=[[1, 1], [2, 2], [3, 3]])
assert_value(4, Solution().maxPoints, points=[[1, 1], [3, 2], [5, 3], [4, 1], [2, 3], [1, 4]])
assert_value(6, Solution().maxPoints,
             points=[[7, 3], [19, 19], [-16, 3], [13, 17], [-18, 1], [-18, -17], [13, -3], [3, 7], [-11, 12], [7, 19],
                     [19, -12], [20, -18], [-16, -15], [-10, -15], [-16, -18], [-14, -1], [18, 10], [-13, 8], [7, -5],
                     [-4, -9], [-11, 2], [-9, -9], [-5, -16], [10, 14], [-3, 4], [1, -20], [2, 16], [0, 14], [-14, 5],
                     [15, -11], [3, 11], [11, -10], [-1, -7], [16, 7], [1, -11], [-8, -3], [1, -6], [19, 7], [3, 6],
                     [-1, -2], [7, -3], [-6, -8], [7, 1], [-15, 12], [-17, 9], [19, -9], [1, 0], [9, -10], [6, 20],
                     [-12, -4], [-16, -17], [14, 3], [0, -1], [-18, 9], [-15, 15], [-3, -15], [-5, 20], [15, -14],
                     [9, -17], [10, -14], [-7, -11], [14, 9], [1, -1], [15, 12], [-5, -1], [-17, -5], [15, -2],
                     [-12, 11], [19, -18], [8, 7], [-5, -3], [-17, -1], [-18, 13], [15, -3], [4, 18], [-14, -15],
                     [15, 8], [-18, -12], [-15, 19], [-9, 16], [-9, 14], [-12, -14], [-2, -20], [-3, -13], [10, -7],
                     [-2, -10], [9, 10], [-1, 7], [-17, -6], [-15, 20], [5, -17], [6, -6], [-11, -8]])
Esempio n. 18
0
    def dfs(self, grid, accessed, i, j):
        accessed[i][j] = True
        if i + 1 < len(grid) and not accessed[i + 1][j] and '1' == grid[i +
                                                                        1][j]:
            self.dfs(grid, accessed, i + 1, j)
        if j + 1 < len(
                grid[0]) and not accessed[i][j + 1] and '1' == grid[i][j + 1]:
            self.dfs(grid, accessed, i, j + 1)
        if i > 0 and not accessed[i - 1][j] and '1' == grid[i - 1][j]:
            self.dfs(grid, accessed, i - 1, j)
        if j > 0 and not accessed[i][j - 1] and '1' == grid[i][j - 1]:
            self.dfs(grid, accessed, i, j - 1)


assert_value(1,
             Solution().numIslands,
             grid=[["1", "1", "1", "1", "0"], ["1", "1", "0", "1", "0"],
                   ["1", "1", "0", "0", "0"], ["0", "0", "0", "0", "0"]])

assert_value(3,
             Solution().numIslands,
             grid=[["1", "1", "0", "0", "0"], ["1", "1", "0", "0", "0"],
                   ["0", "0", "1", "0", "0"], ["0", "0", "0", "1", "1"]])

assert_value(1,
             Solution().numIslands,
             grid=[["1", "1", "1"], ["0", "1", "0"], ["1", "1", "1"]])

assert_value(3,
             Solution().numIslands,
             grid=[["1", "0", "1", "1", "0", "1", "1"]])
Esempio n. 19
0
        return self.size == self.limit

    def rebalance(self):
        """
        Rebalances the first and the second half of the storage
        :return:
        """
        while len(self.front_queue) > len(self.back_queue):
            self.back_queue.insert(0, self.front_queue.pop())

        while len(self.front_queue) + 1 < len(self.back_queue):
            self.front_queue.append(self.back_queue.pop(0))


circularDeque = MyCircularDeque(3)
assert_value(True, circularDeque.insertLast, value=1)
assert_value(True, circularDeque.insertLast, value=2)
assert_value(True, circularDeque.insertFront, value=3)
assert_value(False, circularDeque.insertFront, value=4)
assert_value(2, circularDeque.getRear)
assert_value(True, circularDeque.isFull)
assert_value(True, circularDeque.deleteLast)
assert_value(True, circularDeque.insertFront, value=4)
assert_value(4, circularDeque.getFront)

circularDeque = MyCircularDeque(8)
assert_value(True, circularDeque.insertFront, value=5)
assert_value(5, circularDeque.getFront)
assert_value(False, circularDeque.isEmpty)
assert_value(True, circularDeque.deleteFront)
assert_value(True, circularDeque.insertLast, value=3)
Esempio n. 20
0
'''
8. String to Integer (atoi)
https://leetcode.com/problems/string-to-integer-atoi/
'''
import re
from typing import List

from test_tool import assert_value


class Solution:
    def myAtoi(self, s: str) -> int:
        matcher = re.match(r'^\s*([+|-]?\d+)', s)
        digit = 0
        if matcher:
            digit = int(matcher.group())
        if digit < 0:
            return max(-(1 << 31), digit)
        return min((1 << 31) - 1, digit)


assert_value(42, Solution().myAtoi, s="42")
assert_value(-42, Solution().myAtoi, s="   -42")
assert_value(4193, Solution().myAtoi, s="4193 with words")
assert_value(0, Solution().myAtoi, s="words and 987")
assert_value(-2147483648, Solution().myAtoi, s="-91283472332")
assert_value(0, Solution().myAtoi, s=".1")
Esempio n. 21
0
        curr.next = None
        return head


def build_nodes(nodes: List[int]) -> ListNode:
    if len(nodes) == 0:
        return []
    if len(nodes) == 1:
        return ListNode(nodes[0])
    return ListNode(nodes[0], build_nodes(nodes[1:]))


def to_array(node: ListNode):
    nodes = []
    while node:
        nodes.append(node.val)
        node = node.next
    return nodes


def test_wrapper(func):
    def func_wrapper(**kwargs):
        res = func(**kwargs)
        return to_array(res)

    return func_wrapper


assert_value([5, 4, 3, 2, 1], test_wrapper(Solution().reverseList), head=build_nodes([1, 2, 3, 4, 5]))
Esempio n. 22
0
        self._list_cache[self._idx_cache[val]] = self._list_cache[-1]
        self._idx_cache[self._list_cache[-1]] = self._idx_cache[val]
        del self._list_cache[-1]
        del self._idx_cache[val]
        return True

    def getRandom(self) -> int:
        """
        Get a random element from the set.
        """
        return random.choice(self._list_cache)


# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# assert_value(True, obj.insert, val=1)
# assert_value(False, obj.remove, val=2)
# assert_value(True, obj.insert, val=2)
# assert obj.getRandom() in [1, 2]
# assert_value(True, obj.remove, val=1)
# assert_value(False, obj.insert, val=2)
# assert_value(2, obj.getRandom)

obj = RandomizedSet()
assert_value(True, obj.insert, val=0)
assert_value(True, obj.insert, val=1)
assert_value(True, obj.remove, val=0)
assert_value(True, obj.insert, val=2)
assert_value(True, obj.remove, val=1)
assert_value(2, obj.getRandom)
Esempio n. 23
0
class Solution:
    def rob(self, nums: List[int]) -> int:
        if not nums:
            return 0
        if len(nums) == 1:
            return nums[0]
        elif len(nums) == 2:
            return max(nums[0], nums[1])

        # 1 ~ (n - 1)
        dp1 = [None] * (len(nums) - 1)
        dp1[0] = nums[0]
        dp1[1] = max(nums[0], nums[1])

        for i in range(2, len(nums) - 1):
            dp1[i] = max(dp1[i - 1], dp1[i - 2] + nums[i])

        # 2 ~ (n)
        dp2 = [None] * (len(nums) - 1)
        dp2[0] = nums[1]
        dp2[1] = max(nums[1], nums[2])

        for i in range(2, len(nums) - 1):
            dp2[i] = max(dp2[i - 1], dp2[i - 2] + nums[i + 1])

        return max(dp1[len(dp1) - 1], dp2[len(dp2) - 1])


assert_value(3, Solution().rob, nums=[2, 3, 2])
assert_value(4, Solution().rob, nums=[1, 2, 3, 1])
Esempio n. 24
0
        prev_stack = []
        curr_stack = []
        cnt = 0
        prev = s[0]
        for curr in s:
            if curr != prev:
                curr_stack, prev_stack = prev_stack, curr_stack
                curr_stack.clear()
                prev = curr

            curr_stack.append(curr)
            if len(prev_stack) > 0:
                prev_stack.pop()
                cnt += 1

        return cnt


assert_value(6, Solution().countBinarySubstrings, s='00110011')
assert_value(4, Solution().countBinarySubstrings, s='10101')
assert_value(4, Solution().countBinarySubstrings, s="11110110000")
assert_value(
    27,
    Solution().countBinarySubstrings,
    s="11001111101101100111111111111100110010111111111001101111111111")
assert_value(
    5718,
    Solution().countBinarySubstrings,
    s="1100111110110110011111111111110011001011111111100110111111111101010010011110001111110111101111110101110100001111001110011101011000111011101011111110101100101111110101101101111111001111111000011110110101111111111010101001111100010000001001101001100101111110110111110111111010011001110111101110001011100110011010001011100000001101000011100111111010110101110110000011110110111101010110010101111101011111111111110100110101111101111001101011101111111111100111011011010010110111111101110011011111111110001110110000101111111111101110011111011100010111110011110111111110111000110101011101101011101011011100011101101111110111000111110101100110111111001111110111111101101110011101110111110111111101001111100111010111011110011011100101100101010110001011100110111101111110111111111110010101100100111110101011111010101101101111110111111011011001001111001111000111010111100100110011111111100100111100011111011100001001101111011011110010101110001111010000001111110001011000110110111111000110001110101100111111100011100101000111011101110011111111111011111101111110011110111101110011111101110111110111111101111101011010111110110011011101101111100001000101010110110111011111110111111100110111011001111011100011011100101010111111111101110010101101001111011110111011110011000000110111111111101111010110010010111111100111110111000101111010111011111111111000001011111011110111111111111100100100001101101111110010000111101001111111101011010011110011011111000111010000010110011011011011111111110011111101100010111011010111011111111110101110101001101100010111111001101011011111001000101011111011111011110110101111111011011110101111001010110001101011000110110011111101100111110100101111011001000111111110100111101100101111111010110110011110010010111010111111101111101111101001110011101111110001110111010011011101111100011111111101010101101011111111100110111100111101110110010110111100011111010110011111101101101000110110001010001111011100100111111111011111011111111100101111001111110011010010010111111110110001001101111110011111010110011101111110110010000001111111000110111101101111010111110001011100011111011100100000111111011011010010100110101011001111111101111010111111000101110001011111010110110111111111111101101011100000110101001111010110111100011011110100110111111111111111100011011011110011010011100111111111110110111001110100110111010010110111111111111111110001101111011111110111010001101110111110100111110111111110110111111111011111000000101101101111011011111111111111011111000101111111101111111111111111111111100100111000011010001000110110110111111110101111000110100100001111011100111111010100101101010100000111001111101011001111110111011111011010111111011111011010100111011110001000010111110110111110111011011010001010101101111111101111100010010111101100000110100101111010100111101110111011101001101101111001110111101101111101000110110110111101111011011101010001111010011111110111011011100001111111111111000111010101001110010100011011011101111010111110011111010101101010101111110010101111010111001110000011110100011110110111101001110011101110110101111111000101111010111110111110001111110100100001101010001011111110010110110000101111110110111101000101111011111011001100000111111111101010010100111100111110111100011111101111011111100111110000101111011101001001111001101110100100101101111001111111111000110111111101010110011010010011001000111100010100111111001101111110011111000111101011101111110101111101111010110111111101111011111111111100001101100110110011111111101111111101011010010110110011101000111101111110111111011111111110110011100001111110001111011100111111101011111110100110000110011001011111001001110111011110101101101011011011010011110111011100101011011001110001001101011010111000001101011111111101011001111001001100001111110101001111111011100000111100110101010010111101110111011111010110101111101100111111110011011101011101111110011000110111010110011111111111100111011101111011111101111110011101011100101100100111111111111011011100111111111100101111111001111010100011011111001000010111101111111011111100111110111010101111111011111011010000110010111011011000111111011010000111001010101111101011111010111100011001011110111011101110001000111111111100101100110011011011110111111000100010111111011110100111010111111111001011111111111001111110110010011001111100111011110011111000101101111100110011000010100110111101100111110111101111011111100110011011111011001101010111111111010111111100101101011111111011100001111011011111111011111110010100110000000011000010111011101111101111111101101111001011111010110110101011100001110100101001111001111011101101010011010110111101111110101101111100110111101111111101010000101010010001110111000110101101100101111101101011100101111011111101111011110100001011110110111111111011000111111001111010111011010111000101110011010110010111111101111111110111011111010110111111001010111001110110101011000111110000010001101111111000011010110111100010111110010001110011111001110101001000100111011110000100111101101111010011101011010101101000011111111011101111111101111101101110111011111001110111101010111000101010111010111110110010110110111111110111111110011101111011111011111111001111110100110100010110001111101111000111100111101101010110100110110110111001111111111010011011001111111111111010111011101101010100111111011111000110111111011111010111110101110100011110110100100100101111111111111111011110001100011101011101111010111111000000011100111001011110111110110110101100011100101110010001111110011110110101011001101101110001001111110110111111110110011101100111011111011010110011010100011111101101000100010001111110110101000010110111111111111101111001011101011000000101011011101111001010110011111101100110011100101101110111100011011111100110111111111011111001110110000010010111001111110010111111010110010100011101111100111011111011110110101110101101100000001011101001111111000001110010110111011111111011110110111011001111111101000101110111110111001110001001011011010111111011000111111111101111111100000110110011110011010110101101111101000101101011110111001100110111111100111101001000001001110101110111111110011101001011111011010110111100001110110011111010111111011111110111010101110011010100100110111111111011011011010100001001100010111101110110111001110011011111101111001001111111111100110101111011110111111111010101101011110111111101001111001011011110011111110111011110101100011111111011110111101011111011011110111100100101101101111110111110011110100011010111001100011111110101111101100011111111010111011100011110110111101110001111111110011011101111111010010110010100111111111111111010101111111101111010001010001001101110001100101101101001000101111110110110011010101100101101100110011111010011000010111001011110110110101101010011110011101101100011110110011100010111100111101001000011101110111100111010101111011111001100111011010111001101101110000011011000111101111010111001101111111101110111010110111110111011111101101001001110110011111011101111010001111011111100110011100111011111111001111111111010010001111111111001011010010101110111101111111001011110010111101011111111111111000001111100101111111011101101110011110111101110110111101001100000110000111110001010010111111111011011011011111110111101101011011111101101011100111111101001111011110011101101111010111011011100111100101111111011100111101101010101000111111111101101101111111101110011111111101011101011111111010110110101111001111010011100011111011111100001101011010110101100011111101100111110011011110100110001111011110100111010111111010110111111111011001011111111011111100110110111100111110010011110110011011110110001111011100111101101110011101001101100110110111101000011110011010110101111111111011101110110100101110100011110101010101110111011111101111001011011100101011011010111111010111100000011010011111010110101001111111011101000001010011101111100101111011111111111010110111111011100110111001011001011111111101110111011001111111111111110010101101011011010011101110111000011111010111001011111111111101011111011110100011111010010101110111100110111011010000111001001001111110010110011101110101101011011110001001011100000100101111111100101111011010111111101011100011100111011100100101100111101001011110011001100110001000111110110110001110110111100110111111100111111111101110111111111000001110110101110110010011101110100111001001110110110101101111001001111111100101101101101011101111111010011011101011110111010000011101111001101011111011011110111101010101110101100111110011001111101111111011101001101111111111010001011011010110110001110111111110011111111001110100101111011111110100111110111110011111110011111101111110101100100001110110111110101110011100101111100110111111011111100101111110100001010011110010110101111110010010011100001011001011010101110111011111010101101001101010101111110111011110111101111111111110111011111010101011000110001110111111110111010110110111111110101101111001101111010111010110101110011101111011111111010111111111101010011001101111111011011101110011100101110001111011111010110111111110101011111010111111110111110011111110111001011100111111110111110101101110011011110011110101111111111011011101111110110001001111101100100000111110101010000110011111101011111101111100110011111011010011011011010000001101111111011010111100100111100101101011010101010010111110010010111010001011101011111110000011111010110111101011101101101010010011100111011010110011111110010010111111101011111111111101111111110101100101111111110000110011000101011110111010110011001011000011000001000100110011100111111110011011111111001010011110011101101110011011110010101011101011111010101011001111110010111011111001100100110011010011100110111101010111101110101011111111111111000101111111011010111111010010000101111010101001111111001111010000111111010011111111010001010011011100111111001110011111011101010001111111011001001101111111010111101000111001010111001011111111011110001001111111110111111011100110101111010111101011111111100010000111011111011000111111111111100111011001001111001111110000101110100011101111111101110111111111111111110110001101010101110111110111101111110011010111011101111110111111011101111111001111111011110111111"
)
Esempio n. 25
0
'''
1680. Concatenation of Consecutive Binary Numbers
https://leetcode.com/problems/concatenation-of-consecutive-binary-numbers/
'''
from typing import List

from test_tool import assert_value


class Solution:
    def concatenatedBinary(self, n: int) -> int:
        l, ans = 0, 0
        for i in range(1, n + 1):
            if i & (i - 1) == 0:
                l += 1
            ans = ((ans << l) | i) % (10 ** 9 + 7)
        return (ans)


assert_value(1, Solution().concatenatedBinary, n=1)
assert_value(27, Solution().concatenatedBinary, n=3)
assert_value(505379714, Solution().concatenatedBinary, n=12)
Esempio n. 26
0
class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        if len(s) != len(t):
            return False

        cache_s = {}
        cache_t = {}

        for i in range(len(s)):
            si = s[i]
            ti = t[i]

            if si not in cache_s and ti not in cache_t:
                cache_s[si] = i
                cache_t[ti] = i
                continue

            if si not in cache_s or ti not in cache_t:
                return False

            if cache_s[si] != cache_t[ti]:
                return False

        return True


assert_value(True, Solution().isIsomorphic, s="egg", t="add")
assert_value(False, Solution().isIsomorphic, s="foo", t="bar")
assert_value(True, Solution().isIsomorphic, s="paper", t="title")
Esempio n. 27
0
        if len(nums) == 2:
            if nums[0] == nums[1]:
                return [nums]
            return [nums, nums[::-1]]

        num = nums[0]

        res = []
        ps = self.permuteUnique(nums[1:])
        for p in ps:
            for i in range(len(nums)):
                res.append(p[:i] + [num] + p[i:])
                if i < len(p) and p[i] == num:
                    break
        return sorted(res)


assert_value([[]], Solution().permuteUnique, nums=[])

assert_value([[1]], Solution().permuteUnique, nums=[1])

assert_value([[1, 1, 2], [1, 2, 1], [2, 1, 1]],
             Solution().permuteUnique,
             nums=[1, 1, 2])

assert_value(
    [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]],
    Solution().permuteUnique,
    nums=[1, 2, 3])
Esempio n. 28
0
'''
from typing import List

from test_tool import assert_value


class Solution:
    def nextGreatestLetter(self, letters: List[str], target: str) -> str:
        target = ord(target)
        if target < ord(letters[0]) or target >= ord(letters[-1]):
            return letters[0]

        l, r = 0, len(letters)
        while l < r:
            m = (l + r) >> 1
            if ord(letters[m]) <= target:
                l = m + 1
            else:
                r = m

        return letters[l]


assert_value("c", Solution().nextGreatestLetter, letters=["c", "f", "j"], target="a")
assert_value("f", Solution().nextGreatestLetter, letters=["c", "f", "j"], target="c")
assert_value("f", Solution().nextGreatestLetter, letters=["c", "f", "j"], target="d")
assert_value("j", Solution().nextGreatestLetter, letters=["c", "f", "j"], target="g")
assert_value("c", Solution().nextGreatestLetter, letters=["c", "f", "j"], target="j")
assert_value("c", Solution().nextGreatestLetter, letters=["c", "f", "j"], target="k")
assert_value("v", Solution().nextGreatestLetter, letters=["e", "e", "e", "k", "q", "q", "q", "v", "v", "y"], target="q")
Esempio n. 29
0
        left = self.maximumSwap(num_str[:mid])
        right = self.maximumSwap(num_str[mid:])
        left = str(left) + num_str[mid:]
        right = num_str[:mid] + str(right)

        left_swap = 0
        for i in reversed(range(10)[1:]):
            for j in reversed(range(mid, len(num_str))):
                if i == int(num_str[j]):
                    left_swap = j
                    break
            else:
                continue
            break

        right_swap = 0
        while num_str[right_swap] >= num_str[left_swap] and right_swap < left_swap:
            right_swap += 1
        if left_swap == right_swap:
            return int(max(left, right))
        edge = [c for c in num_str]
        edge[left_swap], edge[right_swap] = edge[right_swap], edge[left_swap]
        edge = ''.join(edge)
        return int(max(max(left, right), edge))


assert_value(7236, Solution().maximumSwap, num=2736)
assert_value(9973, Solution().maximumSwap, num=9973)
assert_value(98863, Solution().maximumSwap, num=98368)
assert_value(91000000, Solution().maximumSwap, num=90000001)
Esempio n. 30
0
            line_str = line[0]
            for i in range(space_res):
                line_str += ' ' * (space_even + 1) + line[i + 1]
            for i in range(len(line) - 1 - space_res):
                line_str += ' ' * space_even + line[i + 1 + space_res]
        else:
            line_str = ' '.join(line)
            line_str += ' ' * (cnt_left + 1)

        res.append(line_str)
        line.clear()


assert_value(
    ["This    is    an", "example  of text", "justification.  "],
    Solution().fullJustify,
    words=["This", "is", "an", "example", "of", "text", "justification."],
    maxWidth=16)

assert_value(["What   must   be", "acknowledgment  ", "shall be        "],
             Solution().fullJustify,
             words=["What", "must", "be", "acknowledgment", "shall", "be"],
             maxWidth=16)

assert_value([
    "Science  is  what we", "understand      well", "enough to explain to",
    "a  computer.  Art is", "everything  else  we", "do                  "
],
             Solution().fullJustify,
             words=[
                 "Science", "is", "what", "we", "understand", "well", "enough",