This is the multi-page printable view of this section. Click here to print.

Return to the regular view of this page.

Python

Python projects

1 - Leetcode submissions

1.1 - 2025-08-13 14:56:30 +0000 UTC

Power of Three

Code

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        if n <= 0:
            return False
        while n % 3 == 0:
            n //= 3
        return n == 1 

1.2 - 2025-08-13 14:55:25 +0000 UTC

Power of Three

Code

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        if n <= 0:
            return False
        if n == 1:
            return True
        while n > 1:
            if n % 3 != 0:
                return False
            n //= 3
        return True

1.3 - 2025-08-12 14:49:12 +0000 UTC

Ways to Express an Integer as Sum of Powers

Code

class Solution:
    def numberOfWays(self, n: int, x: int) -> int:
        MOD = 10**9 + 7
        dp = [0] * (n + 1)
        dp[0] = 1

        for i in range(1, n + 1):
            val = i**x
            if val > n:
                break
            for j in range(n, val - 1, -1):
                dp[j] = (dp[j] + dp[j - val]) % MOD

        return dp[n]

1.4 - 2025-08-11 15:03:04 +0000 UTC

Range Product Queries of Powers

Code

class Solution:
    def productQueries(self, n: int, queries: List[List[int]]) -> List[int]:
        mod = 10**9 + 7

        bins, rep = [], 1
        while n > 0:
            if n % 2 == 1:
                bins.append(rep)
            n //= 2
            rep *= 2

        m = len(bins)
        results = [[0] * m for _ in range(m)]
        for i in range(m):
            cur = 1
            for j in range(i, m):
                cur = cur * bins[j] % mod
                results[i][j] = cur

        ans = []
        for left, right in queries:
            ans.append(results[left][right])
        return ans

1.5 - 2025-08-10 10:08:24 +0000 UTC

Goal Parser Interpretation

Code

class Solution:
    def interpret(self, command: str) -> str:
        stack = []
        res = []
        for char in command:
            if char == ")":
                if stack:
                    res.extend(stack)
                    stack.clear()
                else:
                    res.append("o")
            elif char == "G":
                res.append("G")
            elif char != "(":
                stack.append(char)
        return "".join(res)

1.6 - 2025-08-10 10:03:22 +0000 UTC

Maximum Repeating Substring

Code

class Solution:
    def maxRepeating(self, sequence: str, word: str) -> int:
        temp, res = word, 0
        while temp in sequence:
            res += 1
            temp += word
        return res

1.7 - 2025-08-10 09:45:06 +0000 UTC

Defuse the Bomb

Code

class Solution:
    def decrypt(self, code: List[int], k: int) -> List[int]:
        length = len(code)
        result = [0 for _ in range(length)]
        if k == 0:
            return result
        start, end, window_sum = 1, k + 1, 0
        if k < 0:
            start = length - (-k)
            end = length
        for i in range(start, end):
            window_sum += code[i]
        for i in range(length):
            result[i] = window_sum
            window_sum -= code[start % length]
            window_sum += code[end % length]
            start += 1
            end += 1
        return result

1.8 - 2025-08-10 09:15:52 +0000 UTC

Get Maximum in Generated Array

Code

class Solution:
    def getMaximumGenerated(self, n: int) -> int:
        if n == 0 or n == 1:
            return n
        nums = [0] * (n + 1)
        nums[1] = 1
        res = 1
        for i in range(2, n + 1):
            if i % 2 == 0:
                val = nums[i // 2]
            else:
                val = nums[i // 2] + nums[(i // 2) + 1]
            nums[i] = val
            res = max(res, val)
        return res

1.9 - 2025-08-10 08:45:24 +0000 UTC

Check Array Formation Through Concatenation

Code

class Solution:
    def canFormArray(self, arr: List[int], pieces: List[List[int]]) -> bool:
        num_to_piece = {}
        for i, nums in enumerate(pieces):
            for num in nums:
                num_to_piece[num] = i
        i = 0
        length = len(arr)
        while i < length:
            num1 = arr[i]
            if num1 not in num_to_piece:
                return False
            piece = pieces[num_to_piece[num1]]
            for j, num2 in enumerate(piece):
                if i + j >= length:
                    return False
                num1 = arr[i + j]
                if num1 != num2:
                    return False
            i += len(piece)
        return True

1.10 - 2025-08-10 08:25:09 +0000 UTC

Sort Array by Increasing Frequency

Code

class Solution:
    def frequencySort(self, nums: List[int]) -> List[int]:
        freqs = collections.defaultdict(int)
        for num in nums:
            freqs[num] += 1
        nums.sort(key=lambda val: (freqs[val], -val))
        return nums

1.11 - 2025-08-10 08:02:20 +0000 UTC

Slowest Key

Code

class Solution:
    def slowestKey(self, releaseTimes: List[int], keysPressed: str) -> str:
        max_key, max_dur = keysPressed[0], releaseTimes[0]
        for i, num in enumerate(releaseTimes[1:], 1):
            dur = num - releaseTimes[i - 1]
            cur_key = keysPressed[i]
            if dur > max_dur or (dur == max_dur and cur_key > max_key):
                max_dur = dur
                max_key = cur_key
        return max_key

1.12 - 2025-08-10 07:27:29 +0000 UTC

Reordered Power of 2

Code

class Solution:
    def reorderedPowerOf2(self, n: int) -> bool:
        if n > 0 and n & (n - 1) == 0:
            return True
        def count_digits(num: int, out: list[int]) -> None:
            while num > 0:
                out.append(num % 10)
                num //= 10
            out.sort()
        target = []
        count_digits(n, target)
        cur = []
        for i in range(31):
            cur.clear()
            count_digits(1 << i, cur)
            if cur == target:
                return True
        return False

1.13 - 2025-08-09 13:43:21 +0000 UTC

Mean of Array After Removing Some Elements

Code

class Solution:
    def trimMean(self, arr: List[int]) -> float:
        arr.sort()
        length = len(arr)
        interval = length // 20
        res = sum(arr[interval:length - interval])
        res = (res / (length - interval * 2))
        return res

1.14 - 2025-08-09 13:34:28 +0000 UTC

Crawler Log Folder

Code

class Solution:
    def minOperations(self, logs: List[str]) -> int:
        depth = 0
        for op in logs:
            if op == "../":
                depth = max(depth - 1, 0)
            elif op == "./":
                pass
            else:
                depth += 1
        return depth

1.15 - 2025-08-09 13:31:49 +0000 UTC

Rearrange Spaces Between Words

Code

class Solution:
    def reorderSpaces(self, text: str) -> str:
        res = []
        cur_word = []
        space_count = 0
        for char in text:
            if char == " ":
                space_count += 1
                if cur_word:
                    res.append("".join(cur_word))
                    cur_word.clear()
            else:
                cur_word.append(char)
        if cur_word:
            res.append("".join(cur_word))
        words = len(res) - 1
        if words == 0:
            join_str = ""
            rem_str = " " * space_count
        else:
            join_str = " " * (space_count // words) 
            rem_str = " " * (space_count % words)
        return "".join((join_str.join(res), rem_str))

1.16 - 2025-08-09 13:17:16 +0000 UTC

Sum of All Odd Length Subarrays

Code

class Solution:
    def sumOddLengthSubarrays(self, arr: List[int]) -> int:
        length = len(arr)
        answer = 0
        for i, num in enumerate(arr):
            left, right = i, length - i - 1
            odd_left, odd_right = (left // 2) + 1, (right // 2) + 1
            even_left, even_right = (left + 1) // 2, (right + 1) // 2
            sub_count = (odd_left * odd_right) + (even_left * even_right)
            answer += num * sub_count
        return answer

1.17 - 2025-08-09 12:53:09 +0000 UTC

Sum of All Odd Length Subarrays

Code

class Solution:
    def sumOddLengthSubarrays(self, arr: List[int]) -> int:
        res = 0
        for i in range(len(arr)):
            cur_sum = 0
            for j in range(i, len(arr)):
                cur_sum += arr[j]
                if (j - i + 1) % 2 != 0:
                    res += cur_sum
        return res

1.18 - 2025-08-09 08:14:40 +0000 UTC

Power of Two

Code

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        return n > 0 and (n & (n - 1)) == 0

1.19 - 2025-08-08 15:19:33 +0000 UTC

Soup Servings

Code

class Solution:
    def soupServings(self, n: int) -> float:
        m = ceil(n / 25)
        dp = collections.defaultdict(dict)

        def calculate_dp(i: int, j: int) -> float:
            if i <= 0 and j <= 0:
                return 0.5
            if i <= 0:
                return 1.0
            if j <= 0:
                return 0.0
            if i in dp and j in dp[i]:
                return dp[i][j]

            dp[i][j] = (
                calculate_dp(i - 4, j)
                + calculate_dp(i - 3, j - 1)
                + calculate_dp(i - 2, j - 2)
                + calculate_dp(i - 1, j - 3)
            ) / 4.0
            return dp[i][j]

        for k in range(1, m + 1):
            if calculate_dp(k, k) > 1 - 1e-5:
                return 1.0
        return calculate_dp(m, m)

1.20 - 2025-08-07 14:15:08 +0000 UTC

Find the Maximum Number of Fruits Collected

Code

class Solution:
    def maxCollectedFruits(self, fruits):
        n = len(fruits)
        ans = sum(fruits[i][i] for i in range(n))

        def dp():
            prev = [float("-inf")] * n
            curr = [float("-inf")] * n
            prev[n - 1] = fruits[0][n - 1]
            for i in range(1, n - 1):
                for j in range(max(n - 1 - i, i + 1), n):
                    best = prev[j]
                    if j - 1 >= 0:
                        best = max(best, prev[j - 1])
                    if j + 1 < n:
                        best = max(best, prev[j + 1])
                    curr[j] = best + fruits[i][j]
                prev, curr = curr, prev
            return prev[n - 1]

        ans += dp()

        for i in range(n):
            for j in range(i):
                fruits[i][j], fruits[j][i] = fruits[j][i], fruits[i][j]

        ans += dp()
        return ans

1.21 - 2025-08-06 13:17:09 +0000 UTC

Fruits Into Baskets III

Code

class Solution:
    def numOfUnplacedFruits(self, fruits: List[int], baskets: List[int]) -> int:
        length = len(baskets)
        section_length = int(math.sqrt(length))
        sections = (length + section_length - 1) // section_length
        count = 0
        sections_max = [0] * sections
        for i in range(length):
            section = i // section_length
            sections_max[section] = max(sections_max[section], baskets[i])
        for fruit in fruits:
            unset = 1
            for section in range(sections):
                if sections_max[section] < fruit:
                    continue
                choose = 0
                sections_max[section] = 0
                for i in range(section_length):
                    pos = section * section_length + i
                    if pos < length and baskets[pos] >= fruit and not choose:
                        baskets[pos] = 0
                        choose = 1
                    if pos < length:
                        sections_max[section] = max(sections_max[section], baskets[pos])
                unset = 0
                break
            count += unset
        return count

1.22 - 2025-08-05 17:11:10 +0000 UTC

Fruits Into Baskets II

Code

class Solution:
    def numOfUnplacedFruits(self, fruits: List[int], baskets: List[int]) -> int:
        count = 0
        length = len(baskets)
        for fruit in fruits:
            unset = 1
            for i in range(length):
                if fruit <= baskets[i]:
                    baskets[i] = 0
                    unset = 0
                    break
            count += unset
        return count

1.23 - 2025-08-04 16:06:02 +0000 UTC

Fruit Into Baskets

Code

class Solution:
    def totalFruit(self, fruits: list[int]) -> int:
        start = 0
        max_len = 0
        fruit_count = defaultdict(int)

        for end in range(len(fruits)):
            fruit_count[fruits[end]] += 1

            while len(fruit_count) > 2:
                fruit_count[fruits[start]] -= 1
                if fruit_count[fruits[start]] == 0:
                    del fruit_count[fruits[start]]
                start += 1

            max_len = max(max_len, end - start + 1)

        return max_len

1.24 - 2025-08-03 13:36:16 +0000 UTC

Replace All ?’s to Avoid Consecutive Repeating Characters

Code

class Solution:
    def modifyString(self, s: str) -> str:
        res = list(s)
        length = len(s)

        for i in range(length):
            char = res[i]
            if char != "?":
                continue
            for char_ascii in string.ascii_lowercase:
                if (
                    (i > 0 and res[i - 1] == char_ascii) 
                    or (i < length - 1 and res[i + 1] == char_ascii)
                ):
                    continue
                res[i] = char_ascii
                break
        return "".join(res)

1.25 - 2025-08-03 13:21:01 +0000 UTC

Matrix Diagonal Sum

Code

class Solution:
    def diagonalSum(self, mat: List[List[int]]) -> int:
        length = len(mat)
        res = 0
        for i in range(length):
            row1, col1 = i, i
            row2, col2 = i, length - i - 1
            res += mat[row1][col1]
            if row2 != row1 or col2 != col1:
                res += mat[row2][col2]
        return res

1.26 - 2025-08-03 13:03:54 +0000 UTC

Detect Pattern of Length M Repeated K or More Times

Code

class Solution:
    def containsPattern(self, arr: List[int], m: int, k: int) -> bool:
        length = len(arr)
        if length < m * k:
            return False
        for i in range(length - m + 1):
            cur_pat = arr[i:i+m]
            count = 1
            for j in range(i + m, length, m):
                if arr[j:j+m] == cur_pat:
                    count += 1
                else:
                    break
            if count >= k:
                return True
        return False

1.27 - 2025-08-03 12:13:16 +0000 UTC

Most Visited Sector in a Circular Track

Code

class Solution:
    def mostVisited(self, n: int, rounds: List[int]) -> List[int]:
        start_sector, end_sector = rounds[0], rounds[-1]

        if start_sector <= end_sector:
            return tuple(range(start_sector, end_sector + 1))
            
        return tuple(
            itertools.chain(
                range(1, end_sector + 1),
                range(start_sector, n + 1)
            )
        )

1.28 - 2025-08-03 12:01:18 +0000 UTC

Thousand Separator

Code

class Solution:
    def thousandSeparator(self, n: int) -> str:
        if n < 1000:
            return str(n)
        res = []
        count = 0
        while n > 0:
            res.append(str(n % 10))
            count += 1
            n //= 10
            if count % 3 == 0 and n > 0:
                res.append(".")
        res.reverse()
        return "".join(res)

1.29 - 2025-08-03 11:57:57 +0000 UTC

Three Consecutive Odds

Code

class Solution:
    def threeConsecutiveOdds(self, arr: List[int]) -> bool:
        count = 0
        for num in arr:
            if num % 2 == 0:
                count = 0
            else:
                count += 1
            if count == 3:
                return True
        return False

1.30 - 2025-08-03 11:56:16 +0000 UTC

Kth Missing Positive Number

Code

class Solution:
    def findKthPositive(self, arr: List[int], k: int) -> int:
        prev = 0
        for num in arr:
            diff = num - prev - 1
            if k > diff:
                k -= diff
            else:
                return prev + k
            prev = num
        return prev + k

1.31 - 2025-08-03 11:39:49 +0000 UTC

Shuffle String

Code

class Solution:
    def restoreString(self, s: str, indices: List[int]) -> str:
        res = [None] * len(s)
        for i, char in zip(indices, s):
            res[i] = char
        return "".join(res)

1.32 - 2025-08-03 11:33:50 +0000 UTC

Water Bottles

Code

class Solution:
    def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
        res = 0
        empty = 0
        while numBottles > 0:
            res += numBottles
            empty += numBottles
            numBottles = empty // numExchange
            empty %= numExchange
        return res

1.33 - 2025-08-03 11:27:36 +0000 UTC

Reformat Date

Code

class Solution:
    def reformatDate(self, date: str) -> str:
        day_str, mnth_str, year_str = date.split()
        if len(day_str) == 3:
            day = int(day_str[0:1])
        else:
            day = int(day_str[0:2])
        mnth = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"].index(mnth_str) + 1
        year = int(year_str)
        return f"{year}-{mnth:02}-{day:02}"

1.34 - 2025-08-03 11:18:22 +0000 UTC

Can Make Arithmetic Progression From Sequence

Code

class Solution:
    def canMakeArithmeticProgression(self, arr: List[int]) -> bool:
        arr.sort()
        diff = abs(arr[0] - arr[1])
        for i in range(1, len(arr) - 1):
            if abs(arr[i] - arr[i+1]) != diff:
                return False
        return True

1.35 - 2025-08-03 10:56:55 +0000 UTC

Final Prices With a Special Discount in a Shop

Code

class Solution:
    def finalPrices(self, prices: List[int]) -> List[int]:
        stack = deque()
        for i in range(len(prices)):
            price = prices[i]
            while True:
                if not stack:
                    break
                last_i, last_price = stack[-1]
                if last_price >= price:
                    prices[last_i] -= price
                    stack.pop()
                else:
                    break
            stack.append((i, price))
        return prices

1.36 - 2025-08-03 10:42:44 +0000 UTC

Shuffle the Array

Code

class Solution:
    def shuffle(self, nums: List[int], n: int) -> List[int]:
        res = []
        for j in range(n, 2 * n):
            res.extend((nums[j - n], nums[j]))
        return res

1.37 - 2025-08-03 10:35:23 +0000 UTC

Make Two Arrays Equal by Reversing Subarrays

Code

class Solution:
    def canBeEqual(self, target: List[int], arr: List[int]) -> bool:
        freqs = defaultdict(int)
        length = len(target)
        if length != len(arr):
            return False
        for i in range(length):
            freqs[target[i]] += 1
            freqs[arr[i]] -= 1
        for count in freqs.values():
            if count != 0:
                return False
        return True

1.38 - 2025-08-03 10:30:55 +0000 UTC

Check If a Word Occurs As a Prefix of Any Word in a Sentence

Code

class Solution:
    def isPrefixOfWord(self, sentence: str, searchWord: str) -> int:
        for i, word in enumerate(sentence.split()):
            if word.startswith(searchWord):
                return i + 1
        return -1

1.39 - 2025-08-03 10:25:11 +0000 UTC

Consecutive Characters

Code

class Solution:
    def maxPower(self, s: str) -> int:
        prev = s[0]
        count = 1
        max_count= 1
        for char in s[1:]:
            if char == prev:
                count += 1
                max_count = max(max_count, count)
            else:
                count = 1
                prev = char
        return max_count

1.40 - 2025-08-03 10:22:53 +0000 UTC

Check If All 1’s Are at Least Length K Places Away

Code

class Solution:
    def kLengthApart(self, nums: List[int], k: int) -> bool:
        prev = -k - 1
        for i, num in enumerate(nums):
            if num == 0:
                continue
            if i - prev - 1 >= k:
                prev = i
            else:
                return False
        return True

1.41 - 2025-08-03 10:19:10 +0000 UTC

Reformat The String

Code

class Solution:
    def reformat(self, s: str) -> str:
        res, digits, al = [""], [], []
        for char in s:
            if char.isalpha():
                al.append(char)
            else:
                digits.append(char)
            while digits and al:
                res.extend((digits.pop(), al.pop()))
        if digits:
            res.append(digits.pop())
        elif al:
            res[0] = al.pop()
        if digits or al:
            return ""
        return "".join(res)

1.42 - 2025-08-03 08:38:37 +0000 UTC

Minimum Value to Get Positive Step by Step Sum

Code

class Solution:
    def minStartValue(self, nums: List[int]) -> int:
        min_sum = float('inf')
        cur_sum = 0
        for num in nums:
            cur_sum += num
            min_sum = min(min_sum, cur_sum)
        return max(1 - min_sum, 1)

1.43 - 2025-08-03 07:42:15 +0000 UTC

String Matching in an Array

Code

class Solution:

    class TrieNode:
        def __init__(self):
            # Tracks how many times this substring appears in the Trie.
            self.frequency = 0
            # Maps characters to their respective child nodes.
            self.child_nodes = {}

    def stringMatching(self, words: List[str]) -> List[str]:
        matching_words = []
        root = self.TrieNode()  # Initialize the root of the Trie.

        # Insert all suffixes of each word into the Trie.
        for word in words:
            for start_index in range(len(word)):
                # Insert each suffix starting from index start_index.
                self._insert_word(root, word[start_index:])

        # Check each word to see if it exists as a substring in the Trie.
        for word in words:
            if self._is_substring(root, word):
                matching_words.append(word)

        return matching_words

    def _insert_word(self, root: "TrieNode", word: str) -> None:
        current_node = root
        for char in word:
            if char not in current_node.child_nodes:
                # Create a new node if the character does not exist.
                current_node.child_nodes[char] = self.TrieNode()
            current_node = current_node.child_nodes[char]
            current_node.frequency += 1  # Increment the frequency of the node.

    def _is_substring(self, root: "TrieNode", word: str) -> bool:
        current_node = root
        for char in word:
            # Traverse the Trie following the characters of the word.
            current_node = current_node.child_nodes[char]
        # A word is a substring if its frequency in the Trie is greater than 1.
        return current_node.frequency > 1

1.44 - 2025-08-03 07:26:28 +0000 UTC

Maximum Fruits Harvested After at Most K Steps

Code

class Solution:
    def maxTotalFruits(
        self, fruits: List[List[int]], startPos: int, k: int
    ) -> int:
        n = len(fruits)
        sum_ = [0] * (n + 1)
        indices = [0] * n

        for i in range(n):
            sum_[i + 1] = sum_[i] + fruits[i][1]
            indices[i] = fruits[i][0]

        ans = 0
        for x in range(k // 2 + 1):
            # move left x steps, then right (k - 2x) steps
            y = k - 2 * x
            left = startPos - x
            right = startPos + y
            start = bisect_left(indices, left)
            end = bisect_right(indices, right)
            ans = max(ans, sum_[end] - sum_[start])

            # move right x steps, then left (k - 2x) steps
            y = k - 2 * x
            left = startPos - y
            right = startPos + x
            start = bisect_left(indices, left)
            end = bisect_right(indices, right)
            ans = max(ans, sum_[end] - sum_[start])

        return ans

1.45 - 2025-08-02 17:03:30 +0000 UTC

Minimum Subsequence in Non-Increasing Order

Code

class Solution:
    def minSubsequence(self, nums: List[int]) -> List[int]:
        max_sum = sum(nums)
        nums.sort(reverse=True)
        cur_sum = 0
        res = []
        for num in nums:
            cur_sum += num
            res.append(num)
            if cur_sum > max_sum - cur_sum:
                break
        return res

1.46 - 2025-08-02 16:58:48 +0000 UTC

Count Largest Group

Code

class Solution:
    def countLargestGroup(self, n: int) -> int:
        freqs = defaultdict(int)
        def count(num: int) -> int:
            res = 0
            while num > 0:
                res += num % 10
                num //= 10
            return res
        max_freq = 0
        for i in range(1, n + 1):
            group = count(i)
            freq = freqs[group] + 1
            freqs[group] = freq
            if freq > max_freq:
                max_freq = freq
        res = 0
        for freq in freqs.values():
            if freq == max_freq:
                res += 1
        return res

1.47 - 2025-08-02 16:54:21 +0000 UTC

Find Lucky Integer in an Array

Code

class Solution:
    def findLucky(self, arr: List[int]) -> int:
        freqs = defaultdict(int)
        for num in arr:
            freqs[num] += 1
        max_num = -1
        for num, freq in freqs.items():
            if num == freq:
                max_num = max(max_num, num)
        return max_num

1.48 - 2025-08-02 16:50:44 +0000 UTC

Create Target Array in the Given Order

Code

class Solution:
    def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:
        res = []
        for i, num in zip(index, nums):
            res.insert(i, num)
        return res

1.49 - 2025-08-02 16:45:12 +0000 UTC

Lucky Numbers in a Matrix

Code

class Solution:
    def luckyNumbers(self, matrix: List[List[int]]) -> List[int]:
        rows = len(matrix)
        cols = len(matrix[0])
        min_row = float("-inf")
        max_col = float("inf")
        for row in range(rows):
            min_row = max(min_row, min(matrix[row]))
        for col in range(cols):
            cur_max_col = float("-inf")
            for row in range(rows):
                cur_max_col = max(cur_max_col, matrix[row][col])
            max_col = min(max_col, cur_max_col)
        if min_row == max_col:
            return [min_row]
        return []

1.50 - 2025-08-02 16:36:06 +0000 UTC

Lucky Numbers in a Matrix

Code

class Solution:
    def luckyNumbers(self, matrix: List[List[int]]) -> List[int]:
        rows = len(matrix)
        cols = len(matrix[0])
        min_row = [None] * rows
        max_col = [None] * cols
        for row in range(rows):
            min_row[row] = min(matrix[row])
        for col in range(cols):
            num_max = float("-inf")
            for row in range(rows):
                num = matrix[row][col]
                if num > num_max:
                    num_max = num
            max_col[col] = num_max
        res = []
        for row in range(rows):
            for col in range(cols):
                num = matrix[row][col]
                if num == min_row[row] and num == max_col[col]:
                    res.append(num)
        return res

1.51 - 2025-08-02 16:24:42 +0000 UTC

Generate a String With Characters That Have Odd Counts

Code

class Solution:
    def generateTheString(self, n: int) -> str:
        if n % 2 == 0:
            return ("a" * (n - 1)) + "b"
        return "a" * n

1.52 - 2025-08-02 16:22:20 +0000 UTC

Increasing Decreasing String

Code

class Solution:
    def sortString(self, s: str) -> str:
        freqs = defaultdict(int)
        for char in s:
            freqs[char] += 1
        keys = list(freqs.keys())
        keys.sort(key = ord)
        length = len(keys)
        res = []
        while freqs:
            for i in itertools.chain(range(length), reversed(range(length))):
                key = keys[i]
                if key not in freqs:
                    continue
                res.append(key)
                freqs[key] -= 1
                if freqs[key] == 0:
                    freqs.pop(key)
        return "".join(res)

1.53 - 2025-08-02 16:12:42 +0000 UTC

How Many Numbers Are Smaller Than the Current Number

Code

class Solution:
    def smallerNumbersThanCurrent(self, nums: List[int]) -> List[int]:
        num_to_count = {}
        for i, num in enumerate(sorted(nums)):
            if num not in num_to_count:
                num_to_count[num] = i
        for i in range(len(nums)):
            nums[i] = num_to_count[nums[i]]
        return nums

1.54 - 2025-08-02 16:08:24 +0000 UTC

Number of Days Between Two Dates

Code

class Solution:
    def daysBetweenDates(self, date1: str, date2: str) -> int:
        year1, month1, day1 = map(int, date1.split('-'))
        year2, month2, day2 = map(int, date2.split('-'))
        date1 = datetime.date(year1, month1, day1)
        date2 = datetime.date(year2, month2, day2) 
        return abs((date2 - date1).days)

1.55 - 2025-08-02 15:59:52 +0000 UTC

Check If N and Its Double Exist

Code

class Solution:
    def checkIfExist(self, arr: List[int]) -> bool:
        enc = set()
        for num in arr:
            if num == 0 and 0 in enc:
                return True
            if num % 2 == 0 and num // 2 in enc:
                return True
            if num * 2 in enc:
                return True
            enc.add(num)
        return False

1.56 - 2025-08-02 15:49:48 +0000 UTC

Remove Palindromic Subsequences

Code

class Solution:
    def removePalindromeSub(self, s: str) -> int:
        if s == s[::-1]:
            return 1
        return 2

1.57 - 2025-08-02 15:45:57 +0000 UTC

Rank Transform of an Array

Code

class Solution:
    def arrayRankTransform(self, arr: List[int]) -> List[int]:
        num_to_rank = defaultdict(int)
        nums = sorted(set(arr))
        for rank, num in enumerate(nums, 1):
            num_to_rank[num] = rank
        for i in range(len(arr)):
            arr[i] = num_to_rank[arr[i]]
        return arr

1.58 - 2025-08-02 15:40:13 +0000 UTC

Rank Transform of an Array

Code

class Solution:
    def arrayRankTransform(self, arr: List[int]) -> List[int]:
        ind = defaultdict(list)
        for i, num in enumerate(arr):
            ind[num].append(i)
        for rank, num in enumerate(sorted(ind.keys()), 1):
            for i in ind[num]:
                arr[i] = rank
        return arr

1.59 - 2025-08-02 15:22:51 +0000 UTC

Maximum 69 Number

Code

class Solution:
    def maximum69Number(self, num: int) -> int:
        digits = []
        while num > 0:
            digits.append(num % 10)
            num //= 10
        digits.reverse()
        res = 0
        enc = False
        length = len(digits)
        for i, digit in enumerate(digits):
            if digit == 6 and not enc:
                digit = 9
                enc = True
            res += (10 ** (length - i - 1)) * digit
        return res

1.60 - 2025-08-02 15:14:37 +0000 UTC

Convert Integer to the Sum of Two No-Zero Integers

Code

class Solution:
    def getNoZeroIntegers(self, n: int) -> List[int]:
        if n <= 10:
            return [1, n - 1]
        def check(num: int) -> bool:
            while num > 0:
                if num % 10 == 0:
                    return False
                num //= 10
            return True
        for i in range(1, (n + 1) // 2):
            num1, num2 = i, n - i
            if check(num1) and check(num2):
                return [num1, num2]
        raise Exception

1.61 - 2025-08-02 15:07:54 +0000 UTC

Decompress Run-Length Encoded List

Code

class Solution:
    def decompressRLElist(self, nums: List[int]) -> List[int]:
        res = []
        i = 0
        length = len(nums)
        while i < length:
            freq, val = nums[i], nums[i + 1]
            i += 2
            res.extend((val, ) * freq)
        return res

1.62 - 2025-08-02 15:04:04 +0000 UTC

Decrypt String from Alphabet to Integer Mapping

Code

class Solution:
    def freqAlphabets(self, s: str) -> str:
        res = []
        length = len(s)
        i = 0
        while i < length:
            if i + 2 <  length and s[i + 2] == "#":
                res.append(chr(int(s[i:i+2]) + 97 - 1))
                i += 3
            else:
                res.append(chr(int(s[i]) + 97 - 1))
                i += 1
        return "".join(res)

1.63 - 2025-08-02 14:59:03 +0000 UTC

Find N Unique Integers Sum up to Zero

Code

class Solution:
    def sumZero(self, n: int) -> List[int]:
        if n == 1:
            return [0]
        res = []
        if n % 2 != 0:
            res.append(0)
            n -= 1
        for i in range(1, (n // 2) + 1):
            res.extend((i, -i))
        return res

1.64 - 2025-08-02 14:54:14 +0000 UTC

Replace Elements with Greatest Element on Right Side

Code

class Solution:
    def replaceElements(self, arr: List[int]) -> List[int]:
        greatest = -1
        for i in reversed(range(len(arr))):
            current = arr[i]
            arr[i] = greatest
            if current > greatest:
                greatest = current
        return arr

1.65 - 2025-08-02 14:28:54 +0000 UTC

Find Numbers with Even Number of Digits

Code

class Solution:
    def findNumbers(self, nums: List[int]) -> int:
        def count(num: int) -> int:
            res = 0
            while num:
                res += 1
                num //= 10
            return res
        res = 0
        for num in nums:
            if count(num) % 2 == 0:
                res += 1
        return res

1.66 - 2025-08-02 14:26:28 +0000 UTC

Convert Binary Number in a Linked List to Integer

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def getDecimalValue(self, head: Optional[ListNode]) -> int:
        res = 0
        while head:
            res <<= 1
            res |= head.val
            head = head.next
        return res

1.67 - 2025-08-02 14:06:00 +0000 UTC

Find Winner on a Tic Tac Toe Game

Code

class Solution:
    def tictactoe(self, moves: List[List[int]]) -> str:
        cols = [[0] * 3 for _ in range(2)]
        rows = [[0] * 3 for _ in range(2)]
        diags = [[0] * 2 for _ in range(2)]
        players = ["A", "B"]
        for i, (row, col) in enumerate(moves):
            if i % 2 == 0:
                player = 0
            else:
                player = 1
            rows[player][row] += 1
            cols[player][col] += 1
            if row == col:
                diags[player][0] += 1
            if row == 2 - col:
                diags[player][1] += 1
        for player in range(2):
            for win in (cols, rows, diags):
                if 3 in win[player]:
                    return players[player]
        if len(moves) == 9:
            return "Draw"
        return "Pending"

1.68 - 2025-08-02 13:50:59 +0000 UTC

Shift 2D Grid

Code

class Solution:
    def shiftGrid(self, grid: List[List[int]], k: int) -> List[List[int]]:
        if not grid or not grid[0]:
            return grid
        
        row_length = len(grid)
        col_length = len(grid[0])
        num_count = row_length * col_length
        k %= num_count
        res = [[0] * col_length for _ in range(row_length)]
        
        for row in range(row_length):
            for col in range(col_length):
                flat_mat_index = (row * col_length) + col
                new_flat_mat_index = (flat_mat_index + k) % num_count
                new_row = new_flat_mat_index // col_length
                new_col = new_flat_mat_index % col_length
                res[new_row][new_col] = grid[row][col]
        return res

1.69 - 2025-08-02 13:38:17 +0000 UTC

Cells with Odd Values in a Matrix

Code

class Solution:
    def oddCells(self, m: int, n: int, indices: List[List[int]]) -> int:
        mat = [[0] * n for _ in range(m)]
        for row, col in indices:
            for cur_col in range(n):
                mat[row][cur_col] += 1
            for cur_row in range(m):
                mat[cur_row][col] += 1
        count = 0
        for row in range(m):
            for col in range(n):
                if mat[row][col] % 2 != 0:
                    count += 1
        return count

1.70 - 2025-08-02 13:29:04 +0000 UTC

Rearranging Fruits

Code

class Solution:
    def minCost(self, basket1: List[int], basket2: List[int]) -> int:
        freq = Counter()
        m = float("inf")
        for b1 in basket1:
            freq[b1] += 1
            m = min(m, b1)
        for b2 in basket2:
            freq[b2] -= 1
            m = min(m, b2)

        merge = []
        for k, c in freq.items():
            if c % 2 != 0:
                return -1
            merge.extend([k] * (abs(c) // 2))

        if not merge:
            return 0
        merge.sort()
        return sum(min(2 * m, x) for x in merge[: len(merge) // 2])

1.71 - 2025-08-02 13:11:25 +0000 UTC

Check If It Is a Straight Line

Code

class Solution:
    def checkStraightLine(self, coordinates: List[List[int]]) -> bool:
        x1, y1 = coordinates[0]
        x2, y2 = coordinates[1]
        for x3, y3 in coordinates[2:]:
            if (x3 - x1) * (y2 - y1) != (x2 - x1) * (y3 - y1):
                return False
        return True

1.72 - 2025-08-02 13:04:47 +0000 UTC

Split a String in Balanced Strings

Code

class Solution:
    def balancedStringSplit(self, s: str) -> int:
        count_l, count_r = 0, 0
        count = 0
        for char in s:
            if char == "R":
                count_r += 1
            else:
                count_l += 1
            if count_l == count_r:
                count += 1
        return count
            

1.73 - 2025-08-02 12:56:06 +0000 UTC

Minimum Cost to Move Chips to The Same Position

Code

class Solution:
    def minCostToMoveChips(self, position: List[int]) -> int:
        length = len(position)
        odd, even = 0, 0
        for pos in position:
            if pos % 2 == 0:
                even += 1
            else:
                odd += 1
        return min(odd, even)

1.74 - 2025-08-02 12:43:09 +0000 UTC

Minimum Absolute Difference

Code

class Solution:
    def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
        arr.sort()
        min_diff = float("inf")
        res = []
        for i, num in enumerate(arr[:-1]):
            nxt = arr[i + 1]
            diff = abs(nxt - num)
            if diff < min_diff:
                res.clear()
                res.append((num, nxt))
                min_diff = diff
            elif diff == min_diff:
                res.append((num, nxt))
        return res

1.75 - 2025-08-02 12:41:03 +0000 UTC

Minimum Absolute Difference

Code

class Solution:
    def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
        arr.sort()
        min_diff = float("inf")
        diffs = defaultdict(list)
        for i, num in enumerate(arr[:-1]):
            nxt = arr[i + 1]
            diff = abs(nxt - num)
            diffs[diff].append((num, nxt))
            min_diff = min(min_diff, diff)
        return diffs[min_diff]

1.76 - 2025-08-02 12:39:53 +0000 UTC

Minimum Absolute Difference

Code

class Solution:
    def minimumAbsDifference(self, arr: List[int]) -> List[List[int]]:
        arr.sort()
        min_diff = float("inf")
        res = []
        for i, num in enumerate(arr[:-1]):
            nxt = arr[i + 1]
            diff = abs(nxt - num)
            min_diff = min(min_diff, diff)
        for i, num in enumerate(arr[:-1]):
            nxt = arr[i + 1]
            diff = abs(nxt - num)
            if diff == min_diff:
                res.append((num, nxt))
        return res

1.77 - 2025-08-02 12:34:16 +0000 UTC

Maximum Number of Balloons

Code

class Solution:
    def maxNumberOfBalloons(self, text: str) -> int:
        freqs = defaultdict(int)
        for char in text:
            freqs[char] += 1
        res = min(
            freqs["b"],
            freqs["a"],
            freqs["l"] // 2,
            freqs["o"] // 2,
            freqs["n"]
        )
        return res

1.78 - 2025-08-02 12:27:49 +0000 UTC

Day of the Week

Code

class Solution:
    def dayOfTheWeek(self, day: int, month: int, year: int) -> str:
        return [
            "Monday", "Tuesday", "Wednesday", 
            "Thursday", "Friday", "Saturday", 
            "Sunday"
        ][datetime.date(year, month, day).weekday()]

1.79 - 2025-08-02 12:19:46 +0000 UTC

Distance Between Bus Stops

Code

class Solution:
    def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:
        length = len(distance)
        forward_dist, back_dist = 0, 0
        forward, back = start, start
        while True:
            if forward == destination:
                return forward_dist
            if back == destination or length + back == destination:
                return back_dist
            forward_dist += distance[forward]
            forward = (forward + 1) % length
            back_dist += distance[back - 1]
            back -= 1
        raise Exception

1.80 - 2025-08-02 11:54:02 +0000 UTC

Prime Arrangements

Code

class Solution:
    def numPrimeArrangements(self, n: int) -> int:
        prime = [True] * (n + 1)
        prime[0] = prime[1] = False
        for i in range(2, int(n ** 0.5) + 1):
            if not prime[i]:
                continue
            for j in range(i * i, n + 1, i):
                prime[j] = False
                    
        prime_count = sum(prime)
        mod = 10**9 + 7
        fact_primes = math.factorial(prime_count)
        fact_norm = math.factorial(n - prime_count)
        return (fact_primes * fact_norm) % mod

        

1.81 - 2025-08-02 11:25:28 +0000 UTC

Day of the Year

Code

class Solution:
    def dayOfYear(self, date: str) -> int:
        year, month, day = map(int, date.split('-'))
        days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
        if (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0):
            days_in_month[1] = 29
        day_number = sum(days_in_month[:month - 1]) + day
        return day_number

1.82 - 2025-08-02 11:10:21 +0000 UTC

Number of Equivalent Domino Pairs

Code

class Solution:
    def numEquivDominoPairs(self, dominoes: List[List[int]]) -> int:
        freqs = [0] * 100
        res = 0
        for num1, num2 in dominoes:
            if num1 > num2:
                val = num1 * 10 + num2
            else:
                val = num2 * 10 + num1
            res += freqs[val]
            freqs[val] += 1
        return res

1.83 - 2025-08-02 11:00:42 +0000 UTC

Print in Order

Code

class Foo:
    def __init__(self):
        self._lock1 = threading.Lock()
        self._lock2 = threading.Lock()
        self._lock1.acquire()
        self._lock2.acquire()

    def first(self, printFirst: 'Callable[[], None]') -> None:
        printFirst()
        self._lock1.release()


    def second(self, printSecond: 'Callable[[], None]') -> None:
        with self._lock1:
            printSecond()
        self._lock2.release()


    def third(self, printThird: 'Callable[[], None]') -> None:
        with self._lock2:
            printThird()

1.84 - 2025-08-02 10:55:22 +0000 UTC

Defanging an IP Address

Code

class Solution:
    def defangIPaddr(self, address: str) -> str:
        return address.replace(".", "[.]")

1.85 - 2025-08-02 10:54:26 +0000 UTC

Distribute Candies to People

Code

class Solution:
    def distributeCandies(self, candies: int, num_people: int) -> List[int]:
        res = [0] * num_people
        i = 0
        while candies > 0:
            loss = min(i + 1, candies)
            res[i % num_people] += loss
            i += 1
            candies -= loss
        return res

1.86 - 2025-08-02 10:48:16 +0000 UTC

Distribute Candies to People

Code

class Solution:
    def distributeCandies(self, candies: int, num_people: int) -> List[int]:
        res = [0] * num_people
        mult = 0
        while candies > 0:
            for i in range(num_people):
                target = min((mult * num_people) + (i + 1), candies)
                if candies > 0: 
                    res[i] += target
                    candies -= target
                else:
                    break
            mult += 1
        return res

1.87 - 2025-08-02 10:02:23 +0000 UTC

Duplicate Zeros

Code

class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """

        possible_dups = 0
        length_ = len(arr) - 1

        for left in range(length_ + 1):
            if left > length_ - possible_dups:
                break
            if arr[left] == 0:
                if left == length_ - possible_dups:
                    arr[length_] = 0
                    length_ -= 1
                    break
                possible_dups += 1

        last = length_ - possible_dups
        for i in range(last, -1, -1):
            if arr[i] == 0:
                arr[i + possible_dups] = 0
                possible_dups -= 1
                arr[i + possible_dups] = 0
            else:
                arr[i + possible_dups] = arr[i]

1.88 - 2025-08-02 09:36:15 +0000 UTC

Duplicate Zeros

Code

class Solution:
    def duplicateZeros(self, arr: List[int]) -> None:
        """
        Do not return anything, modify arr in-place instead.
        """
        queue = deque()
        for i in range(len(arr)):
            num = arr[i]
            if queue:
                arr[i] = queue.popleft()
                queue.append(num)
            if num == 0:
                queue.append(0)

1.89 - 2025-08-02 08:12:11 +0000 UTC

Occurrences After Bigram

Code

class Solution:
    def findOcurrences(self, text: str, first: str, second: str) -> List[str]:
        words = text.split()
        length = len(words)
        if length < 3:
            return []
        res = []
        i = 0
        while i + 2 < length:
            if words[i] == first and words[i+1] == second:
                res.append(words[i+2])
            i += 1
        return res

1.90 - 2025-08-02 07:38:33 +0000 UTC

Remove All Adjacent Duplicates In String

Code

class Solution:
    def removeDuplicates(self, s: str) -> str:
        stack = []
        for char in s:
            if stack and char == stack[-1]:
                stack.pop()
            else:
                stack.append(char)
        return "".join(stack)

1.91 - 2025-08-02 07:31:09 +0000 UTC

Last Stone Weight

Code

class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:
        for i, num in enumerate(stones):
            stones[i] = -num
        heapq.heapify(stones)
        while stones:
            last = -heapq.heappop(stones)
            if not stones:
                return last
            prev = -heapq.heappop(stones)
            if last > prev:
                heapq.heappush(stones, -(last - prev))
        return 0

1.92 - 2025-08-02 07:28:21 +0000 UTC

Last Stone Weight

Code

class Solution:
    def lastStoneWeight(self, stones: List[int]) -> int:
        stones.sort()
        while stones:
            last = stones.pop()
            if not stones:
                return last
            prev = stones[-1]
            if last == prev:
                stones.pop()
            else:
                stones[-1] = last - prev
                stones.sort()
        return 0

1.93 - 2025-08-02 06:19:39 +0000 UTC

Valid Boomerang

Code

class Solution:
    def isBoomerang(self, points: List[List[int]]) -> bool:
        x1, y1 = points[0]
        x2, y2 = points[1]
        x3, y3 = points[2]
        return (y2 - y1) * (x3 - x2) != (y3 - y2) * (x2 - x1)

1.94 - 2025-08-02 06:15:14 +0000 UTC

Matrix Cells in Distance Order

Code

class Solution:
    def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:
        res = []
        for row in range(rows):
            for col in range(cols):
                res.append((row, col))
        def key(point: tuple[int, int]) -> int:
            row, col = point
            return abs(row - rCenter) + abs(col - cCenter)
        res.sort(key=key) 
        return res

1.95 - 2025-08-02 06:11:31 +0000 UTC

Matrix Cells in Distance Order

Code

class Solution:
    def allCellsDistOrder(self, rows: int, cols: int, rCenter: int, cCenter: int) -> List[List[int]]:
        res = []
        for row in range(rows):
            for col in range(cols):
                dist = abs(row - rCenter) + abs(col - cCenter)
                res.append((dist, row, col))
        res.sort()
        for i in range(len(res)):
            res[i] = res[i][1:] 
        return res

1.96 - 2025-08-02 06:03:11 +0000 UTC

Divisor Game

Code

class Solution:
    def divisorGame(self, n: int) -> bool:
        return n % 2 == 0

1.97 - 2025-08-02 05:55:10 +0000 UTC

Sum of Root To Leaf Binary Numbers

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
        res = 0
        queue = [(root, 0)]
        while queue:
            node, parent = queue.pop()
            if node is None:
                continue
            val = (parent << 1) | node.val
            if not node.left and not node.right:
                res += val
            queue.extend(((node.left, val), (node.right, val)))
        return res

1.98 - 2025-08-02 05:53:28 +0000 UTC

Sum of Root To Leaf Binary Numbers

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sumRootToLeaf(self, root: Optional[TreeNode]) -> int:
        def dfs(node: Optional[TreeNode], parent: int) -> int:
            if node is None:
                return 0
            cur_val = (parent << 1) | node.val
            if not node.left and not node.right:
                return cur_val
            return dfs(node.left, cur_val) + dfs(node.right, cur_val)
        return dfs(root, 0)

1.99 - 2025-08-02 05:48:51 +0000 UTC

Remove Outermost Parentheses

Code

class Solution:
    def removeOuterParentheses(self, s: str) -> str:
        res = []
        balance = 0
        start = 0

        for i, char in enumerate(s):
            if char == '(':
                balance += 1
            else:
                balance -= 1
            if balance == 0:
                res.append(s[start + 1:i])
                start = i + 1
        return "".join(res)

1.100 - 2025-08-02 05:38:26 +0000 UTC

Binary Prefix Divisible By 5

Code

class Solution:
    def prefixesDivBy5(self, nums: List[int]) -> List[bool]:
        cur = 0
        for i in range(len(nums)):
            cur <<= 1
            cur |= nums[i]
            nums[i] = cur % 5 == 0
        return nums

1.101 - 2025-08-02 05:34:40 +0000 UTC

Partition Array Into Three Parts With Equal Sum

Code

class Solution:
    def canThreePartsEqualSum(self, arr: List[int]) -> bool:
        total = sum(arr)
        if total % 3 != 0:
            return False
        length = len(arr)
        target = total // 3
        cur = 0
        count = 0
        for i, num in enumerate(arr):
            cur += num
            if cur == target:
                cur = 0
                count += 1
            if count == 2 and i + 1 < length:
                return True
        return False

1.102 - 2025-08-01 18:34:49 +0000 UTC

Complement of Base 10 Integer

Code

class Solution:
    def bitwiseComplement(self, n: int) -> int:
        if n == 0:
            return 1
        res, count = 0, 0
        while n > 0:
            if n & 1 == 0:
                res += 2 ** count
            count += 1
            n >>= 1
        return res

1.103 - 2025-08-01 18:23:46 +0000 UTC

Maximize Sum Of Array After K Negations

Code

class Solution:
    def largestSumAfterKNegations(self, nums: List[int], k: int) -> int:
        nums.sort()
        for i in range(len(nums)):
            num = nums[i]
            if num < 0 and k > 0:
                nums[i] = -num
                k -= 1
            else:
                break
        if k == 0 or k % 2 == 0:
            return sum(nums)
        nums.sort()
        nums[0] = -nums[0]
        return sum(nums)

1.104 - 2025-08-01 17:49:53 +0000 UTC

Available Captures for Rook

Code

class Solution:
    def numRookCaptures(self, board: List[List[str]]) -> int:
        bishop_row, bishop_col = -1, -1
        length = len(board)
        delta = (
            (0, 1), (0, -1), (1, 0), (-1, 0)            
        )
        for row in range(length):
            for col in range(length):
                if board[row][col] == "R":
                    bishop_row, bishop_col = row, col
                    break
            if bishop_row != -1:
                break
        count = 0
        for delta_row, delta_col in delta:
            row, col = bishop_row, bishop_col
            while 0 <= row < length and 0 <= col < length:
                char = board[row][col]
                if char == "p":
                    count += 1
                    break
                elif char == "B":
                    break
                row, col = row + delta_row, col + delta_col
        return count

1.105 - 2025-08-01 17:14:01 +0000 UTC

Cousins in Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isCousins(self, root: Optional[TreeNode], x: int, y: int) -> bool:
        def dfs(node: Optional[TreeNode], depth: int) -> tuple[int, int]:
            if node is None:
                return 0, 0
            if node.val == x:
                return depth, 0
            if node.val == y:
                return 0, depth
            depth1_x, depth1_y = dfs(node.left, depth + 1)
            depth2_x, depth2_y = dfs(node.right, depth + 1)
            depth1, depth2 = depth1_x or depth2_x, depth1_y or depth2_y
            if depth1 and depth2 and depth1 == depth + 1:
                return 0, 0
            return depth1, depth2

        depth1, depth2 = dfs(root, 0)
        return depth1 == depth2 and depth1 > 1

1.106 - 2025-08-01 16:32:18 +0000 UTC

Univalued Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
        queue = [root]
        while queue:
            node = queue.pop()
            if node.right and node.val != node.right.val:
                return False
            if node.left and node.val != node.left.val:
                return False
            if node.left:
                queue.append(node.left)
            if node.right:
                queue.append(node.right)
        return True

1.107 - 2025-08-01 16:30:30 +0000 UTC

Univalued Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isUnivalTree(self, root: Optional[TreeNode]) -> bool:
        def dfs(node: Optional[TreeNode]) -> bool:
            if node is None:
                return True
            if node.left and node.val != node.left.val:
                return False
            if node.right and node.val != node.right.val:
                return False
            return dfs(node.left) and dfs(node.right)
        return dfs(root)

1.108 - 2025-08-01 16:27:17 +0000 UTC

N-Repeated Element in Size 2N Array

Code

class Solution:
    def repeatedNTimes(self, nums: List[int]) -> int:
        length = len(nums)
        for k in range(1, 4):
            for i in range(length - k):
                if nums[i] == nums[i+k]:
                    return nums[i]
        raise Exception

1.109 - 2025-08-01 16:18:48 +0000 UTC

N-Repeated Element in Size 2N Array

Code

class Solution:
    def repeatedNTimes(self, nums: List[int]) -> int:
        enc = set()
        for num in nums:
            if num in enc:
                return num
            enc.add(num)
        raise Exception

1.110 - 2025-08-01 16:16:55 +0000 UTC

Verifying an Alien Dictionary

Code

class Solution:
    def isAlienSorted(self, words: List[str], order: str) -> bool:
        pos = {}
        for i, char in enumerate(order):
            pos[char] = i
        for i in range(len(words) - 1):
            cur, nxt = words[i], words[i + 1]
            cur_length, nxt_length = len(cur), len(nxt)
            for j in range(cur_length):
                if j >= nxt_length:
                    return False
                cur_char, nxt_char = cur[j], nxt[j]
                if cur_char == nxt_char:
                    continue
                if pos[cur_char] > pos[nxt_char]: 
                    return False
                break
        return True

1.111 - 2025-08-01 14:46:26 +0000 UTC

Delete Columns to Make Sorted

Code

class Solution:
    def minDeletionSize(self, strs: List[str]) -> int:
        res = 0
        for col in range(len(strs[0])):
            prev = 0
            for row in range(len(strs)):
                char = ord(strs[row][col])
                if char >= prev:
                    prev = char
                else:
                    res += 1
                    break
        return res

1.112 - 2025-08-01 14:40:59 +0000 UTC

DI String Match

Code

class Solution:
    def diStringMatch(self, s: str) -> List[int]:
        length = len(s)
        res = [None] * (length + 1)
        num_i, num_d = 0, length
        for i, char in enumerate(s):
            if char == "I":
                res[i] = num_i
                num_i += 1
            else:
                res[i] = num_d
                num_d -= 1
        res[-1] = num_i
        return res

1.113 - 2025-08-01 14:39:13 +0000 UTC

DI String Match

Code

class Solution:
    def diStringMatch(self, s: str) -> List[int]:
        length = len(s)
        res = [None] * (length + 1)
        num_i, num_d = 0, length
        for i, char in enumerate(s):
            is_i = char == "I"
            if is_i:
                res[i] = num_i
                num_i += 1
            else:
                res[i] = num_d
                num_d -= 1
            if i != length - 1:
                continue
            if is_i:
                res[i+1] = num_d
            else:
                res[i+1] = num_i
        return res

1.114 - 2025-08-01 14:12:58 +0000 UTC

Valid Mountain Array

Code

class Solution:
    def validMountainArray(self, arr: List[int]) -> bool:
        length = len(arr)
        if length < 3:
            return False
        enc_peak = False
        prev = arr[0]
        for i, num in enumerate(arr[1:], 1):
            if num == prev:
                return False
            if not enc_peak and num < prev:
                enc_peak = True
            if enc_peak and (num > prev or i == 1):
                return False   
            prev = num
        return enc_peak

1.115 - 2025-08-01 13:57:25 +0000 UTC

Unique Email Addresses

Code

class Solution:
    def numUniqueEmails(self, emails: List[str]) -> int:
        enc = set()
        for email in emails:
            name, domain = email.rsplit("@", 1)
            name = name.split("+", 1)[0].replace(".", "")
            enc.add("@".join((name, domain)))
        return len(enc)

1.116 - 2025-08-01 13:53:59 +0000 UTC

Long Pressed Name

Code

class Solution:
    def isLongPressedName(self, name: str, typed: str) -> bool:
        name_i, typed_i = 0, 0
        name_length, typed_length = len(name), len(typed)

        while name_i < name_length and typed_i < typed_length:
            if name[name_i] == typed[typed_i]:
                name_i += 1
                typed_i += 1
            elif typed_i >= 1 and typed[typed_i] == typed[typed_i - 1]:
                typed_i += 1
            else:
                return False

        if name_i != name_length:
            return False

        while typed_i < typed_length:
            if typed[typed_i] != typed[typed_i - 1]:
                return False
            typed_i += 1

        return True

1.117 - 2025-08-01 13:43:05 +0000 UTC

Sort Array By Parity II

Code

class Solution:
    def sortArrayByParityII(self, nums: List[int]) -> List[int]:
        res = [None] * len(nums)
        i1, i2 = 0, 1
        for num in nums:
            if num % 2 == 0:
                res[i1] = num
                i1 += 2
            else:
                res[i2] = num
                i2 += 2
        return res

1.118 - 2025-08-01 13:39:51 +0000 UTC

Sort Array By Parity II

Code

class Solution:
    def sortArrayByParityII(self, nums: List[int]) -> List[int]:
        stack_even, stack_odd = [], []
        for num in nums:
            if num % 2 == 0:
                stack_even.append(num)
            else:
                stack_odd.append(num)
        for i in range(len(nums)):
            if i % 2 == 0:
                nums[i] = stack_even.pop()
            else:
                nums[i] = stack_odd.pop()
        return nums

1.119 - 2025-08-01 13:33:40 +0000 UTC

Reverse Only Letters

Code

class Solution:
    def reverseOnlyLetters(self, s: str) -> str:
        i, j = 0, len(s) - 1
        res = [None] * len(s)
        while i <= j:
            char1, char2 = s[i], s[j]
            if not char1.isalpha():
                res[i] = char1
                i += 1
            elif not char2.isalpha():
                res[j] = char2
                j -= 1
            else:
                res[i], res[j] = char2, char1
                i += 1
                j -= 1
        return "".join(res)

1.120 - 2025-08-01 13:24:11 +0000 UTC

X of a Kind in a Deck of Cards

Code

import math
import functools

class Solution:
    def hasGroupsSizeX(self, deck: List[int]) -> bool:
        freqs = collections.defaultdict(int)
        for num in deck:
            freqs[num] += 1
        gcd = functools.reduce(math.gcd, freqs.values())
        return gcd > 1

1.121 - 2025-08-01 13:02:30 +0000 UTC

Smallest Range I

Code

class Solution:
    def smallestRangeI(self, nums: List[int], k: int) -> int:
        min_num, max_num = min(nums), max(nums)
        diff = max_num - min_num
        res = max(diff - 2 * k, 0)
        return res

1.122 - 2025-08-01 13:01:56 +0000 UTC

Smallest Range I

Code

class Solution:
    def smallestRangeI(self, nums: List[int], k: int) -> int:
        min_num, max_num = float("inf"), float("-inf")
        for num in nums:
            if num > max_num:
                max_num = num
            if num < min_num:
                min_num = num
        diff = max_num - min_num
        res = max(diff - 2 * k, 0)
        return res

1.123 - 2025-08-01 12:50:58 +0000 UTC

Increasing Order Search Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def increasingBST(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root is None:
            return None
        def dfs(node: TreeNode) -> tuple[TreeNode, TreeNode]:
            if node.left:
                root, tail = dfs(node.left)
                tail.right = node
                tail = node
                node.left = None
            else:
                root, tail = node, node
            if node.right:
                right_root, right_tail = dfs(node.right)
                tail.right = right_root
                tail = right_tail
            return root, tail

        root, tail = dfs(root)
        return root

1.124 - 2025-08-01 12:30:00 +0000 UTC

Surface Area of 3D Shapes

Code

class Solution:
    def surfaceArea(self, grid: list[list[int]]) -> int:
        length = len(grid)
        res = 0
        adj_delta = (
            (-1, 0), (1, 0), (0, -1), (0, 1)
        )
        for row in range(length):
            for col in range(length):
                height = grid[row][col]
                if height == 0:
                    continue
                res += 2
                for row_delta, col_delta in adj_delta:
                    adj_row, adj_col = row + row_delta, col + col_delta
                    if 0 <= adj_row < length and 0 <= adj_col < length:
                        adj_height = grid[adj_row][adj_col]
                    else:
                        adj_height = 0
                    if height > adj_height:
                        res += grid[row][col] - adj_height
        return res

1.125 - 2025-08-01 11:50:20 +0000 UTC

Fair Candy Swap

Code

class Solution:
    def fairCandySwap(self, aliceSizes: List[int], bobSizes: List[int]) -> List[int]:
        count1, count2 = sum(aliceSizes), sum(bobSizes)
        delta = (count2 - count1) // 2
        set2 = set(bobSizes)
        for ex1 in aliceSizes:
            ex2 = ex1 + delta
            if ex2 in set2:
                return ex1, ex2
        raise Exception

1.126 - 2025-08-01 10:28:24 +0000 UTC

Uncommon Words from Two Sentences

Code

class Solution:
    def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
        freqs = collections.defaultdict(int)
        res = []
        for word in s1.split():
            freqs[word] += 1
        for word in s2.split():
            freqs[word] += 1
        for word, freq in freqs.items():
            if freq == 1:
                res.append(word)
        return res

1.127 - 2025-08-01 10:24:00 +0000 UTC

Uncommon Words from Two Sentences

Code

class Solution:
    def uncommonFromSentences(self, s1: str, s2: str) -> List[str]:
        freqs1, freqs2 = defaultdict(int), defaultdict(int)
        words1, words2 = s1.split(" "), s2.split(" ")
        for word in words1:
            freqs1[word] += 1
        for word in words2:
            freqs2[word] += 1
        res = []
        for word, freq in freqs1.items():
            if freq != 1 or word in freqs2:
                continue
            res.append(word)
        for word, freq in freqs2.items():
            if freq != 1 or word in freqs1:
                continue
            res.append(word)
        return res

1.128 - 2025-08-01 10:12:38 +0000 UTC

Projection Area of 3D Shapes

Code

class Solution:
    def projectionArea(self, grid: list[list[int]]) -> int:
        res = 0
        length = len(grid)

        for i in range(length):
            best_row = 0
            best_col = 0 
            for j in range(length):
                if grid[i][j]: 
                    res += 1 
                best_row = max(best_row, grid[i][j])
                best_col = max(best_col, grid[j][i])

            res += best_row + best_col

        return res

1.129 - 2025-08-01 06:59:43 +0000 UTC

Lemonade Change

Code

class Solution:
    def lemonadeChange(self, bills: List[int]) -> bool:
        change_5, change_10 = 0, 0
        for bill in bills:
            if bill == 5:
                change_5 += 1
            elif bill == 10 and change_5 > 0:
                change_5 -= 1
                change_10 += 1
            elif bill == 10 and change_5 <= 0:
                return False
            elif bill == 20 and change_10 > 0 and change_5 > 0:
                change_10 -= 1
                change_5 -= 1
            elif bill == 20 and change_5 >= 3:
                change_5 -= 3
            else:
                return False
        return True

1.130 - 2025-08-01 06:40:56 +0000 UTC

Rectangle Overlap

Code

class Solution:
    def isRectangleOverlap(self, rec1: List[int], rec2: List[int]) -> bool:
        def intersect(p_left: int, p_right: int, q_left: int, q_right: int) -> bool:
            return min(p_right, q_right) > max(p_left, q_left)
        return (
            intersect(rec1[0], rec1[2], rec2[0], rec2[2]) # width > 0 
            and intersect(rec1[1], rec1[3], rec2[1], rec2[3]) # height > 0
        )

1.131 - 2025-08-01 05:25:54 +0000 UTC

Flipping an Image

Code

class Solution:
    def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
        for row in image:
            row.reverse()
            for i in range(len(row)):
                row[i] ^= 1
        return image

1.132 - 2025-08-01 05:21:20 +0000 UTC

Flipping an Image

Code

class Solution:
    def flipAndInvertImage(self, image: List[List[int]]) -> List[List[int]]:
        for row in image:
            row.reverse()
            for i in range(len(row)):
                if row[i] == 0:
                    row[i] = 1
                else:
                    row[i] = 0
        return image

1.133 - 2025-08-01 05:13:47 +0000 UTC

Positions of Large Groups

Code

class Solution:
    def largeGroupPositions(self, s: str) -> List[List[int]]:
        res = []
        start = 0
        prev = s[0]
        for i, char in enumerate(itertools.chain(s[1:], " "), 1):
            if char == prev:
                continue
            if i - 1 - start >= 2:
                res.append((start, i - 1))
            start = i
            prev = char
        return res

1.134 - 2025-08-01 04:59:37 +0000 UTC

Goat Latin

Code

class Solution:
    def toGoatLatin(self, sentence: str) -> str:
        cur_word = []
        res = []
        i = 0
        for char in itertools.chain(sentence, " "):
            if char != " ":
                cur_word.append(char)
                continue
            if not cur_word:
                continue
            i += 1
            if cur_word[0].lower() in ("a", "e", "i", "o", "u"):
                cur_word.append("ma")
            else:
                cur_word.append(cur_word[0])
                cur_word.append("ma")
                cur_word[0] = ""
            cur_word.append("a" * i)
            res.append("".join(cur_word))
            cur_word.clear()
        return " ".join(res)

1.135 - 2025-08-01 04:51:03 +0000 UTC

Shortest Distance to a Character

Code

class Solution:
    def shortestToChar(self, s: str, c: str) -> List[int]:
        indexes = []
        for i, char in enumerate(s):
            if char == c:
                indexes.append(i)
        length = len(indexes)
        res = []
        i = 0
        max_diff = float("inf")
        for j, char in enumerate(s):
            diff1 = abs(indexes[i] - j)
            if i + 1 >= length:
                diff2 = max_diff
            else:
                diff2 = abs(indexes[i + 1] - j)
            if diff1 <= diff2:
                res.append(diff1)
            else:
                res.append(diff2)
                i += 1
        return res

            

1.136 - 2025-08-01 04:33:33 +0000 UTC

Most Common Word

Code

class Solution:
    def mostCommonWord(self, paragraph: str, banned: List[str]) -> str:
        freqs = defaultdict(int)
        banned_set = set(banned)
        cur_word = []
        for char in itertools.chain(paragraph, "."):
            if char.isalpha():
                cur_word.append(char.lower())
                continue
            if not cur_word:
                continue
            word = "".join(cur_word)
            if word not in banned_set:
                freqs[word] += 1
            cur_word.clear()
        most_freq = ""
        most_freq_freq = 0
        for word, freq in freqs.items():
            if freq > most_freq_freq:
                most_freq, most_freq_freq = word, freq
        return most_freq

1.137 - 2025-08-01 04:15:40 +0000 UTC

Pascal’s Triangle

Code

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        res = [(1, )]
        cur_row = []
        for row in range(1, numRows):
            cur_row.append(1)
            prev_row = res[-1]
            for i in range(1, row):
                cur_row.append(prev_row[i] + prev_row[i - 1])
            cur_row.append(1)
            res.append(tuple(cur_row))
            cur_row.clear()
        return res
                

1.138 - 2025-07-31 18:28:35 +0000 UTC

Largest Triangle Area

Code

class Solution:
    def largestTriangleArea(self, points: list[int]) -> float:
        def area(p: tuple[int, int], q: tuple[int, int], r: tuple[int, int]) -> float:
            return 0.5 * abs(
                (p[0] * q[1]) 
                + (q[0] * r[1]) 
                + (r[0] * p[1])
                - (p[1] * q[0]) 
                - (q[1] * r[0]) 
                - (r[1] * p[0])
            )

        res = max(
            area(p, q, r)
            for p, q, r in itertools.combinations(points, 3)
        )
        return res

1.139 - 2025-07-31 15:46:45 +0000 UTC

Number of Lines To Write String

Code

class Solution:
    def numberOfLines(self, widths: List[int], s: str) -> List[int]:
        line_count = 1
        line_width = 0
        for char in s:
            char_width = widths[ord(char) - 97]
            line_width += char_width
            if line_width > 100:
                line_width = char_width
                line_count += 1
        return line_count, line_width

1.140 - 2025-07-31 15:31:00 +0000 UTC

Unique Morse Code Words

Code

MORSE = (".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--..")

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        enc = set()
        for word in words:
            enc.add("".join(MORSE[ord(char) - 97] for char in word))
        return len(enc)

1.141 - 2025-07-31 15:29:59 +0000 UTC

Unique Morse Code Words

Code

class Solution:
    def uniqueMorseRepresentations(self, words: List[str]) -> int:
        morse = [".-","-...","-.-.","-..",".","..-.","--.","....","..",".---","-.-",".-..","--","-.","---",".--.","--.-",".-.","...","-","..-","...-",".--","-..-","-.--","--.."]
        enc = set()
        cur_morse = []
        for word in words:
            cur_morse.clear()
            for char in word:
                cur_morse.append(morse[ord(char) - 97])
            enc.add("".join(cur_morse))
        return len(enc)

1.142 - 2025-07-31 15:14:30 +0000 UTC

Rotate String

Code

class Solution:
    def rotateString(self, s: str, goal: str) -> bool:
        if len(s) != len(goal):
            return False
        return goal in "".join((s, s))

1.143 - 2025-07-31 14:53:16 +0000 UTC

Minimum Distance Between BST Nodes

Code

class Solution:
    def minDiffInBST(self, root: TreeNode) -> int:
        self.ans = float('inf')
        self.pred = None
        self.inorder(root)
        return self.ans

    def inorder(self, root: TreeNode) -> None:
        if root is None:
            return
        
        self.inorder(root.left)
        if self.pred is not None:
            self.ans = min(self.ans, root.val - self.pred)
        self.pred = root.val
        self.inorder(root.right)

1.144 - 2025-07-31 14:18:00 +0000 UTC

Jewels and Stones

Code

class Solution:
    def numJewelsInStones(self, jewels: str, stones: str) -> int:
        jewels_set = set(jewels)
        count = 0
        for char in stones:
            if char in jewels:
                count += 1
        return count

1.145 - 2025-07-31 14:16:38 +0000 UTC

Toeplitz Matrix

Code

class Solution:
    def isToeplitzMatrix(self, matrix: List[List[int]]) -> bool:
        for i in range(1, len(matrix)):
            for j in range(1, len(matrix[0])):
                if matrix[i-1][j-1] != matrix[i][j]:
                    return False
        return True

1.146 - 2025-07-31 14:05:37 +0000 UTC

Shortest Completing Word

Code

class Solution:
    def shortestCompletingWord(self, licensePlate: str, words: List[str]) -> str:
        freq = defaultdict(int)
        for char in licensePlate:
            if char == " " or char.isnumeric():
                continue
            freq[char.lower()] += 1
        cur_freq = {}
        shortest = None
        for word in words:
            cur_freq.clear()
            cur_freq.update(freq)
            for char in word:
                if not cur_freq:
                    break
                if char not in cur_freq:
                    continue
                new_freq = cur_freq[char] - 1
                if new_freq <= 0:
                    cur_freq.pop(char)
                else:
                    cur_freq[char] = new_freq
            if not cur_freq and (shortest is None or len(word) < len(shortest)):
                shortest = word
        return shortest

1.147 - 2025-07-31 11:35:36 +0000 UTC

Largest Number At Least Twice of Others

Code

class Solution:
    def dominantIndex(self, nums: List[int]) -> int:
        largest1, largest2 = -1, -1
        largest_i = -1
        for i, num in enumerate(nums):
            if num == largest2 or num == largest1:
                continue
            if num > largest2:
                largest1 = largest2
                largest2 = num
                largest_i = i
            elif num > largest1:
                largest1 = num
        if largest1 * 2 <= largest2:
            return largest_i
        return -1

1.148 - 2025-07-31 10:54:58 +0000 UTC

Flood Fill

Code

class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
        target_color = image[sr][sc]
        if target_color == color:
            return image
        length_row = len(image)
        length_col = len(image[0])
        dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
        queue = [(sr, sc)]
        while queue:
            row, col = queue.pop()
            if row < 0 or row >= length_row:
                continue
            if col < 0 or col >= length_col:
                continue
            if image[row][col] != target_color:
                continue
            image[row][col] = color
            for row_delta, col_delta in dirs:
                queue.append((row + row_delta, col + col_delta))
        return image

1.149 - 2025-07-31 10:46:42 +0000 UTC

Flood Fill

Code

class Solution:
    def floodFill(self, image: List[List[int]], sr: int, sc: int, color: int) -> List[List[int]]:
        target_color = image[sr][sc]
        enc = set()
        length_row = len(image)
        length_col = len(image[0])
        dirs = ((1, 0), (-1, 0), (0, 1), (0, -1))
        queue = [(sr, sc)]
        while queue:
            row, col = queue.pop()
            if row < 0 or row >= length_row:
                continue
            if col < 0 or col >= length_col:
                continue
            if (row, col) in enc:
                continue
            if image[row][col] != target_color:
                continue
            image[row][col] = color
            enc.add((row, col))
            for row_delta, col_delta in dirs:
                queue.append((row + row_delta, col + col_delta))
        return image

1.150 - 2025-07-31 10:03:46 +0000 UTC

Self Dividing Numbers

Code

class Solution:
    def selfDividingNumbers(self, left: int, right: int) -> List[int]:
        def self_dividing(num: int) -> bool:
            if num == 0:
                return False
            cur_num = num
            while cur_num > 0:
                mod = cur_num % 10
                cur_num //= 10
                if mod == 0 or num % mod > 0:
                    return False
            return True
        ans = []
        for n in range(left, right + 1):
            if self_dividing(n):
                ans.append(n)
        return ans

1.151 - 2025-07-31 08:07:49 +0000 UTC

Degree of an Array

Code

class Solution:
    def findShortestSubArray(self, nums: List[int]) -> int:
        left, right, freq = defaultdict(int), defaultdict(int), defaultdict(int)
        max_freq = 0
        for i, num in enumerate(nums):
            if num not in left:
                left[num] = i
            right[num] = i
            freq[num] += 1
            max_freq = max(max_freq, freq[num])
        min_length = len(nums)
        for num, num_freq in freq.items():
            if num_freq != max_freq:
                continue
            min_length = min(min_length, right[num] - left[num] + 1)
        return min_length

1.152 - 2025-07-31 08:00:20 +0000 UTC

Count Binary Substrings

Code

class Solution:
    def countBinarySubstrings(self, s: str) -> int:
        groups = [1]
        for i in range(1, len(s)):
            if s[i-1] != s[i]:
                groups.append(1)
            else:
                groups[-1] += 1

        ans = 0
        for i in range(1, len(groups)):
            ans += min(groups[i-1], groups[i])
        return ans

1.153 - 2025-07-31 07:28:31 +0000 UTC

Baseball Game

Code

class Solution:
    def calPoints(self, operations: List[str]) -> int:
        stack = []
        stack_sum = 0
        for op in operations:
            if op.isnumeric() or op.startswith("-"):
                new_score = int(op)
                stack.append(new_score)
                stack_sum += new_score
            elif op == "+":
                new_score = stack[-1] + stack[-2]
                stack_sum += new_score
                stack.append(new_score)
            elif op == "D":
                new_score = stack[-1] * 2
                stack_sum += new_score
                stack.append(new_score)
            elif op == "C":
                stack_sum -= stack[-1]
                stack.pop()
            else:
                raise Exception(op)
        return stack_sum

1.154 - 2025-07-31 07:04:49 +0000 UTC

Bitwise ORs of Subarrays

Code

class Solution:
    def subarrayBitwiseORs(self, arr: List[int]) -> int:
        ors = set()
        cur = {0}
        for num in arr:
            cur = {num | cur_num for cur_num in cur} | {num}
            ors |= cur
        return len(ors)

1.155 - 2025-07-30 19:05:38 +0000 UTC

Valid Palindrome II

Code

class Solution:
    def validPalindrome(self, s: str) -> bool:
        def check(i: int, j: int) -> bool:
            while i < j:
                if s[i] != s[j]:
                    return False
                i, j = i + 1, j - 1
            return True

        i, j = 0, len(s) - 1
        while i < j:
            if s[i] != s[j]:
                return check(i + 1, j) or check(i, j - 1)
            i, j = i + 1, j - 1
        return True

1.156 - 2025-07-30 19:00:12 +0000 UTC

Longest Continuous Increasing Subsequence

Code

class Solution:
    def findLengthOfLCIS(self, nums: List[int]) -> int:
        prev = nums[0]
        length = 1
        max_length = 1
        for num in nums[1:]:
            if num > prev:
                length += 1
            else:
                max_length = max(length, max_length)
                length = 1
            prev = num
        return max(length, max_length)

1.157 - 2025-07-30 18:55:12 +0000 UTC

Second Minimum Node In a Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findSecondMinimumValue(self, root):
        self.ans = float('inf')
        min1 = root.val

        def dfs(node):
            if node:
                if min1 < node.val < self.ans:
                    self.ans = node.val
                elif node.val == min1:
                    dfs(node.left)
                    dfs(node.right)

        dfs(root)
        return self.ans if self.ans < float('inf') else -1

1.158 - 2025-07-30 18:02:37 +0000 UTC

Robot Return to Origin

Code

class Solution:
    def judgeCircle(self, moves: str) -> bool:
        row, col = 0, 0
        coords = {
            "R": (0, 1),
            "L": (0, -1),
            "U": (1, 0),
            "D": (-1, 0)           
        }
        for move in moves:
            row_delta, col_delta = coords[move]
            row += row_delta
            col += col_delta
        return row == 0 and col == 0

1.159 - 2025-07-30 17:59:49 +0000 UTC

Maximum Product of Three Numbers

Code

class Solution:
    def maximumProduct(self, nums: List[int]) -> int:
        nums.sort()
        pos_res = nums[-1] * nums[-2] * nums[-3]
        if nums[0] >= 0:
            return pos_res
        neg_res = nums[0] * nums[1] * nums[-1]
        return max(pos_res, neg_res)

1.160 - 2025-07-30 17:35:12 +0000 UTC

Merge Two Binary Trees

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
        if root1 is None:
            return root2
        if root2 is None:
            return root1
        queue = [(root1, root2)]
        while queue:
            node1, node2 = queue.pop()
            if node1 is None or node2 is None:
                continue
            node1.val += node2.val
            if node1.left is None:
                node1.left = node2.left
            else:
                queue.append((node1.left, node2.left))
            if node1.right is None:
                node1.right = node2.right
            else:
                queue.append((node1.right, node2.right))
        return root1

1.161 - 2025-07-30 17:27:09 +0000 UTC

Merge Two Binary Trees

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def mergeTrees(self, root1: Optional[TreeNode], root2: Optional[TreeNode]) -> Optional[TreeNode]:
        def dfs(node1: Optional[TreeNode], node2: Optional[TreeNode]) -> None:
            if node1 is None:
                return node2
            if node2 is None:
                return node1
            node1.val += node2.val
            node1.left = dfs(node1.left, node2.left)
            node1.right = dfs(node1.right, node2.right)
            return node1
        
        return dfs(root1, root2)

1.162 - 2025-07-30 16:52:43 +0000 UTC

Minimum Index Sum of Two Lists

Code

class Solution:
    def findRestaurant(self, list1: List[str], list2: List[str]) -> List[str]:
        indexes = {}
        res = []
        if len(list1) > len(list2):
            first, second = list2, list1
        else:
            first, second = list1, list2
        for i, string in enumerate(first):
            indexes[string] = i
        min_sum = float("inf")
        res = []
        for j, string in enumerate(second):
            if string not in indexes:
                continue
            cur_sum = indexes[string] + j
            if cur_sum < min_sum:
                res.clear()
                res.append(string)
                min_sum = cur_sum
            elif cur_sum == min_sum:
                res.append(string)
        return res

1.163 - 2025-07-30 16:27:05 +0000 UTC

Range Addition II

Code

class Solution:
    def maxCount(self, m: int, n: int, ops: List[List[int]]) -> int:
        min_row = m
        min_col = n
        for range_row, range_col in ops:
            min_row = min(min_row, range_row)
            min_col = min(min_col, range_col)
        return min_row * min_col

1.164 - 2025-07-30 16:11:57 +0000 UTC

Longest Harmonious Subsequence

Code

class Solution:
    def findLHS(self, nums):
        freq = defaultdict(int)
        max_length = 0
        for num in nums:
            freq[num] += 1
        for num in freq:
            nxt = num + 1
            if nxt not in freq:
                continue
            cur_length = freq[num] + freq[nxt]
            max_length = max(max_length, cur_length)
        return max_length 

1.165 - 2025-07-30 15:59:58 +0000 UTC

N-ary Tree Postorder Traversal

Code

"""
# Definition for a Node.
class Node:
    def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
        self.val = val
        self.children = children
"""

class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        if root is None:
            return []
        res = []
        queue = [root]
        while queue:
            node = queue.pop()
            res.append(node.val)
            for child in node.children:
                queue.append(child)
        res.reverse()
        return res

1.166 - 2025-07-30 15:49:52 +0000 UTC

N-ary Tree Postorder Traversal

Code

"""
# Definition for a Node.
class Node:
    def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
        self.val = val
        self.children = children
"""

class Solution:
    def postorder(self, root: 'Node') -> List[int]:
        res = []
        def dfs(node: Node, res: list[int]) -> None:
            if node is None:
                return
            for child in node.children:
                dfs(child, res)
            res.append(node.val)
        dfs(root, res)
        return res

1.167 - 2025-07-30 15:45:39 +0000 UTC

N-ary Tree Preorder Traversal

Code

"""
# Definition for a Node.
class Node:
    def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
        self.val = val
        self.children = children
"""

class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        if root is None:
            return []
        res = []
        queue = [root]
        while queue:
            node = queue.pop()
            res.append(node.val)
            queue.extend(reversed(node.children))
        return res

1.168 - 2025-07-30 15:44:00 +0000 UTC

N-ary Tree Preorder Traversal

Code

"""
# Definition for a Node.
class Node:
    def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
        self.val = val
        self.children = children
"""

class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        if root is None:
            return []
        res = []
        queue = deque((root, ))
        while queue:
            node = queue.popleft()
            res.append(node.val)
            queue.extendleft(reversed(node.children))
        return res

1.169 - 2025-07-30 15:35:45 +0000 UTC

N-ary Tree Preorder Traversal

Code

"""
# Definition for a Node.
class Node:
    def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
        self.val = val
        self.children = children
"""

class Solution:
    def preorder(self, root: 'Node') -> List[int]:
        res = []
        def dfs(node: Optional[Node], res: list[int]) -> None:
            if node is None:
                return
            res.append(node.val)
            for child in node.children:
                dfs(child, res)
        dfs(root, res)
        return res

1.170 - 2025-07-30 15:07:19 +0000 UTC

Distribute Candies

Code

class Solution:
    def distributeCandies(self, candyType: List[int]) -> int:
        types = set()
        max_length = len(candyType) // 2
        for candy in candyType:
            types.add(candy)
            if len(types) >= max_length:
                return max_length
        return len(types)

1.171 - 2025-07-30 14:54:50 +0000 UTC

Subtree of Another Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
        def dfs(node: Optional[TreeNode], sub_node: Optional[TreeNode]) -> bool:
            if not node and not sub_node:
                return True
            if not node or not sub_node:
                return False
            if node.val != sub_node.val:
                return False
            return dfs(node.left, sub_node.left) and dfs(node.right, sub_node.right)
        
        def dfs2(node: Optional[TreeNode], sub_node: Optional[TreeNode]) -> bool:
            if dfs(node, sub_node):
                return True
            if not node or not sub_node:
                return False
            return dfs2(node.left, sub_node) or dfs2(node.right, sub_node)

        return dfs2(root, subRoot)

1.172 - 2025-07-30 14:36:45 +0000 UTC

Reshape the Matrix

Code

class Solution:
    def matrixReshape(self, mat: List[List[int]], r: int, c: int) -> List[List[int]]:
        if len(mat) * len(mat[0]) != r * c:
            return mat
        new_mat = [[None] * c for _ in range(r)]
        new_row = 0
        new_col = 0
        for row in mat:
            for col in row:
                if new_col == c:
                    new_col = 0
                    new_row += 1
                new_mat[new_row][new_col] = col
                new_col += 1
        return new_mat
                

1.173 - 2025-07-30 13:27:11 +0000 UTC

Binary Tree Tilt

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findTilt(self, root: Optional[TreeNode]) -> int:
        def dfs(node: Optional[TreeNode]) -> tuple[int, int]:
            if node is None:
                return 0, 0
            left_sum, left_tilt = dfs(node.left)
            right_sum, right_tilt = dfs(node.right)
            tilt_sum = left_tilt + right_tilt + abs(left_sum - right_sum)
            node_sum = node.val + left_sum + right_sum
            return node_sum, tilt_sum
        _, tilt_sum = dfs(root)
        return tilt_sum

1.174 - 2025-07-30 13:07:35 +0000 UTC

Array Partition

Code

class Solution:
    def arrayPairSum(self, nums: List[int]) -> int:
        nums.sort()
        length = len(nums)
        i = 0
        sum = 0
        while i < length:
            sum += nums[i]
            i += 2
        return sum

1.175 - 2025-07-30 13:04:16 +0000 UTC

Maximum Depth of N-ary Tree

Code

"""
# Definition for a Node.
class Node:
    def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
        self.val = val
        self.children = children
"""

class Solution:
    def maxDepth(self, root: 'Node') -> int:
        if root is None:
            return 0
        queue: deque[tuple[Node, int]] = deque(((root, 1),))
        max_depth = 0
        while queue:
            node, depth = queue.popleft()
            max_depth = depth
            for child in node.children:
                queue.append((child, 1 + depth))
        return max_depth

1.176 - 2025-07-30 12:53:02 +0000 UTC

Maximum Depth of N-ary Tree

Code

"""
# Definition for a Node.
class Node:
    def __init__(self, val: Optional[int] = None, children: Optional[List['Node']] = None):
        self.val = val
        self.children = children
"""

class Solution:
    def maxDepth(self, root: 'Node') -> int:
        def dfs(node: Node) -> int:
            if not node:
                return 0
            if not node.children:
                return 1
            return 1 + max(dfs(child) for child in node.children)
        return dfs(root)

1.177 - 2025-07-30 12:50:06 +0000 UTC

Student Attendance Record I

Code

class Solution:
    def checkRecord(self, s: str) -> bool:
        a_count = 0
        l_count = 0
        for char in s:
            if char == "P":
                l_count = 0
            elif char == "A":
                a_count += 1
                l_count = 0
            elif char == "L":
                l_count += 1
            if l_count >= 3 or a_count >= 2:
                return False
        return True

1.178 - 2025-07-30 12:40:51 +0000 UTC

Reverse String II

Code

class Solution:
    def reverseStr(self, s: str, k: int) -> str:
        length = len(s)
        if length == 1:
            return s
        if length <= k:
            return s[::-1]
        res = []
        i = 0
        while i < length:
            new_i = i + 2 * k
            res.append(s[i+k-1:i:-1])
            res.append(s[i])
            res.append(s[i+k:new_i])
            i = new_i
        return "".join(res)

1.179 - 2025-07-30 12:11:27 +0000 UTC

Longest Uncommon Subsequence I

Code

class Solution:
    def findLUSlength(self, a: str, b: str) -> int:
        if a == b:
            return -1
        else:
            return max(len(a), len(b))

1.180 - 2025-07-30 12:08:16 +0000 UTC

Longest Subarray With Maximum Bitwise AND

Code

class Solution:
    def longestSubarray(self, nums: List[int]) -> int:
        max_val = ans = current_streak = 0
        for num in nums:
            if max_val < num:
                max_val = num
                ans = current_streak = 0
            if max_val == num:
                current_streak += 1
            else:
                current_streak = 0
            ans = max(ans, current_streak)
        return ans

1.181 - 2025-07-30 12:06:29 +0000 UTC

Longest Subarray With Maximum Bitwise AND

Code

class Solution:
    def longestSubarray(self, nums: List[int]) -> int:
        max_and = max(nums)
        max_length = 0        
        cur_length = 0
        for num in nums:
            if num == max_and:
                cur_length += 1
            else:
                max_length = max(max_length, cur_length)
                cur_length = 0
        return max(max_length, cur_length)

1.182 - 2025-07-30 11:49:28 +0000 UTC

Detect Capital

Code

class Solution:
    def detectCapitalUse(self, word: str) -> bool:
        length = len(word)
        if length == 1:
            return True
        def is_cap(char: str) -> bool:
            res = 65 <= ord(char) <= 90
            return res
        first_cap, second_cap = is_cap(word[0]), is_cap(word[1])
        if first_cap and second_cap:
            should_be_cap = True
        elif first_cap and not second_cap:
            should_be_cap = False
        elif not first_cap and second_cap:
            return False
        elif not first_cap and not second_cap:
            should_be_cap = False
        else:
            raise Exception
        for char in word[2:]:
            if is_cap(char) != should_be_cap:
                return False
        return True

1.183 - 2025-07-29 18:05:02 +0000 UTC

Perfect Number

Code

class Solution:
    def checkPerfectNumber(self, num: int) -> bool:
        if num == 1:
            return False
        count = 1
        for i in range(2, int(num**0.5) + 1):
            if num % i == 0:
                count += i + (num // i)
        return num == count

1.184 - 2025-07-29 17:50:01 +0000 UTC

Base 7

Code

class Solution:
    def convertToBase7(self, num: int) -> str:
        if num > -7 and num < 7:
            return str(num)
        res_arr = []
        sign = ""
        if num < 0:
            sign = "-"
            num = -num
        while num:
            res_arr.append(str(num % 7))
            num //= 7
        res = sign + "".join(reversed(res_arr))
        return res

1.185 - 2025-07-29 17:45:22 +0000 UTC

Next Greater Element I

Code

class Solution:
    def nextGreaterElement(self, nums1: list[int], nums2: list[int]) -> list[int]:
        stack = []
        greater = {}
        for num in nums2:
            while stack and num > stack[-1]:
                greater[stack.pop()] = num
            stack.append(num)
        for num in stack:
            greater[num] = -1
        return [greater[num] for num in nums1]

1.186 - 2025-07-29 16:17:54 +0000 UTC

Teemo Attacking

Code

class Solution:
    def findPoisonedDuration(self, timeSeries: List[int], duration: int) -> int:
        total = 0
        cur_end = -1
        for second in timeSeries:
            if second > cur_end:
                total += duration
            else:
                total += duration - (cur_end - second) - 1
            cur_end = second + duration - 1
        return total

1.187 - 2025-07-29 15:55:38 +0000 UTC

Hamming Distance

Code

class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        count = 0
        while x or y:
            if x % 2 != y % 2:
                count += 1
            x //= 2
            y //= 2
        return count

1.188 - 2025-07-29 15:52:23 +0000 UTC

Number of Segments in a String

Code

class Solution:
    def countSegments(self, s: str) -> int:
        length = len(s)
        count = 0
        is_segment = False
        for char in s:
            is_space = char == " "
            if not is_segment and not is_space:
                is_segment = True
                count += 1
            elif is_space:
                is_segment = False
        return count

1.189 - 2025-07-29 15:27:23 +0000 UTC

Convert a Number to Hexadecimal

Code

class Solution:
    def toHex(self, num: int) -> str:
        if num >=0 and num < 10:
            return str(num)
        if num < 0:
            num = (1 << 32) + num
        symbols = "0123456789abcdef"
        res = []
        while num > 0:
            mod = num % 16
            res.append(symbols[mod])
            num //= 16
        return "".join(reversed(res))

1.190 - 2025-07-29 14:59:54 +0000 UTC

Binary Watch

Code

class Solution:
    def readBinaryWatch(self, num: int) -> list[str]:
        times = []

        for h in range(12):
            for m in range(60):
                hOnes = bin(h).count('1')
                mOnes = bin(m).count('1')
                if hOnes + mOnes == num:
                    times.append(f"{h}:{m:02d}")

        return times

1.191 - 2025-07-29 14:38:44 +0000 UTC

Nim Game

Code

class Solution:
    def canWinNim(self, n: int) -> bool:
        return n % 4 != 0

1.192 - 2025-07-29 14:38:31 +0000 UTC

Nim Game

Code

class Solution:
    def canWinNim(self, n: int) -> bool:
        if n < 3:
            return True
        True, True, True, False, True, True, True
        1,    2,    3,    4,     5,    6,    7    
        return n % 4 != 0

1.193 - 2025-07-29 10:59:48 +0000 UTC

Smallest Subarrays With Maximum Bitwise OR

Code

class Solution:
    def smallestSubarrays(self, nums: List[int]) -> List[int]:
        n = len(nums)
        pos = [-1] * 31
        ans = [0] * n
        for i in range(n - 1, -1, -1):
            j = i
            for bit in range(31):
                if (nums[i] & (1 << bit)) == 0:
                    if pos[bit] != -1:
                        j = max(j, pos[bit])
                else:
                    pos[bit] = i
            ans[i] = j - i + 1
        return ans

1.194 - 2025-07-28 13:25:34 +0000 UTC

Count Number of Maximum Bitwise-OR Subsets

Code

class Solution:
    def countMaxOrSubsets(self, nums: List[int]) -> int:
        max_or_value = 0
        n = len(nums)
        for num in nums:
            max_or_value |= num
        memo = [[-1] * (max_or_value + 1) for _ in range(n)]
        return self._count_subsets_recursive(nums, 0, 0, max_or_value, memo)

    def _count_subsets_recursive(
        self,
        nums: List[int],
        index: int,
        current_or: int,
        target_or: int,
        memo: List[List[int]],
    ) -> int:
        if index == len(nums):
            return 1 if current_or == target_or else 0
        if memo[index][current_or] != -1:
            return memo[index][current_or]
        count_without = self._count_subsets_recursive(
            nums, index + 1, current_or, target_or, memo
        )
        count_with = self._count_subsets_recursive(
            nums, index + 1, current_or | nums[index], target_or, memo
        )
        res = count_without + count_with
        memo[index][current_or] = res
        return res

1.195 - 2025-07-27 16:03:38 +0000 UTC

Count Hills and Valleys in an Array

Code

class Solution:
    def countHillValley(self, nums: List[int]) -> int:
        res = 0
        length = len(nums)
        for i in range(1, length - 1):
            if nums[i] == nums[i - 1]:
                continue
            left = 0
            for j in range(i - 1, -1, -1):
                if nums[j] > nums[i]:
                    left = 1
                    break
                elif nums[j] < nums[i]:
                    left = -1
                    break
            right = 0
            for j in range(i + 1, length):
                if nums[j] > nums[i]:
                    right = 1
                    break
                elif nums[j] < nums[i]:
                    right = -1
                    break
            if left == right and left != 0:
                res += 1
        return res

1.196 - 2025-07-26 15:50:49 +0000 UTC

Maximize Subarrays After Removing One Conflicting Pair

Code

class Solution:
    def maxSubarrays(self, n: int, conflictingPairs: List[List[int]]) -> int:
        bMin1 = [2**31 - 1] * (n + 1)
        bMin2 = [2**31 - 1] * (n + 1)
        for pair in conflictingPairs:
            a = min(pair[0], pair[1])
            b = max(pair[0], pair[1])
            if bMin1[a] > b:
                bMin2[a] = bMin1[a]
                bMin1[a] = b
            elif bMin2[a] > b:
                bMin2[a] = b
        res = 0
        ib1 = n
        b2 = 0x3FFFFFFF
        delCount = [0] * (n + 1)
        for i in range(n, 0, -1):
            if bMin1[ib1] > bMin1[i]:
                b2 = min(b2, bMin1[ib1])
                ib1 = i
            else:
                b2 = min(b2, bMin1[i])
            res += min(bMin1[ib1], n + 1) - i
            delCount[ib1] += min(min(b2, bMin2[ib1]), n + 1) - min(
                bMin1[ib1], n + 1
            )
        return res + max(delCount)

1.197 - 2025-07-26 15:48:20 +0000 UTC

Ugly Number

Code

class Solution(object):
    def isUgly(self, n):
        if n <= 0:
            return False
        
        while n % 2 == 0:
            n //= 2
        while n % 3 == 0:
            n //= 3
        while n % 5 == 0:
            n //= 5
        
        return n == 1

1.198 - 2025-07-25 10:23:28 +0000 UTC

1-bit and 2-bit Characters

Code

class Solution(object):
    def isOneBitCharacter(self, bits):
        i = 0
        while i < len(bits) - 1:
            i += bits[i] + 1
        return i == len(bits) - 1

1.199 - 2025-07-25 10:15:13 +0000 UTC

To Lower Case

Code

class Solution:
    def toLowerCase(self, s: str) -> str:
        return s.lower()

1.200 - 2025-07-25 10:14:11 +0000 UTC

Kth Largest Element in a Stream

Code

class KthLargest:

    def __init__(self, k: int, nums: List[int]):
        if len(nums) < k:
            nums.extend((float("-inf"),) * (k - len(nums)))
        nums.sort()
        self._nums: list[int] = nums[-k:]
        self._k: int = k
        
    def add(self, val: int) -> int:
        if val > self._nums[0]:
            self._nums[0] = val
            self._nums.sort()
        return self._nums[-self._k]

# Your KthLargest object will be instantiated and called as such:
# obj = KthLargest(k, nums)
# param_1 = obj.add(val)

1.201 - 2025-07-25 09:37:39 +0000 UTC

Number of Students Doing Homework at a Given Time

Code

class Solution:
    def busyStudent(self, startTime: List[int], endTime: List[int], queryTime: int) -> int:
        count = 0
        for start, end in zip(startTime, endTime):
            if queryTime >= start and queryTime <= end:
                count += 1
        return count

1.202 - 2025-07-25 09:29:53 +0000 UTC

Count Negative Numbers in a Sorted Matrix

Code

class Solution:
    def countNegatives(self, grid: List[List[int]]) -> int:
        count = 0
        for i, row in enumerate(grid):
            for j, num in enumerate(row):
                if num < 0:
                    count += len(row) - j
                    break 
        return count

1.203 - 2025-07-25 09:07:53 +0000 UTC

Delete Characters to Make Fancy String

Code

class Solution:
    def makeFancyString(self, s: str) -> str:
        length = len(s)
        if length < 3:
            return s
        prev_char, prev_char_count = "", 0
        res = []
        for char in s:
            if char != prev_char:
                prev_char = char
                prev_char_count = 1
                res.append(char)
            elif prev_char_count < 2:
                prev_char_count += 1
                res.append(char)
        return "".join(res)

1.204 - 2025-07-25 08:57:05 +0000 UTC

Maximum Erasure Value

Code

class Solution:
    def maximumUniqueSubarray(self, nums: List[int]) -> int:
        sub: deque[int] = deque()
        sub_nums: set[int] = set()
        cur_sum: int = 0
        max_sum: int = 0
        for num in nums:
            while num in sub_nums:
                sub_num = sub.popleft()
                sub_nums.remove(sub_num)
                cur_sum -= sub_num
            sub.append(num)
            sub_nums.add(num)
            cur_sum += num
            max_sum = max(cur_sum, max_sum)
        return max_sum
                
            

1.205 - 2025-07-25 06:50:01 +0000 UTC

Maximum Unique Subarray Sum After Deletion

Code

class Solution:
    def maxSum(self, nums: List[int]) -> int:
        if len(nums) == 1:
            return nums[0]
        nums.sort()
        if nums[-1] <= 0:
            return nums[-1]
        res = 0
        if nums[0] > 0:
            res = nums[0]
        for i, num in enumerate(nums[1:], 1):
            if num <= 0 or num == nums[i - 1]:
                continue
            res += num
        return res

1.206 - 2025-07-24 15:52:24 +0000 UTC

Maximum Score From Removing Substrings

Code

class Solution:
    def maximumGain(self, s: str, x: int, y: int) -> int:
        total_score = 0
        high_priority_pair = "ab" if x > y else "ba"
        low_priority_pair = "ba" if high_priority_pair == "ab" else "ab"

        # First pass: remove high priority pair
        string_after_first_pass = self.remove_substring(s, high_priority_pair)
        removed_pairs_count = (len(s) - len(string_after_first_pass)) // 2

        # Calculate score from first pass
        total_score += removed_pairs_count * max(x, y)

        # Second pass: remove low priority pair
        string_after_second_pass = self.remove_substring(
            string_after_first_pass, low_priority_pair
        )
        removed_pairs_count = (
            len(string_after_first_pass) - len(string_after_second_pass)
        ) // 2

        # Calculate score from second pass
        total_score += removed_pairs_count * min(x, y)

        return total_score

    def remove_substring(self, input: str, target_pair: str) -> str:
        char_stack = []

        # Iterate through each character in the input string
        for current_char in input:
            # Check if current character forms the target pair with the top of the stack
            if (
                current_char == target_pair[1]
                and char_stack
                and char_stack[-1] == target_pair[0]
            ):
                char_stack.pop()  # Remove the matching character from the stack
            else:
                char_stack.append(current_char)

        # Reconstruct the remaining string after removing target pairs
        return "".join(char_stack)

1.207 - 2025-07-24 14:40:53 +0000 UTC

Minimum Score After Removals on a Tree

Code

class Solution:
    def calc(self, part1: int, part2: int, part3: int) -> int:
        return max(part1, part2, part3) - min(part1, part2, part3)

    def minimumScore(self, nums: List[int], edges: List[List[int]]) -> int:
        length = len(nums)
        parent_to_child: list[int] = [[] for _ in range(length)]
        for node_1, node_2 in edges:
            parent_to_child[node_1].append(node_2)
            parent_to_child[node_2].append(node_1)

        total = 0
        for num in nums:
            total ^= num

        res = float("inf")

        def dfs2(node: int, parent: int, oth: int, anc: int) -> int:
            son = nums[node]
            for child in parent_to_child[node]:
                if child == parent:
                    continue
                son ^= dfs2(child, node, oth, anc)
            if parent == anc:
                return son
            nonlocal res
            res = min(res, self.calc(oth, son, total ^ oth ^ son))
            return son

        def dfs(node: int, parent: int) -> int:
            son = nums[node]
            for child in parent_to_child[node]:
                if child == parent:
                    continue
                son ^= dfs(child, node)
            for child in parent_to_child[node]:
                if child == parent:
                    dfs2(child, node, son, node)
            return son

        dfs(0, -1)
        return res

1.208 - 2025-07-20 13:53:28 +0000 UTC

Delete Duplicate Folders in System

Code

class Trie:
    serial: str = ""
    children: dict[str, "Trie"]

    def __init__(self) -> None:
        self.children = dict()


class Solution:
    def deleteDuplicateFolder(self, paths: List[List[str]]) -> List[List[str]]:
        root = Trie()
        freq = Counter()

        for path in paths:
            cur = root
            for node in path:
                if node not in cur.children:
                    cur.children[node] = Trie()
                cur = cur.children[node]

        
        def construct(node: Trie) -> None:
            if not node.children:
                return

            serial: list[str] = []
            for folder, child in node.children.items():
                construct(child)
                serial.append(f"{folder}({child.serial})")

            serial.sort()
            node.serial = "".join(serial)
            freq[node.serial] += 1

        construct(root)

        ans = list()
        path = list()

        def operate(node: Trie) -> None:
            if freq[node.serial] > 1:
                return
            if path:
                ans.append(path[:])

            for folder, child in node.children.items():
                path.append(folder)
                operate(child)
                path.pop()

        operate(root)
        return ans

1.209 - 2025-04-15 13:14:06 +0000 UTC

Count Good Triplets in an Array

Code

from sortedcontainers import SortedList
from typing import List

class Solution:
    def goodTriplets(self, nums1: List[int], nums2: List[int]) -> int:

        index_map = {num: i for i, num in enumerate(nums2)}
  
        indices = [index_map[num] for num in nums1]

        left_counts = []
        left_sorted = SortedList()
        for idx in indices:
            left_counts.append(left_sorted.bisect_left(idx))
            left_sorted.add(idx)

        right_counts = []
        right_sorted = SortedList()
        for idx in reversed(indices):
            right_counts.append(len(right_sorted) - right_sorted.bisect_right(idx))
            right_sorted.add(idx)
        right_counts.reverse() 
        
        return sum(left * right for left, right in zip(left_counts, right_counts))

1.210 - 2025-04-14 16:45:07 +0000 UTC

Count Good Triplets

Code

class Solution:
    def countGoodTriplets(self, arr: List[int], a: int, b: int, c: int) -> int:
        ans = 0
        n = len(arr)
        total = [0] * 1001
        for j in range(n):
            for k in range(j + 1, n):
                if abs(arr[j] - arr[k]) <= b:
                    lj, rj = arr[j] - a, arr[j] + a
                    lk, rk = arr[k] - c, arr[k] + c
                    l = max(0, lj, lk)
                    r = min(1000, rj, rk)
                    if l <= r:
                        ans += total[r] if l == 0 else total[r] - total[l - 1]
            for k in range(arr[j], 1001):
                total[k] += 1

        return ans

1.211 - 2025-04-13 14:10:23 +0000 UTC

Count Good Numbers

Code

class Solution:
    def countGoodNumbers(self, n: int) -> int:
        mod = 10**9 + 7

        # use fast exponentiation to calculate x^y % mod
        def quickmul(x: int, y: int) -> int:
            ret, mul = 1, x
            while y > 0:
                if y % 2 == 1:
                    ret = ret * mul % mod
                mul = mul * mul % mod
                y //= 2
            return ret

        return quickmul(5, (n + 1) // 2) * quickmul(4, n // 2) % mod

1.212 - 2025-04-12 16:10:13 +0000 UTC

Find the Count of Good Integers

Code

class Solution(object):
    def __init__(self):
        self.res = 0
        self.visited = set()

    def vectorToNumber(self, digits):
        return int(''.join(map(str, digits)))

    def totalPermutations(self, freqMap, total):
        res = factorial(total)
        for count in freqMap.values():
            res //= factorial(count)
        return res

    def permsWithZero(self, freqMap, total):
        if freqMap.get(0, 0) == 0:
            return 0
        freqMap[0] -= 1
        res = factorial(total - 1)
        for count in freqMap.values():
            res //= factorial(count)
        return res

    def genPal(self, palin, left, right, divisor, total):
        if left > right:
            palinVal = self.vectorToNumber(palin)
            if palinVal % divisor == 0:
                freq = Counter(palin)
                key = tuple(sorted(freq.items()))
                if key not in self.visited:
                    self.res += self.totalPermutations(freq, total) - self.permsWithZero(freq.copy(), total)
                    self.visited.add(key)
            return

        for dig in range(1 if left == 0 else 0, 10):
            palin[left] = palin[right] = dig
            self.genPal(palin, left + 1, right - 1, divisor, total)

    def countGoodIntegers(self, n, k):
        self.res = 0
        self.visited.clear()
        self.genPal([0] * n, 0, n - 1, k, n)
        return self.res

1.213 - 2025-04-11 17:06:54 +0000 UTC

Count Symmetric Integers

Code

class Solution:
    def countSymmetricIntegers(self, low: int, high: int) -> int:
        count = 0
        for num in range(low, high + 1):
            s = str(num)
            if len(s) % 2 == 0:
                mid = len(s) // 2
                if sum(map(int, s[:mid])) == sum(map(int, s[mid:])):
                    count += 1
        return count

1.214 - 2025-04-10 16:50:16 +0000 UTC

Count the Number of Powerful Integers

Code

class Solution:
    def numberOfPowerfulInt(self, start: int, finish: int, limit: int, suffix: str) -> int:
        def count_powerful_up_to(num: int) -> int:
            num_str = str(num)
            suffix_len = len(suffix)
            prefix_len = len(num_str) - suffix_len

            if prefix_len < 0:
                return 0

            dp = [[0] * 2 for _ in range(prefix_len + 1)]

            dp[prefix_len][0] = 1
            suffix_from_num = num_str[prefix_len:]
            dp[prefix_len][1] = int(suffix_from_num) >= int(suffix)

            for i in range(prefix_len - 1, -1, -1):
                digit = int(num_str[i])
                dp[i][0] = (limit + 1) * dp[i + 1][0]
                if digit <= limit:
                    dp[i][1] = digit * dp[i + 1][0] + dp[i + 1][1]
                else:
                    dp[i][1] = (limit + 1) * dp[i + 1][0]

            return dp[0][1]

        return count_powerful_up_to(finish) - count_powerful_up_to(start - 1)

1.215 - 2025-04-09 16:33:13 +0000 UTC

Minimum Operations to Make Array Values Equal to K

Code

class Solution:
    def minOperations(self, nums: List[int], k: int) -> int:
        if not nums:
            return -1
        nums.sort(reverse=True)
        if nums[-1] < k:
            return -1
        prev = nums[0]
        if prev == k:
            return 0
        ops = 0
        for num in nums[1:]:
            if num == prev:
                continue
            ops += 1
            prev = num
            if num == k:
                return ops
        return ops + 1

1.216 - 2024-06-28 16:53:30 +0000 UTC

Maximum Total Importance of Roads

Code

class Solution:
    def maximumImportance(self, n: int, roads: List[List[int]]) -> int:
        res = 0
        cost = 1
        conn = [0] * n
        for road in roads:
            conn[road[0]] += 1
            conn[road[1]] += 1

        conn.sort()
        for con in conn:
            res += con * cost
            cost += 1
        return res

1.217 - 2024-06-26 15:39:14 +0000 UTC

Balance a Binary Search Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def balanceBST(self, root: TreeNode) -> TreeNode:
        self.sortedArr = []
        self.inorderTraverse(root)
        return self.sortedArrayToBST(0, len(self.sortedArr) - 1)

    def inorderTraverse(self, root: TreeNode) -> None:
        if not root:
            return
        self.inorderTraverse(root.left)
        self.sortedArr.append(root)
        self.inorderTraverse(root.right)

    def sortedArrayToBST(self, start: int, end: int) -> TreeNode:
        if start > end:
            return None
        mid = (start + end) // 2
        root = self.sortedArr[mid]
        root.left = self.sortedArrayToBST(start, mid - 1)
        root.right = self.sortedArrayToBST(mid + 1, end)
        return root        

1.218 - 2024-06-25 17:07:01 +0000 UTC

Binary Search Tree to Greater Sum Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def bstToGst(self, root: TreeNode) -> TreeNode:
        self.val = 0
        
        def dfs(node):
            if not node:
                return
            
            dfs(node.right)
            self.val += node.val
            node.val = self.val
            dfs(node.left)
        
        dfs(root)
        return root

1.219 - 2024-06-24 12:55:17 +0000 UTC

Minimum Number of K Consecutive Bit Flips

Code

class Solution:
    def minKBitFlips(self, A: List[int], K: int) -> int:
        n, flipped, res = len(A), 0, 0
        fp = [0] * n
        for i in range(n):
            if i >= K:
                flipped ^= fp[i - K]
            if flipped == A[i]:
                if i + K > n:
                    return -1
                fp[i] = 1
                flipped ^= 1
                res += 1
        return res

1.220 - 2024-06-23 11:38:18 +0000 UTC

Longest Continuous Subarray With Absolute Diff Less Than or Equal to Limit

Code

class Solution:
    def longestSubarray(self, nums: List[int], limit: int) -> int:
        decQ = collections.deque() 
        incQ = collections.deque() 
        ans = 0
        left = 0

        for right, num in enumerate(nums):
            while decQ and num > decQ[-1]:
                decQ.pop()

            decQ.append(num)

            while incQ and num < incQ[-1]:
                incQ.pop()

            incQ.append(num)

            while decQ[0] - incQ[0] > limit:
                if decQ[0] == nums[left]:
                    decQ.popleft()

                if incQ[0] == nums[left]:
                    incQ.popleft()

                left += 1

            ans = max(ans, right - left + 1)

        return ans

1.221 - 2024-06-22 13:33:20 +0000 UTC

Count Number of Nice Subarrays

Code

class Solution:
    def numberOfSubarrays(self, nums: List[int], k: int) -> int:
        for i in range(len(nums)):
            nums[i] %= 2
        
        prefix_count = [0] * (len(nums) + 1)
        prefix_count[0] = 1
        s = 0
        ans = 0
        
        for num in nums:
            s += num
            if s >= k:
                ans += prefix_count[s - k]
            prefix_count[s] += 1
        
        return ans

1.222 - 2024-06-21 16:21:07 +0000 UTC

Grumpy Bookstore Owner

Code

class Solution:
    def maxSatisfied(self, customers: List[int], grumpy: List[int], minutes: int) -> int:
        ans = 0
        total = sum((1 - grumpy[i]) * customers[i] for i in range(len(customers)))

        window_all = 0
        window_partial = 0
        for i in range(len(customers)):
            window_all += customers[i]
            window_partial += (1 - grumpy[i]) * customers[i]
            if i + 1 >= minutes:
                ans = max(ans, total - window_partial + window_all)
                left = i - minutes + 1
                window_all -= customers[left]
                window_partial -= (1 - grumpy[left]) * customers[left]

        return ans

1.223 - 2024-06-19 16:59:31 +0000 UTC

Minimum Number of Days to Make m Bouquets

Code

class Solution:
    def minDays(self, bloomDay: List[int], m: int, k: int) -> int:
        n=len(bloomDay)
        if m*k>n: return -1

        def f(d):
            len, bouquet=0, 0
            i=0
            while i<n:
                while i<n and bloomDay[i]<=d:
                    len+=1
                    if len==k:
                        bouquet+=1
                        len=0
                    i+=1
                if i<n and bloomDay[i]>d: len=0
                if bouquet>m: return True
                i+=1
            return bouquet>=m

        l, r = min(bloomDay), max(bloomDay)
        while l < r:
            mid = l + (r - l) // 2
            if f(mid):
                r = mid
            else:
                l = mid + 1
        return l
        

1.224 - 2024-06-17 12:39:57 +0000 UTC

Sum of Square Numbers

Code

from math import sqrt

class Solution:
    def judgeSquareSum(self, c: int) -> bool:
        for a in range(int(sqrt(c)) + 1):  # Iterate through all possible values of `a`
            b = sqrt(c - a * a)  # Compute `b` as the square root of `c - a^2`
            if b == int(b):  # Check if `b` is an integer
                return True  # If `b` is an integer, return true
        return False  # If no such pair `(a, b)` is found, return false

1.225 - 2024-06-15 10:32:54 +0000 UTC

IPO

Code

class Solution:
    def findMaximizedCapital(
        self, k: int, w: int, profits: List[int], capital: List[int]
    ) -> int:
        n = len(profits)
        projects = [(capital[i], profits[i]) for i in range(n)]
        projects.sort()
        maxHeap = []
        i = 0
        for _ in range(k):
            while i < n and projects[i][0] <= w:
                heapq.heappush(maxHeap, -projects[i][1])
                i += 1
            if not maxHeap:
                break
            w -= heapq.heappop(maxHeap)

        return w

1.226 - 2024-06-14 15:54:35 +0000 UTC

Minimum Increment to Make Array Unique

Code

class Solution:
    def minIncrementForUnique(self, nums: List[int]) -> int:
        # nums = [3,2,1,2,1,7]
        #        [1,1,2,2,3,7]

        # mySet = set({ num for num in nums }), 2+4
        nums.sort()
        numTracker = 0
        minIncreament = 0

        for num in nums:
            numTracker = max(numTracker, num)
            minIncreament += numTracker - num
            numTracker += 1
        return minIncreament

1.227 - 2024-06-13 07:32:12 +0000 UTC

Minimum Number of Moves to Seat Everyone

Code

class Solution:
    def minMovesToSeat(self, seats: List[int], students: List[int]) -> int:
        seats.sort()
        students.sort()
        moves = 0

        for i in range(len(seats)) :
            moves += abs(seats[i] - students[i])

        return moves

1.228 - 2024-06-12 16:59:15 +0000 UTC

Sort Colors

Code

class Solution:
    def sortColors(self, nums: List[int]) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        zeros, ones, n = 0, 0, len(nums)
        for num in nums:
            if num == 0:
                zeros += 1
            elif num == 1:
                ones += 1

        for i in range(0, zeros):
            nums[i] = 0

        for i in range(zeros, zeros + ones):
            nums[i] = 1

        for i in range(zeros + ones, n):
            nums[i] = 2

1.229 - 2024-06-11 17:57:06 +0000 UTC

Relative Sort Array

Code

class Solution:
    def relativeSortArray(self, arr1, arr2):
        result = []
        
        for i in range(len(arr2)):
            for j in range(len(arr1)):
                if arr1[j] == arr2[i]:
                    result.append(arr1[j])
                    arr1[j] = -1
        
        arr1.sort()
        
        for num in arr1:
            if num != -1:
                result.append(num)
                
        return result

1.230 - 2024-06-10 10:15:44 +0000 UTC

Height Checker

Code

class Solution:
    def heightChecker(self, heights: List[int]) -> int:
        return sum(h!=s for h, s in zip(heights, sorted(heights)))

1.231 - 2024-06-09 10:56:45 +0000 UTC

Subarray Sums Divisible by K

Code

class Solution:
    def subarraysDivByK(self, nums: List[int], k: int) -> int:
        count = 0
        prefix_sum = 0
        prefix_map = {0: 1}  
        
        for num in nums:
            prefix_sum += num
            mod = prefix_sum % k
            if mod < 0:  
                mod += k
            if mod in prefix_map:
                count += prefix_map[mod]
                prefix_map[mod] += 1
            else:
                prefix_map[mod] = 1
        
        return count

1.232 - 2024-06-08 19:13:27 +0000 UTC

Continuous Subarray Sum

Code

class Solution:
    def checkSubarraySum(self, nums: List[int], k: int) -> bool:
        remainder_map = {0: -1}  
        cumulative_sum = 0
        
        for i, num in enumerate(nums):
            cumulative_sum += num
            remainder = cumulative_sum % k
            if remainder in remainder_map:
                if i - remainder_map[remainder] > 1:
                    return True
            else:
                remainder_map[remainder] = i
        return False

1.233 - 2024-06-07 15:18:51 +0000 UTC

Replace Words

Code

class Solution:
    def replaceWords(self, dict: List[str], sentence: str) -> str:
        roots = set(dict)
        words = sentence.split()
        result = []

        for word in words:
            for i in range(len(word) + 1):
                prefix = word[:i]
                if prefix in roots:
                    result.append(prefix)
                    break
            else:
                result.append(word)

        return ' '.join(result)

1.234 - 2024-06-06 15:22:03 +0000 UTC

Hand of Straights

Code

class Solution:
    def isNStraightHand(self, hand: List[int], groupSize: int) -> bool:
        # Step 1: Check if grouping is possible
        if len(hand) % groupSize != 0:
            return False
        
        # Step 2: Count the occurrences of each card
        count = Counter(hand)
        
        # Step 3: Sort the unique card values
        sorted_keys = sorted(count.keys())
        
        # Step 4: Form consecutive groups
        for key in sorted_keys:
            if count[key] > 0:  # If this card is still available
                start_count = count[key]
                # Check and form a group starting from `key`
                for i in range(key, key + groupSize):
                    if count[i] < start_count:
                        return False
                    count[i] -= start_count
        
        # Step 5: Return True if all groups are formed successfully
        return True

1.235 - 2024-06-05 07:32:36 +0000 UTC

Find Common Characters

Code

class Solution:
    def commonChars(self, words: List[str]) -> List[str]:
        result = []
        
        # Check each character from 'a' to 'z'
        for char in range(ord('a'), ord('z') + 1):
            char = chr(char)
            min_count = float('inf')  # Start with a very high number
            
            # Find the minimum count of the character in all words
            for word in words:
                count = word.count(char)  # Count the current character in the current word
                min_count = min(min_count, count)  # Keep track of the smallest count
                if min_count == 0:
                    break  # If the character is not in one of the words, we can skip further checking
            
            # Add the character to the result list the required number of times
            result.extend([char] * min_count)
        
        return result

1.236 - 2024-06-03 12:40:20 +0000 UTC

Append Characters to String to Make Subsequence

Code

class Solution:
    def appendCharacters(self, s: str, t: str) -> int:
        i, j = 0, 0  # Start both pointers at the beginning of s and t
        
        while i < len(s) and j < len(t):  # Continue until one of the strings is fully scanned
            if s[i] == t[j]:  # If characters match
                j += 1  # Move the pointer in t forward
            i += 1  # Always move the pointer in s forward
        
        return len(t) - j  # The number of characters in t not matched in s
               

1.237 - 2024-06-02 18:31:18 +0000 UTC

Student Attendance Record II

Code

class Solution:
    def checkRecord(self, n: int) -> int:
        # Recursion + Cache
        mod=10**9+7
        #only @cache will lead to MLE
        dp=[[[-1]*3 for _ in range(2)] for _ in range(n+1)]
        def f(i, absent, late):
            if absent>=2 or late>=3: return 0
            if i==0: return 1
            if dp[i][absent][late]!=-1:
                return dp[i][absent][late]
            ans=f(i-1, absent, 0)
            ans+=f(i-1, absent, late+1)
            ans+=f(i-1, absent+1, 0)
            dp[i][absent][late]=ans%mod
            return dp[i][absent][late]
        return f(n, 0, 0)

1.238 - 2024-06-01 19:04:19 +0000 UTC

Single Number III

Code

class Solution:
    def singleNumber(self, nums: list[int]) -> list[int]:
        n: int = len(nums)
        result: list[int] = [0, 0]
        index = 0

        for i in range(n):
            found = False
            for j in range(n):
                if i != j and nums[i] == nums[j]:
                    found = True
                    break
            if not found:
                result[index] = nums[i]
                index += 1
                if index == 2:
                    break

        return result

1.239 - 2024-06-01 19:04:02 +0000 UTC

Count Triplets That Can Form Two Arrays of Equal XOR

Code

class Solution:
    def countTriplets(self, arr: List[int]) -> int:
        n = len(arr)
        prefix = [0] * (n + 1)
        
        for i in range(n):
            prefix[i + 1] = prefix[i] ^ arr[i]
        
        count = 0
        for i in range(n):
            for k in range(i + 1, n):
                if prefix[i] == prefix[k + 1]:
                    count += (k - i)
        
        return count

1.240 - 2024-06-01 19:03:45 +0000 UTC

Maximum Score Words Formed by Letters

Code

class Solution:
    def maxScoreWords(
        self, words: List[str], letters: List[str], score: List[int]
    ) -> int:
        lettersCounter = Counter(letters)
        totalScore = 0

        def explore(index, letterCounter, currScore):
            nonlocal totalScore

            totalScore = max(totalScore, currScore)
            if index == len(words):
                return

            for i in range(index, len(words)):
                tmpCounter = copy.deepcopy(letterCounter)
                word = words[i]
                wordScore = 0
                isValid = True

                for ch in word:
                    if ch in tmpCounter and tmpCounter[ch] > 0:
                        tmpCounter[ch] -= 1
                        wordScore += score[ord(ch) - ord("a")]
                    else:
                        isValid = False
                        break
                if isValid:
                    explore(i + 1, tmpCounter, currScore + wordScore)

        explore(0, lettersCounter, 0)
        return totalScore

1.241 - 2024-06-01 19:01:30 +0000 UTC

Score of a String

Code

class Solution:
    def scoreOfString(self, s: str) -> int:
        score = 0
        for i in range(len(s) - 1):
            score += abs(ord(s[i]) - ord(s[i + 1]))
        return score               

1.242 - 2024-05-29 09:47:46 +0000 UTC

Number of Steps to Reduce a Number in Binary Representation to One

Code

class Solution:
    def numSteps(self, s: str) -> int:
        steps = 0
        carry = 0
        n = len(s) - 1
        for i in range(n, 0, -1):
            if int(s[i]) + carry == 1:
                carry = 1
                steps += 2
            else:
                steps += 1
        return steps + carry

        

1.243 - 2024-05-28 17:05:20 +0000 UTC

Get Equal Substrings Within Budget

Code

class Solution:
    def equalSubstring(self, s: str, t: str, maxCost: int) -> int:
        n = len(s)
        start = 0
        current_cost = 0
        max_length = 0

        for end in range(n):
            current_cost += abs(ord(s[end]) - ord(t[end]))

            while current_cost > maxCost:
                current_cost -= abs(ord(s[start]) - ord(t[start]))
                start += 1

            max_length = max(max_length, end - start + 1)
        
        return max_length

1.244 - 2024-05-27 07:56:18 +0000 UTC

Special Array With X Elements Greater Than or Equal X

Code

class Solution:
    def specialArray(self, nums: list[int]) -> int:
        nums.sort()
        n: int = len(nums)

        def find_number_of_nums(cur_num) -> int:
            left: int = 0
            right: int = n - 1

            first_index: int = n
            while left <= right:
                mid: int = (left + right) // 2

                if nums[mid] >= cur_num:
                    first_index = mid
                    right = mid - 1
                else:
                    left = mid + 1

            return n - first_index

        for candidate_number in range(1, n + 1, 1):
            if candidate_number == find_number_of_nums(candidate_number):
                return candidate_number

        return -1

1.245 - 2024-05-26 17:44:15 +0000 UTC

Student Attendance Record II

Code

class Solution:
    def checkRecord(self, n: int) -> int:
        temp: list[list[list[int]]] = [
            [[-1 for _ in range(3)] for _ in range(2)] for _ in range(n)
        ]  # temp[cur_ind][count_a][count_l]
        MOD: int = 10**9 + 7

        def check_all_records(cur_ind, count_a, count_l) -> int:
            if cur_ind == n:
                return 1
            if temp[cur_ind][count_a][count_l] != -1:
                return temp[cur_ind][count_a][count_l]
            with_a_next: int = check_all_records(cur_ind + 1, count_a + 1, 0) if count_a == 0 else 0
            with_l_next: int = 0 if count_l == 2 else check_all_records(cur_ind + 1, count_a, count_l + 1)
            with_p_next: int = check_all_records(cur_ind + 1, count_a, 0)
            total: int = (with_a_next + with_l_next + with_p_next) % MOD

            temp[cur_ind][count_a][count_l] = total
            return total

        return check_all_records(0, 0, 0)

1.246 - 2024-05-25 19:59:58 +0000 UTC

Word Break II

Code

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> List[str]:
        wordSet = set(wordDict)
        @cache
        def helper(t):
            combos = []
            if not t:
                return [""]
            for i, _ in enumerate(t):
                w = t[:i+1] 
                if w in wordSet:
                    combos.extend([
                        f'{w} {sentence}' if sentence else w 
                        for sentence in helper(t[i+1:])
                    ])
            return combos
        return helper(s)

1.247 - 2024-05-21 18:02:08 +0000 UTC

Subsets

Code

class Solution:
    def subsets(self, nums: List[int]) -> List[List[int]]:
        def backtrack(start, path):
            result.append(path)
            for i in range(start, len(nums)):
                backtrack(i + 1, path + [nums[i]])

        result = []
        backtrack(0, [])
        return result

1.248 - 2024-05-20 10:28:49 +0000 UTC

Sum of All Subset XOR Totals

Code

class Solution:
    def subsetXORSum(self, nums: List[int]) -> int:
        return reduce(operator.or_, nums) * 1 << (len(nums) - 1)
        

1.249 - 2024-05-19 12:08:43 +0000 UTC

Find the Maximum Sum of Node Values

Code

class Solution:
    def maximumValueSum(self, nums: list[int], k: int, edges: list[list[int]]) -> int:
        n: int = len(nums)
        temp: list[list[int]] = [[-1 for _ in range(2)] for _ in range(n)]  # temp[current_index(node)][is_even]

        def calculate_max(cur_ind, is_even) -> int:  # cur_ind -> cur_index of the tree and is_even represents whether we have already changed (XOR) even or odd number of nodes 
            if cur_ind == n:  # if we go to node which doesn't exist
                return 0 if is_even else -float("inf")
            if temp[cur_ind][is_even] != -1:  # if we've already encountered this state
                return temp[cur_ind][is_even]

            # checking all possible variants (no XOR or XOR)
            no_xor = nums[cur_ind] + calculate_max(cur_ind + 1, is_even)  # we don't change the number of XOR nodes
            with_xor = (nums[cur_ind] ^ k) + calculate_max(cur_ind + 1, not is_even)  # we added 1 XORed node

            mx_possible = max(no_xor, with_xor)
            temp[cur_ind][is_even] = mx_possible
            return mx_possible

        return calculate_max(0, 1)  # is_even == 1 because we have XORed 0 nodes which is even

1.250 - 2024-05-18 17:24:14 +0000 UTC

Distribute Coins in Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def distributeCoins(self, root: Optional[TreeNode]) -> int:
        #move coins to parent DFS
        def f(root, parent):
            if root==None: return 0
            moves=f(root.left, root)+f(root.right, root)
            x=root.val-1
            if parent!=None: parent.val+=x
            moves+=abs(x)
            return moves
        return f(root, None)

1.251 - 2024-05-17 18:25:39 +0000 UTC

Delete Leaves With a Given Value

Code

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right

class Solution(object):
    def removeLeafNodes(self, root, target):
        """
        :type root: TreeNode
        :type target: int
        :rtype: TreeNode
        """
        if not root:
            return None
        root.left = self.removeLeafNodes(root.left, target)
        root.right = self.removeLeafNodes(root.right, target)
        if not root.left and not root.right and root.val == target:
            return None
        return root

1.252 - 2024-05-16 15:11:33 +0000 UTC

Evaluate Boolean Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def helper(self, root):
        if root.val == 0 or root.val == 1:
            return root.val == 1
        elif root.val == 2:
            return self.helper(root.left) or self.helper(root.right)
        elif root.val == 3:
            return self.helper(root.left) and self.helper(root.right)
        return False
        
    def evaluateTree(self, root: Optional[TreeNode]) -> bool:
        return self.helper(root)

1.253 - 2024-05-14 09:06:07 +0000 UTC

Path with Maximum Gold

Code

class Solution:
    roww = [1, -1, 0, 0]
    coll = [0, 0, -1, 1]

    def dfs(self, grid, x, y, n, m):
        if x < 0 or x >= n or y < 0 or y >= m or grid[x][y] == 0:
            return 0
        
        curr = grid[x][y]
        grid[x][y] = 0
        localMaxGold = curr

        for i in range(4):
            newX = x + self.roww[i]
            newY = y + self.coll[i]
            localMaxGold = max(localMaxGold, curr + self.dfs(grid, newX, newY, n, m))

        grid[x][y] = curr
        return localMaxGold

    def getMaximumGold(self, grid):
        n = len(grid)
        m = len(grid[0])
        maxGold = 0

        for i in range(n):
            for j in range(m):
                if grid[i][j] != 0:
                    maxGold = max(maxGold, self.dfs(grid, i, j, n, m))

        return maxGold

1.254 - 2024-05-13 07:22:15 +0000 UTC

Score After Flipping Matrix

Code

class Solution:
    def matrixScore(self, grid: List[List[int]]) -> int:
        n, m = len(grid), len(grid[0])
        res = (1 << (m - 1)) * n

        for j in range(1, m):
            val = 1 << (m - 1 - j)
            set_count = 0

            for i in range(n):
                if grid[i][j] == grid[i][0]:
                    set_count += 1

            res += max(set_count, n - set_count) * val

        return res

1.255 - 2024-05-12 18:39:08 +0000 UTC

Largest Local Values in a Matrix

Code

class Solution:
    def largestLocal(self, grid: List[List[int]]) -> List[List[int]]:
        n, res = len(grid), []

        for i in range(1, n - 1):
            temp_row = []
            for j in range(1, n - 1):
                temp = 0

                for k in range(i - 1, i + 2):
                    for l in range(j - 1, j + 2):
                        temp = max(temp, grid[k][l])

                temp_row.append(temp)
            res.append(temp_row)

        return res

1.256 - 2024-05-08 07:50:28 +0000 UTC

Relative Ranks

Code

import heapq

class Solution:
    def findRelativeRanks(self, score: List[int]) -> List[str]:
        heap = []
        length = len(score)
        scores = [0] * length
        for i in range(length):
            scores[i] = (score[i], i)
        scores.sort(reverse=True)
        ranks = {0: "Gold Medal", 1: "Silver Medal", 2: "Bronze Medal"}
        for i in range(length):
            _, idx = scores[i]
            score[idx] = ranks.get(i, str(i + 1))
        return score

1.257 - 2024-05-08 07:39:08 +0000 UTC

Relative Ranks

Code

import heapq

class Solution:
    def findRelativeRanks(self, score: List[int]) -> List[str]:
        heap = []
        for i, athlete_score in enumerate(score):
            heapq.heappush(heap, (-athlete_score, i))
        i = 0
        ranks = {0: "Gold Medal", 1: "Silver Medal", 2: "Bronze Medal"}
        while heap:
            _, athlete = heapq.heappop(heap)
            rank = ranks.get(i, str(i + 1))
            score[athlete] = rank
            i += 1
        return score

1.258 - 2024-05-07 07:56:39 +0000 UTC

Double a Number Represented as a Linked List

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def doubleIt(self, head: Optional[ListNode]) -> Optional[ListNode]:
        def func(head):
            a=head.val*2
            if head.next:
                a+=func(head.next)
            head.val=a%10
            return a//10
        a=func(head)
        if a:
            return ListNode(a,head)
        return head
                

1.259 - 2024-05-06 13:47:26 +0000 UTC

Remove Nodes From Linked List

Code

class Solution:
    def removeNodes(self, head: Optional[ListNode]) -> Optional[ListNode]:
        cur = head
        stack = []
        while cur:
            while stack and stack[-1].val < cur.val:
                stack.pop()
            stack.append(cur)
            cur = cur.next
        
        nxt = None
        while stack:
            cur = stack.pop()
            cur.next = nxt
            nxt = cur
        
        return cur

1.260 - 2024-02-21 08:42:07 +0000 UTC

Bitwise AND of Numbers Range

Code

class Solution:
    def rangeBitwiseAnd(self, left: int, right: int) -> int:
        shift = 0
        while left != right:
            left >>= 1
            right >>= 1
            shift += 1
        return left << shift

1.261 - 2024-02-20 15:21:21 +0000 UTC

Missing Number

Code

import operator
class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        return reduce(
            operator.xor, 
            nums, 
            reduce(operator.xor, tuple(range(len(nums) + 1)), 0)
        )

1.262 - 2024-02-20 15:19:05 +0000 UTC

Missing Number

Code

import operator
class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        nums.extend(range(len(nums) + 1))
        return reduce(operator.xor, nums, 0)

1.263 - 2024-02-20 15:16:37 +0000 UTC

Missing Number

Code

import operator
class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        length = len(nums)
        return reduce(operator.xor, range(length), reduce(operator.xor, nums, length))

1.264 - 2024-02-20 12:10:36 +0000 UTC

Missing Number

Code

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        def xor(total: int, i: int) -> int:
            return total ^ nums[i] ^ (i + 1)
        return reduce(xor, chain((0, ), range(len(nums))))

1.265 - 2024-02-19 08:56:55 +0000 UTC

Power of Two

Code

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        return n > 0 and n & (n - 1) == 0

1.266 - 2024-02-18 09:45:46 +0000 UTC

Meeting Rooms III

Code

class Solution:
    def mostBooked(self, n: int, meetings: List[List[int]]) -> int:
        unused_rooms, used_rooms = list(range(n)), []
        heapify(unused_rooms)
        meeting_count = [0] * n
        for start, end in sorted(meetings):
            while used_rooms and used_rooms[0][0] <= start:
                _, room = heappop(used_rooms)
                heappush(unused_rooms, room)
            if unused_rooms:
                room = heappop(unused_rooms)
                heappush(used_rooms, [end, room])
            else:
                room_availability_time, room = heappop(used_rooms)
                heappush(
                    used_rooms,
                    [room_availability_time + end - start, room]
                )
            meeting_count[room] += 1
        return meeting_count.index(max(meeting_count))

1.267 - 2024-02-17 12:07:38 +0000 UTC

Furthest Building You Can Reach

Code

class Solution:
    def furthestBuilding(self, heights: List[int], bricks: int, ladders: int) -> int:
        heap = []
        i = 0
        length = len(heights)
        for i in range(length - 1):
            diff = heights[i + 1] - heights[i]           
            if diff <= 0:
                continue
            bricks -= diff
            heapq.heappush(heap, -diff)
            if bricks < 0:
                bricks += -heapq.heappop(heap)
                ladders -= 1
            if ladders < 0:
                return i
        return length - 1
  

1.268 - 2024-02-17 12:03:52 +0000 UTC

Furthest Building You Can Reach

Code

class Solution:
   def furthestBuilding(self, h: List[int], b: int, l: int) -> int:
       p = []
       
       i = 0
       for i in range(len(h) - 1):
           diff = h[i + 1] - h[i]
           
           if diff <= 0:
               continue
           
           b -= diff
           x = heapq.heappush(p, -diff)
           print(x)
           if b < 0:
               b += -heapq.heappop(p)
               l -= 1
               
           if l < 0:
               return i
       return len(h)-1
  

1.269 - 2024-02-16 15:29:09 +0000 UTC

Least Number of Unique Integers after K Removals

Code

class Solution:
    def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:
        counter = defaultdict(int)
        for num in arr:
            counter[num] += 1
        nums = [(count, num) for num, count in counter.items()]
        nums.sort()
        removed = 0
        for count, num in nums:
            if k < count:
                break
            k -= count
            removed += 1
        return len(counter) - removed

1.270 - 2024-02-15 09:51:25 +0000 UTC

Find Polygon With the Largest Perimeter

Code

class Solution:
    def largestPerimeter(self, nums: List[int]) -> int:
        nums.sort()
        previous_elements_sum = 0
        ans = -1
        for num in nums:
            if num < previous_elements_sum:
                ans = num + previous_elements_sum
            previous_elements_sum += num
        return ans

1.271 - 2024-02-14 07:48:17 +0000 UTC

Rearrange Array Elements by Sign

Code

class Solution:
    def rearrangeArray(self, nums: List[int]) -> List[int]:
        res = []
        pos, neg = [], []
        length = len(nums)
        for i in range(length):
            num = nums[i]
            if num > 0:
                pos.append(num)
            else:
                neg.append(num)
        pos.reverse()
        neg.reverse()
        while pos and neg:
            res.extend((pos.pop(), neg.pop()))
        return res

1.272 - 2024-02-13 13:10:55 +0000 UTC

Find First Palindromic String in the Array

Code

class Solution:
    def firstPalindrome(self, words: List[str]) -> str:
        for s in words:
            for i in range(len(s) // 2):
                if s[i] != s[-i - 1]:
                    break
            else:
                return s
        return ""

1.273 - 2024-02-12 09:50:44 +0000 UTC

Majority Element

Code

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        counter = defaultdict(int)
        half = len(nums) // 2
        for num in nums:
            counter[num] += 1
            if counter[num] > half:
                return num
        raise Exception()

1.274 - 2024-02-11 13:20:27 +0000 UTC

Cherry Pickup II

Code

class Solution:
    def cherryPickup(self, grid: List[List[int]]) -> int:
        n = len(grid)
        m = len(grid[0])

        # Create 3D DP table with initial values of 0
        dp = [[[0] * m for _ in range(m)] for _ in range(n)]

        # Set the starting point value (top-left and top-right corner)
        cherries = 0
        dp[0][0][m - 1] = grid[0][0] + grid[0][m - 1]

        # Iterate through each row from second onwards
        for i in range(1, n):
            # Iterate through each column for robot 1
            for j in range(m):
                # Iterate through each column for robot 2
                for k in range(m):
                    # Skip invalid states:
                    # - Both robots in the same row (j > i)
                    # - Robot 2 left of robot 1 (k < m - i - 1)
                    # - Robot 1 further right than robot 2 (j > k)
                    if j > i or k < m - i - 1 or j > k:
                        continue
                    # Base case: no moves possible, use previous state
                    dp[i][j][k] = dp[i - 1][j][k]
                    # Explore moves for robot 1:
                    # - Up-diagonal with robot 2 at same position
                    if j - 1 >= 0:
                        dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j - 1][k])
                    # - Up-diagonal with robot 2 one step left/right
                    if j - 1 >= 0 and k - 1 >= 0:
                        dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j - 1][k - 1])
                    if j - 1 >= 0 and k + 1 < m:
                        dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j - 1][k + 1])
                    # Explore moves for robot 2:
                    # - Up-diagonal with robot 1 at same position
                    if j + 1 < m:
                        dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j + 1][k])
                    # - Up-diagonal with robot 1 one step left/right
                    if j + 1 < m and k - 1 >= 0:
                        dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j + 1][k - 1])
                    if j + 1 < m and k + 1 < m:
                        dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j + 1][k + 1])
                    # Explore horizontal moves for both robots:
                    # - Both robots move left
                    if k - 1 >= 0:
                        dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j][k - 1])
                    # - Both robots move right
                    if k + 1 < m:
                        dp[i][j][k] = max(dp[i][j][k], dp[i - 1][j][k + 1])
                    # Add cherries only if robots are in different positions
                    if j != k:
                        dp[i][j][k] += grid[i][j] + grid[i][k]
                    else:
                        dp[i][j][k] += grid[i][j]  # Only one robot picks if they land in the same cell
                    # Update maximum cherries collected so far
                    cherries = max(cherries, dp[i][j][k])

        return cherries

1.275 - 2024-02-10 12:12:54 +0000 UTC

Palindromic Substrings

Code

class Solution:
    def countSubstrings(self, s: str) -> int:
        n = len(s)
        palindrome = [[False] * n for _ in range(n)]
        ans = 0

        for i in range(n):
            palindrome[i][i] = True
            ans += 1

        for i in range(n - 1):
            if s[i] == s[i + 1]:
                palindrome[i][i + 1] = True
                ans += 1

        for length in range(3, n + 1):
            for i in range(n - length + 1):
                if s[i] == s[i + length - 1] and palindrome[i + 1][i + length - 2]:
                    palindrome[i][i + length - 1] = True
                    ans += 1

        return ans

1.276 - 2024-02-09 16:12:32 +0000 UTC

Largest Divisible Subset

Code

class Solution:
    def largestDivisibleSubset(self, nums: List[int]) -> List[int]:
        nums.sort()
        n = len(nums)
        dp = [1] * n
        max_size, max_index = 1, 0

        for i in range(1, n):
            for j in range(i):
                if nums[i] % nums[j] == 0:
                    dp[i] = max(dp[i], dp[j] + 1)
                    if dp[i] > max_size:
                        max_size = dp[i]
                        max_index = i

        result = []
        num = nums[max_index]
        for i in range(max_index, -1, -1):
            if num % nums[i] == 0 and dp[i] == max_size:
                result.append(nums[i])
                num = nums[i]
                max_size -= 1

        return result

1.277 - 2024-02-08 12:50:03 +0000 UTC

Perfect Squares

Code

class Solution:
    def numSquares(self, n: int) -> int:
        dp = [float('inf')] * (n + 1)
        dp[0] = 0
        for i in range(1, n + 1):
            min_val = float('inf')
            j = 1
            while j * j <= i:
                min_val = min(min_val, dp[i - j * j] + 1)
                j += 1
            dp[i] = min_val
        return dp[n]

1.278 - 2024-02-07 07:59:44 +0000 UTC

Sort Characters By Frequency

Code

class Solution:
    def frequencySort(self, s: str) -> str:
        counter = defaultdict(int)
        for char in s:
            counter[char] += 1
        pq = [(-freq, char) for char, freq in counter.items()]
        heapq.heapify(pq)
        result = []
        while pq:
            freq, char = heapq.heappop(pq)
            result.append(char * -freq)
        return "".join(result)

1.279 - 2024-02-07 07:54:21 +0000 UTC

Sort Characters By Frequency

Code

class Solution:
    def frequencySort(self, s: str) -> str:
        counter = {}
        for char in s:
            if char not in counter:
                counter[char] = -ord(char)
            counter[char] -= 100
        return "".join(sorted(s, key=lambda val: counter[val]))

1.280 - 2024-02-07 07:52:55 +0000 UTC

Sort Characters By Frequency

Code

class Solution:
    def frequencySort(self, s: str) -> str:
        counter = {}
        for char in s:
            if char not in counter:
                counter[char] = ord(char)
            counter[char] += 100
        return "".join(sorted(s, key=lambda val: -counter[val]))

1.281 - 2024-02-07 07:49:08 +0000 UTC

Sort Characters By Frequency

Code

class Solution:
    def frequencySort(self, s: str) -> str:
        counter = defaultdict(int)
        for char in s:
            counter[char] += 1
        return "".join(sorted(s, key=lambda val: -(ord(val) + counter[val] * 100)))

1.282 - 2024-02-06 06:02:52 +0000 UTC

Group Anagrams

Code

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        anagrams = defaultdict(list)
        for anagram in strs:
            anagrams[tuple(sorted(anagram))].append(anagram)
        return anagrams.values()

1.283 - 2024-02-05 07:12:58 +0000 UTC

First Unique Character in a String

Code

class Solution:
    def firstUniqChar(self, s: str) -> int:
        counter = [0] * 26

        for char in s:
            idx = ord(char) - ord('a')
            if counter[idx] in (0, 1):
                counter[idx] += 1
        for i in range(len(s)):
            if counter[ord(s[i]) - ord('a')] == 1:
                return i
        return -1

1.284 - 2024-02-04 12:38:07 +0000 UTC

Partition Array for Maximum Sum

Code

class Solution:
    def maxSumAfterPartitioning(self, arr: List[int], k: int) -> int:
        min_num = -1
        length = len(arr)
        last_idx = length - 1
        cache = [-1] * length

        def dp(start: int) -> int:
            cached = cache[start]
            if cached != -1:
                return cached
            max_num = min_num
            max_sum = 0
            for i in range(start, min(start + k, length)):
                max_num = max(max_num, arr[i])
                cur_sum = max_num * (i - start + 1)
                if i != last_idx:
                    cur_sum += dp(i + 1)
                max_sum = max(max_sum, cur_sum)
            cache[start] = max_sum
            return max_sum
        
        return dp(0)
            

1.285 - 2024-02-04 12:17:08 +0000 UTC

Minimum Window Substring

Code

class Solution:
    def minWindow(self, s: str, t: str) -> str:
        if not s or not t:
            return ""

        dictT = defaultdict(int)
        for c in t:
            dictT[c] += 1

        required = len(dictT)
        l, r = 0, 0
        formed = 0

        windowCounts = defaultdict(int)
        ans = [-1, 0, 0]

        while r < len(s):
            c = s[r]
            windowCounts[c] += 1

            if c in dictT and windowCounts[c] == dictT[c]:
                formed += 1

            while l <= r and formed == required:
                c = s[l]

                if ans[0] == -1 or r - l + 1 < ans[0]:
                    ans[0] = r - l + 1
                    ans[1] = l
                    ans[2] = r

                windowCounts[c] -= 1
                if c in dictT and windowCounts[c] < dictT[c]:
                    formed -= 1

                l += 1

            r += 1

        return "" if ans[0] == -1 else s[ans[1]:ans[2] + 1]

1.286 - 2024-02-02 16:53:06 +0000 UTC

Divide Array Into Arrays With Max Difference

Code

class Solution:
    def divideArray(self, nums, k):
        size = len(nums)
        if size % 3 != 0:
            return []

        nums.sort()

        result = []
        group_index = 0
        for i in range(0, size, 3):
            if i + 2 < size and nums[i + 2] - nums[i] <= k:
                result.append([nums[i], nums[i + 1], nums[i + 2]])
                group_index += 1
            else:
                return []
        return result

1.287 - 2024-02-02 16:52:11 +0000 UTC

Divide Array Into Arrays With Max Difference

Code

class Solution:
    def divideArray(self, nums, k):
        size = len(nums)
        if size % 3 != 0:
            return []

        nums.sort()

        result = []
        group_index = 0
        for i in range(0, size, 3):
            if i + 2 < size and nums[i + 2] - nums[i] <= k:
                result.append([nums[i], nums[i + 1], nums[i + 2]])
                group_index += 1
            else:
                return []
        return result

1.288 - 2024-02-02 16:51:07 +0000 UTC

Sequential Digits

Code

class Solution:
    def sequentialDigits(self, low, high):
        a = []

        for i in range(1, 10):
            num = i
            next_digit = i + 1

            while num <= high and next_digit <= 9:
                num = num * 10 + next_digit
                if low <= num <= high:
                    a.append(num)
                next_digit += 1

        a.sort()
        return a

1.289 - 2024-01-31 08:09:51 +0000 UTC

Daily Temperatures

Code

class Solution:
    def dailyTemperatures(self, temperatures: List[int]) -> List[int]:
        temps_left = defaultdict(list)
        to_pop = []
        length = len(temperatures)
        ans = [0] * length
        for i in range(length):
            temp = temperatures[i]
            for temp_left, ids in temps_left.items():
                if temp <= temp_left:
                    continue
                for id in ids:
                    ans[id] = i - id
                to_pop.append(temp_left)
            temps_left[temp].append(i)
            for temp in to_pop:
                temps_left.pop(temp)
            to_pop.clear()
        
        return ans

1.290 - 2024-01-30 12:36:53 +0000 UTC

Evaluate Reverse Polish Notation

Code

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack: list[int] = []
        for token in tokens:
            match token:
                case "+":
                    stack.append(stack.pop() + stack.pop())
                case "-":
                    last, prev = stack.pop(), stack.pop()
                    stack.append(prev - last)
                case "*":
                    stack.append(stack.pop() * stack.pop())
                case "/": 
                    last, prev = stack.pop(), stack.pop()
                    stack.append(int(prev / last))
                case _:
                    stack.append(int(token))
        return stack[0]

1.291 - 2024-01-29 06:44:33 +0000 UTC

Implement Queue using Stacks

Code

class MyQueue:

    def __init__(self):
        self.stack_in = []
        self.stack_out = []

    def push(self, x: int) -> None:
        self.stack_in.append(x)

    def pop(self) -> int:
        self.peek()
        return self.stack_out.pop()

    def peek(self) -> int:
        if self.stack_out:
            return self.stack_out[-1]
        
        while self.stack_in:
            self.stack_out.append(self.stack_in.pop())

        return self.stack_out[-1]

    def empty(self) -> bool:
        return not self.stack_out and not self.stack_in


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

1.292 - 2024-01-28 10:34:03 +0000 UTC

Number of Submatrices That Sum to Target

Code

class Solution:
    def numSubmatrixSumTarget(self, matrix, target):
        m, n = len(matrix), len(matrix[0])

        for row in range(m):
            for col in range(1, n):
                matrix[row][col] += matrix[row][col - 1]

        count = 0

        for c1 in range(n):
            for c2 in range(c1, n):
                prefix_sum_count = {0: 1}
                sum_val = 0

                for row in range(m):
                    sum_val += matrix[row][c2] - (matrix[row][c1 - 1] if c1 > 0 else 0)
                    count += prefix_sum_count.get(sum_val - target, 0)
                    prefix_sum_count[sum_val] = prefix_sum_count.get(sum_val, 0) + 1

        return count

1.293 - 2024-01-27 07:05:52 +0000 UTC

K Inverse Pairs Array

Code

class Solution:
    def kInversePairs(self, n: int, k: int) -> int:
        MOD = 10**9 + 7
        dp = [[0] * (k + 1) for _ in range(n + 1)]

        for i in range(1, n + 1):
            for j in range(k + 1):
                if j == 0:
                    dp[i][j] = 1
                else:
                    val = (dp[i - 1][j] + MOD - (dp[i - 1][j - i] if j - i >= 0 else 0)) % MOD
                    dp[i][j] = (dp[i][j - 1] + val) % MOD

        return (dp[n][k] + MOD - (dp[n][k - 1] if k > 0 else 0)) % MOD

1.294 - 2024-01-26 08:02:15 +0000 UTC

Out of Boundary Paths

Code

class Solution:

    def findPaths(self, m: int, n: int, N: int, x: int, y: int) -> int:

        M = 1000000000 + 7

        dp = [[0] * n for _ in range(m)]

        dp[x][y] = 1

        count = 0



        for moves in range(1, N + 1):

            temp = [[0] * n for _ in range(m)]



            for i in range(m):

                for j in range(n):

                    if i == m - 1:

                        count = (count + dp[i][j]) % M

                    if j == n - 1:

                        count = (count + dp[i][j]) % M

                    if i == 0:

                        count = (count + dp[i][j]) % M

                    if j == 0:

                        count = (count + dp[i][j]) % M

                    temp[i][j] = (

                        ((dp[i - 1][j] if i > 0 else 0) + (dp[i + 1][j] if i < m - 1 else 0)) % M +

                        ((dp[i][j - 1] if j > 0 else 0) + (dp[i][j + 1] if j < n - 1 else 0)) % M

                    ) % M



            dp = temp



        return count

1.295 - 2024-01-25 14:31:23 +0000 UTC

Longest Common Subsequence

Code

class Solution:
    def longestCommonSubsequence(self, text1: str, text2: str) -> int:
        # Get the lengths of both input strings
        len_text1, len_text2 = len(text1), len(text2)
      
        # Initialize a 2D array (list of lists) with zeros for dynamic programming
        # The array has (len_text1 + 1) rows and (len_text2 + 1) columns
        dp_matrix = [[0] * (len_text2 + 1) for _ in range(len_text1 + 1)]
      
        # Loop through each character index of text1 and text2
        for i in range(1, len_text1 + 1):
            for j in range(1, len_text2 + 1):
                # If the characters match, take the diagonal value and add 1
                if text1[i - 1] == text2[j - 1]:
                    dp_matrix[i][j] = dp_matrix[i - 1][j - 1] + 1
                else:
                    # If the characters do not match, take the maximum of the value from the left and above
                    dp_matrix[i][j] = max(dp_matrix[i - 1][j], dp_matrix[i][j - 1])
      
        # The bottom-right value in the matrix contains the length of the longest common subsequence
        return dp_matrix[len_text1][len_text2]

1.296 - 2024-01-24 07:39:27 +0000 UTC

Pseudo-Palindromic Paths in a Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        
        num_count = defaultdict(int)
        perm_count = 0

        def traverse(node: TreeNode) -> int:
            val, left, right = node.val, node.left, node.right
            num_count[val] += 1
            res = 0
            if not left and not right:
                non_even = 0
                for num in num_count.values():
                    if num % 2 == 0:
                        continue
                    if non_even == 1:
                        break
                    non_even += 1
                else:
                    res += 1
            if left:
                res += traverse(left)
            if right: 
                res += traverse(right)
            num_count[val] = max(0, num_count[val] - 1)
            return res 

        return traverse(root)

1.297 - 2024-01-24 07:27:08 +0000 UTC

Pseudo-Palindromic Paths in a Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def pseudoPalindromicPaths (self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        
        num_count = defaultdict(int)
        perm_count = 0

        def traverse(node: TreeNode) -> int:
            if not node:
                return 0
            val, left, right = node.val, node.left, node.right
            num_count[val] += 1
            res = 0
            if not left and not right:
                non_even = 0
                for num in num_count.values():
                    if num % 2 == 0:
                        continue
                    non_even += 1
                    if non_even > 1:
                        break
                else:
                    res += 1
            res += traverse(left) + traverse(right)
            num_count[val] = max(0, num_count[val] - 1)
            return res 

        return traverse(root)

1.298 - 2024-01-23 07:54:38 +0000 UTC

Maximum Length of a Concatenated String with Unique Characters

Code

class Solution:
    def maxLength(self, arr: List[str]) -> int:
        cur = set()
        length = len(arr)
        max_length = 0

        def backtrack(start: int) -> None:
            nonlocal max_length 
            
            for i in range(start, length):
                new_subs = arr[i]
                new = set(new_subs)
                if len(new_subs) != len(new) or len(cur.intersection(new)) != 0:
                    continue
                cur.update(new)
                backtrack(i + 1)
                cur.difference_update(new)

            max_length = max(max_length, len(cur))

        backtrack(0)

        return max_length

1.299 - 2024-01-22 09:39:06 +0000 UTC

Set Mismatch

Code

class Solution:
    def findErrorNums(self, nums: List[int]) -> List[int]:
        length = len(nums)
        # dupl_xor_miss = duplicate ^ missing
        dupl_xor_miss = reduce(lambda total, i: total ^ i ^ nums[i - 1], range(length + 1))
        rightmost_set_bit = dupl_xor_miss & -dupl_xor_miss
        xor_group1 = xor_group2 = 0
        for i in range(1, length + 1):
            if i & rightmost_set_bit:
                xor_group1 ^= i
            else:
                xor_group2 ^= i
            if nums[i - 1] & rightmost_set_bit:
                xor_group1 ^= nums[i - 1]
            else:
                xor_group2 ^= nums[i - 1]
        for num in nums:
            if num == xor_group1:
                return num, xor_group2
            if num == xor_group2:
                return num, xor_group1 
        
        raise Exception()

1.300 - 2024-01-21 18:12:22 +0000 UTC

House Robber

Code

class Solution:
    def rob(self, nums: List[int]) -> int:
        length = len(nums)
        cache = {}

        def dp(i: int) -> int:
            if i >= length:
                return 0
            val = nums[i]
            if i in cache:
                return cache[i]
            res = max(dp(i + 1), val + dp(i + 2))
            cache[i] = res
            return res 

        return dp(0)

1.301 - 2024-01-20 14:21:44 +0000 UTC

Sum of Subarray Minimums

Code

class Solution:
    def sumSubarrayMins(self, arr: List[int]) -> int:
        n = len(arr)
        left = [-1] * n 
        right = [n] * n
        stack = []

        for i, value in enumerate(arr):
            while stack and arr[stack[-1]] >= value:  
                stack.pop()  
            if stack:
                left[i] = stack[-1]  
            stack.append(i) 

        stack = [] 

        
        for i in range(n - 1, -1, -1):  
            while stack and arr[stack[-1]] > arr[i]: 
                stack.pop()  
            if stack:
                right[i] = stack[-1]  
            stack.append(i) 

        mod = 10**9 + 7 

        result = sum((i - left[i]) * (right[i] - i) * value for i, value in enumerate(arr)) % mod
      
        return result 

1.302 - 2024-01-19 08:46:22 +0000 UTC

Minimum Falling Path Sum

Code

class Solution:
    def minFallingPathSum(self, matrix: List[List[int]]) -> int:
        length = len(matrix)
        cache = {}
        deltas = ((1, 0), (1, 1), (1, -1))
        last_row = length - 1

        def dp(row: int, col: int) -> int:
            if (row, col) in cache:
                return cache[(row, col)]
            val = matrix[row][col]
            if row == last_row:
                return val
            min_cost = None
            for delta_row, delta_col in deltas:
                new_row, new_col = row + delta_row, col + delta_col
                if new_col == length or new_col == -1:
                    continue
                cost = dp(new_row, new_col)
                min_cost = cost if min_cost is None else min(min_cost, cost)
            res = val + min_cost
            cache[(row, col)] = res
            return res

        return min(dp(0, col) for col in range(length))

1.303 - 2024-01-19 08:45:33 +0000 UTC

Minimum Falling Path Sum

Code

class Solution:
    def minFallingPathSum(self, matrix: List[List[int]]) -> int:
        length = len(matrix)
        max_val = 101 * length * length
        cache = {}
        deltas = ((1, 0), (1, 1), (1, -1))
        last_row = length - 1

        def dp(row: int, col: int) -> int:
            if (row, col) in cache:
                return cache[(row, col)]
            val = matrix[row][col]
            if row == last_row:
                return val
            min_cost = max_val
            for delta_row, delta_col in deltas:
                new_row, new_col = row + delta_row, col + delta_col
                if new_col == length or new_col == -1:
                    continue
                cost = dp(new_row, new_col)
                min_cost = min(min_cost, cost)
            res = val + min_cost
            cache[(row, col)] = res
            return res

        return min(dp(0, col) for col in range(length))

1.304 - 2024-01-18 10:27:10 +0000 UTC

Climbing Stairs

Code

class Solution:
    def climbStairs(self, n: int) -> int:
        prev, cur = 1, 2
        if n == prev:
            return prev
        if n == cur:
            return cur
        for i in range(2, n):
            new = prev + cur
            cur, prev = new, cur
        return cur

1.305 - 2024-01-17 16:14:04 +0000 UTC

Unique Number of Occurrences

Code

class Solution:
    def uniqueOccurrences(self, arr: List[int]) -> bool:
        counts = defaultdict(int)
        for num in arr:
            counts[num] += 1

        viewed = set()
        for _, count in counts.items():
            if count in viewed:
                return False
            viewed.add(count)
        return True

1.306 - 2024-01-16 08:04:01 +0000 UTC

Insert Delete GetRandom O(1)

Code

import random

class RandomizedSet:

    def __init__(self):
        self._nums_map = {}
        self._nums = []
        

    def insert(self, val: int) -> bool:
        if val in self._nums_map:
            return False
        self._nums_map[val] = len(self._nums)
        self._nums.append(val)
        return True

    def remove(self, val: int) -> bool:
        if val not in self._nums_map:
            return False
        last = self._nums[-1]
        idx = self._nums_map[val]
        self._nums_map[last] = idx
        self._nums[idx] = last
        self._nums.pop()
        self._nums_map.pop(val)
        return True
        
    def getRandom(self) -> int:
        return random.choice(self._nums) 


# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()

1.307 - 2024-01-15 08:45:13 +0000 UTC

Find Players With Zero or One Losses

Code

class Solution:
    def findWinners(self, matches):
        losses = [0] * 100001

        for winner, loser in matches:
            if losses[winner] == 0:
                losses[winner] = -1

            if losses[loser] == -1:
                losses[loser] = 1
            else:
                losses[loser] += 1

        zero_loss = [i for i in range(1, 100001) if losses[i] == -1]
        one_loss = [i for i in range(1, 100001) if losses[i] == 1]

        return [zero_loss, one_loss]

1.308 - 2024-01-14 14:27:29 +0000 UTC

Determine if Two Strings Are Close

Code


class Solution:
    def closeStrings(self, word1: str, word2: str) -> bool:
        freq1 = [0] * 26
        freq2 = [0] * 26

        for ch in word1:
            freq1[ord(ch) - ord('a')] += 1

        for ch in word2:
            freq2[ord(ch) - ord('a')] += 1

        for i in range(26):
            if (freq1[i] == 0 and freq2[i] != 0) or (freq1[i] != 0 and freq2[i] == 0):
                return False

        freq1.sort()
        freq2.sort()

        for i in range(26):
            if freq1[i] != freq2[i]:
                return False

        return True

1.309 - 2024-01-13 14:33:48 +0000 UTC

Minimum Number of Steps to Make Two Strings Anagram

Code

class Solution:
    def minSteps(self, s: str, t: str) -> int:
        count_s = [0] * 26
        count_t = [0] * 26

        for char in s:
            count_s[ord(char) - ord('a')] += 1

        for char in t:
            count_t[ord(char) - ord('a')] += 1

        steps = 0
        for i in range(26):
            steps += abs(count_s[i] - count_t[i])

        return steps // 2

1.310 - 2024-01-12 20:55:40 +0000 UTC

Determine if String Halves Are Alike

Code

class Solution:
    def halvesAreAlike(self, s: str) -> bool:
        def count_vowels(string):
            vowels = set('aeiouAEIOU')
            return sum(1 for char in string if char in vowels)

        length = len(s)
        mid_point = length // 2

        first_half = s[:mid_point]
        second_half = s[mid_point:]

        return count_vowels(first_half) == count_vowels(second_half)

1.311 - 2024-01-11 09:15:51 +0000 UTC

Maximum Difference Between Node and Ancestor

Code

# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
    def maxAncestorDiff(self, root):
        if not root:
            return 0
        self.diff = 0
        self.helper(root, root.val, root.val)
        return self.diff
    
    def helper(self, root, min_val, max_val):
        if not root:
            return
        self.diff = max(self.diff, max(abs(min_val - root.val), abs(max_val - root.val)))
        min_val = min(min_val, root.val)
        max_val = max(max_val, root.val)
        self.helper(root.left, min_val, max_val)
        self.helper(root.right, min_val, max_val)
        

1.312 - 2024-01-10 08:34:26 +0000 UTC

Amount of Time for Binary Tree to Be Infected

Code

class Solution:
    def amountOfTime(self, root: Optional[TreeNode], start: int) -> int:
        def dfs(node):
            if node is None:
                return
            if node.left:
                graph[node.val].append(node.left.val)
                graph[node.left.val].append(node.val)
            if node.right:
                graph[node.val].append(node.right.val)
                graph[node.right.val].append(node.val)
            dfs(node.left)
            dfs(node.right)

        graph = defaultdict(list)
        dfs(root)
        visited = set()
        queue = deque([start])
        time = -1
        while queue:
            time += 1
            for _ in range(len(queue)):
                current_node = queue.popleft()
                visited.add(current_node)
                for neighbor in graph[current_node]:
                    if neighbor not in visited:
                        queue.append(neighbor)
        return time

1.313 - 2024-01-09 16:45:41 +0000 UTC

Leaf-Similar Trees

Code

class Solution:
    def leafSimilar(self, root1, root2):
        def dfs(node):
            if node:
                if not node.left and not node.right:
                    yield node.val
                yield from dfs(node.left)
                yield from dfs(node.right)

        return list(dfs(root1)) == list(dfs(root2))

1.314 - 2024-01-08 14:44:21 +0000 UTC

Range Sum of BST

Code

class Solution:
    def rangeSumBST(self, root: Optional[TreeNode], low: int, high: int) -> int:
        def dfs(node):
            if not node:
                return 0
            
            current_val = 0
            if low <= node.val <= high:
                current_val = node.val
            
            left_sum = dfs(node.left)
            right_sum = dfs(node.right)
            
            return current_val + left_sum + right_sum
        
        return dfs(root)

1.315 - 2024-01-07 09:26:09 +0000 UTC

Maximum Profit in Job Scheduling

Code

class Solution:
    def jobScheduling(self, startTime: List[int], endTime: List[int], profit: List[int]) -> int:
        jobs = sorted(zip(endTime, startTime, profit))
      
        number_of_jobs = len(profit)
      
        dp = [0] * (number_of_jobs + 1)
      
        for i, (current_end_time, current_start_time, current_profit) in enumerate(jobs):
            index = bisect_right(jobs, current_start_time, hi=i, key=lambda x: x[0])
            dp[i + 1] = max(dp[i], dp[index] + current_profit)
      
        return dp[number_of_jobs]

1.316 - 2024-01-07 09:23:04 +0000 UTC

Arithmetic Slices II - Subsequence

Code

class Solution:
    def numberOfArithmeticSlices(self, nums: List[int]) -> int:
        n = len(nums)
        total_count = 0  
        dp = [defaultdict(int) for _ in range(n)]

        for i in range(1, n):
            for j in range(i):
                diff = nums[i] - nums[j]
                dp[i][diff] += 1  
                if diff in dp[j]:
                    dp[i][diff] += dp[j][diff]
                    total_count += dp[j][diff]

        return total_count

1.317 - 2024-01-05 10:00:49 +0000 UTC

Longest Increasing Subsequence

Code

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

        n = len(nums)
        dp = [1] * n

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

        return max(dp)

1.318 - 2024-01-04 11:11:50 +0000 UTC

Minimum Number of Operations to Make Array Empty

Code

class Solution:
    def minOperations(self, nums: List[int]) -> int:
        counter = Counter(nums)
        ans = 0
        for c in counter.values():
            if c == 1: 
                return -1
            ans += ceil(c / 3)
        return ans

1.319 - 2024-01-03 11:46:50 +0000 UTC

Number of Laser Beams in a Bank

Code

class Solution:
    def numberOfBeams(self, bank):
        ans, temp = 0, 0
        for s in bank:
            n = s.count('1')
            if n == 0:
                continue
            ans += temp * n
            temp = n
        return ans

1.320 - 2024-01-02 12:20:19 +0000 UTC

Convert an Array Into a 2D Array With Conditions

Code

class Solution:
    def findMatrix(self, v: List[int]) -> List[List[int]]:
        um = {}
        for i in v:
            um[i] = um.get(i, 0) + 1
        
        ans = []
        while um:
            temp = []
            to_erase = []
            for f, s in um.items():
                temp.append(f)
                s -= 1
                if s == 0:
                    to_erase.append(f)
                um[f] = s
            ans.append(temp)
            for i in to_erase:
                del um[i]
        return ans

1.321 - 2024-01-01 13:10:42 +0000 UTC

Assign Cookies

Code

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort()
        s.sort()
        content_children = 0
        cookie_index = 0
        while cookie_index < len(s) and content_children < len(g):
            if s[cookie_index] >= g[content_children]:
                content_children += 1
            cookie_index += 1
        return content_children

1.322 - 2023-12-31 10:19:35 +0000 UTC

Largest Substring Between Two Equal Characters

Code

class Solution:
    def maxLengthBetweenEqualCharacters(self, s: str) -> int:
        ans = -1
        
        for left in range(len(s)):
            for right in range(left + 1, len(s)):
                if s[left] == s[right]:
                    ans = max(ans, right - left - 1)
        
        return ans

1.323 - 2023-12-30 11:22:38 +0000 UTC

Redistribute Characters to Make All Strings Equal

Code

class Solution:
    def makeEqual(self, words: List[str]) -> bool:
        counts = defaultdict(int)
        for word in words:
            for c in word:
                counts[c] += 1
        
        n = len(words)
        for val in counts.values():
            if val % n != 0:
                return False
        
        return True

1.324 - 2023-12-29 07:09:26 +0000 UTC

Minimum Difficulty of a Job Schedule

Code

class Solution:
    def minDifficulty(self, jobDifficulty, days):
        length = len(jobDifficulty)
        if days > length:
            return -1

        min_difficulties = [[float('inf')] * length for _ in range(days)]

        max_diff = 0
        i = 0
        while i <= length - days:
            max_diff = max(max_diff, jobDifficulty[i])
            min_difficulties[0][i] = max_diff
            i += 1

        current_day = 1
        while current_day < days:
            to = current_day
            while to <= length - days + current_day:
                current_job_difficulty = jobDifficulty[to]
                result = float('inf')
                j = to - 1
                while j >= current_day - 1:
                    result = min(result, min_difficulties[current_day - 1][j] + current_job_difficulty)
                    current_job_difficulty = max(current_job_difficulty, jobDifficulty[j])
                    j -= 1
                min_difficulties[current_day][to] = result
                to += 1
            current_day += 1

        return min_difficulties[days - 1][length - 1]

1.325 - 2023-12-28 07:12:36 +0000 UTC

String Compression II

Code

class Solution:
    def getLengthOfOptimalCompression(self, s: str, k: int) -> int:
        n = len(s)
        dp = [[9999] * 110 for _ in range(110)]
        dp[0][0] = 0

        for i in range(1, n + 1):
            for j in range(0, k + 1):
                cnt, del_ = 0, 0
                for l in range(i, 0, -1):
                    if s[l - 1] == s[i - 1]:
                        cnt += 1
                    else:
                        del_ += 1

                    if j - del_ >= 0:
                        dp[i][j] = min(dp[i][j], dp[l - 1][j - del_] + 1 + (3 if cnt >= 100 else 2 if cnt >= 10 else 1 if cnt >= 2 else 0))

                if j > 0:
                    dp[i][j] = min(dp[i][j], dp[i - 1][j - 1])

        return dp[n][k]

1.326 - 2023-12-27 08:51:17 +0000 UTC

Minimum Time to Make Rope Colorful

Code

class Solution:
    def minCost(self, colors: str, neededTime: List[int]) -> int:
        totalTime = 0
        i = 0
        j = 0

        while i < len(neededTime) and j < len(neededTime):
            currTotal = 0
            currMax = 0

            while j < len(neededTime) and colors[i] == colors[j]:
                currTotal += neededTime[j]
                currMax = max(currMax, neededTime[j])
                j += 1

            totalTime += currTotal - currMax
            i = j

        return totalTime

1.327 - 2023-12-26 08:08:25 +0000 UTC

Number of Dice Rolls With Target Sum

Code

class Solution:
    mod = 10 ** 9 + 7

    def numRollsToTarget(self, n: int, k: int, target: int) -> int:
        dp = [[-1] * (target + 1) for _ in range(n + 1)]
        return self.recursion(dp, n, k, target)

    def recursion(self, dp: list, n: int, k: int, target: int) -> int:
        if target == 0 and n == 0:
            return 1
        if n == 0 or target <= 0:
            return 0

        if dp[n][target] != -1:
            return dp[n][target] % self.mod

        ways = 0
        for i in range(1, k + 1):
            ways = (ways + self.recursion(dp, n - 1, k, target - i)) % self.mod

        dp[n][target] = ways % self.mod
        return dp[n][target]

1.328 - 2023-12-25 07:53:55 +0000 UTC

Decode Ways

Code

class Solution:
    def numDecodings(self, s):
        if s == "0":
            return 0
        
        # dp_0 = dp[i]
        # dp_1 = dp[i + 1]
        # dp_2 = dp[i + 2]
        dp_2 = 1
        dp_1 = int(s[-1] != "0")

        i = len(s) - 2
        while i >= 0:
            if s[i] == "0":
                dp_0 = 0
            else:
                dp_0 = dp_1
                if (s[i] == "1") or (s[i] == "2" and eval(s[i + 1]) < 7):
                    dp_0 += dp_2
            i -= 1
            dp_0, dp_1, dp_2 = 0, dp_0, dp_1
        
        return dp_1

1.329 - 2023-12-24 09:54:15 +0000 UTC

Minimum Changes To Make Alternating Binary String

Code

class Solution:
    def minOperations(self, s: str) -> int:
        start0 = 0
        start1 = 0
        
        for i in range(len(s)):
            if i % 2 == 0:
                if s[i] == "0":
                    start1 += 1
                else:
                    start0 += 1
            else:
                if s[i] == "1":
                    start1 += 1
                else:
                    start0 += 1
        
        return min(start0, start1)

1.330 - 2023-12-23 21:41:36 +0000 UTC

Path Crossing

Code

class Solution:
    def isPathCrossing(self, path: str) -> bool:
        moves = {
            "N": (0, 1),
            "S": (0, -1),
            "W": (-1, 0),
            "E": (1, 0)
        }
        
        visited = {(0, 0)}
        x = 0
        y = 0

        for c in path:
            dx, dy = moves[c]
            x += dx
            y += dy
            
            if (x, y) in visited:
                return True

            visited.add((x, y))
        
        return False

1.331 - 2023-12-22 08:52:14 +0000 UTC

Maximum Score After Splitting a String

Code

class Solution:
    def maxScore(self, s: str) -> int:
        ones = s.count("1")
        zeros = 0
        ans = 0 

        for i in range(len(s) - 1):
            if s[i] == "1":
                ones -= 1
            else:
                zeros += 1
        
            ans = max(ans, zeros + ones)
        
        return ans

1.332 - 2023-12-21 05:42:34 +0000 UTC

Widest Vertical Area Between Two Points Containing No Points

Code

class Solution:
    def maxWidthOfVerticalArea(self, points: List[List[int]]) -> int:
        points.sort(key=lambda x: x[0])

        max_width = 0

        for i in range(1, len(points)):
            width = points[i][0] - points[i-1][0]
            max_width = max(max_width, width)

        return max_width

1.333 - 2023-12-20 11:05:16 +0000 UTC

Buy Two Chocolates

Code

class Solution:
    def buyChoco(self, prices: List[int], money: int) -> int:
        # Assume the Minimum Cost to be Infinity
        min_cost = float('inf')

        # Number of Chocolates
        n = len(prices)

        # Check Every Pair of Chocolates
        for first_choco in range(n):
            for second_choco in range(first_choco + 1, n):
                # Sum of Prices of the Two Chocolates
                cost = prices[first_choco] + prices[second_choco]

                # If the Sum of Prices is Less than the Minimum Cost
                if cost < min_cost:
                    # Update the Minimum Cost
                    min_cost = cost
        
        # We can buy chocolates only if we have enough money
        if min_cost <= money:
            # Return the Amount of Money Left
            return money - min_cost
        else:
            # We cannot buy chocolates. Return the initial amount of money
            return money

1.334 - 2023-12-19 08:24:47 +0000 UTC

Image Smoother

Code

class Solution:
    def imageSmoother(self, img: List[List[int]]) -> List[List[int]]:
        # Save the dimensions of the image.
        m = len(img)
        n = len(img[0])

        # Create a new image of the same dimension as the input image.
        smooth_img = [[0] * n for _ in range(m)]

        # Iterate over the cells of the image.
        for i in range(m):
            for j in range(n):
                # Initialize the sum and count 
                sum = 0
                count = 0

                # Iterate over all plausible nine indices.
                for x in (i - 1, i, i + 1):
                    for y in (j - 1, j, j + 1):
                        # If the indices form valid neighbor
                        if 0 <= x < m and 0 <= y < n:
                            sum += img[x][y]
                            count += 1

                # Store the rounded down value in smooth_img[i][j].
                smooth_img[i][j] = sum // count
        
        # Return the smooth image.
        return smooth_img

1.335 - 2023-12-18 10:27:09 +0000 UTC

Maximum Product Difference Between Two Pairs

Code

class Solution:
    def maxProductDifference(self, nums: List[int]) -> int:
        nums.sort()
        return nums[-1] * nums[-2] - nums[0] * nums[1]

1.336 - 2023-12-17 09:09:37 +0000 UTC

Design a Food Rating System

Code

class Food:
    def __init__(self, food_rating, food_name):
        # Store the food's rating.
        self.food_rating = food_rating
        # Store the food's name.
        self.food_name = food_name

    def __lt__(self, other):
        # Overload the less than operator for comparison.
        # If food ratings are the same, sort based on their name (lexicographically smaller name food will be on top).
        if self.food_rating == other.food_rating:
            return self.food_name < other.food_name
        # Sort based on food rating (bigger rating food will be on top).
        return self.food_rating > other.food_rating

class FoodRatings:
    def __init__(self, foods: List[str], cuisines: List[str], ratings: List[int]):
        # Map food with its rating.
        self.food_rating_map = {}
        # Map food with the cuisine it belongs to.
        self.food_cuisine_map = {}
        # Store all food of a cuisine in a priority queue (to sort them on ratings/name).
        # Priority queue element -> Food: (food_rating, food_name)
        self.cuisine_food_map = defaultdict(list)

        for i in range(len(foods)):
            # Store 'rating' and 'cuisine' of the current 'food' in 'food_rating_map' and 'food_cuisine_map' maps.
            self.food_rating_map[foods[i]] = ratings[i]
            self.food_cuisine_map[foods[i]] = cuisines[i]
            # Insert the '(rating, name)' element into the current cuisine's priority queue.
            heapq.heappush(self.cuisine_food_map[cuisines[i]], Food(ratings[i], foods[i]))

    def changeRating(self, food: str, newRating: int) -> None:
        # Update food's rating in 'food_rating' map.
        self.food_rating_map[food] = newRating
        # Insert the '(new rating, name)' element in the respective cuisine's priority queue.
        cuisineName = self.food_cuisine_map[food]
        heapq.heappush(self.cuisine_food_map[cuisineName], Food(newRating, food))

    def highestRated(self, cuisine: str) -> str:
        # Get the highest rated 'food' of 'cuisine'.
        highest_rated = self.cuisine_food_map[cuisine][0]

        # If the latest rating of 'food' doesn't match with the 'rating' on which it was sorted in the priority queue,
        # then we discard this element from the priority queue.
        while self.food_rating_map[highest_rated.food_name] != highest_rated.food_rating:
            heapq.heappop(self.cuisine_food_map[cuisine])
            highest_rated = self.cuisine_food_map[cuisine][0]

        # Return the name of the highest-rated 'food' of 'cuisine'.
        return highest_rated.food_name

1.337 - 2023-12-16 10:01:55 +0000 UTC

Valid Anagram

Code

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        if (len(s) != len(t)):
            return False
            
        letters = [0] * 26
        for char in s:
            letters[ord(char) - ord('a')] += 1
        
        for char in t:
            i = ord(char) - ord('a')
            letters[i] -= 1
            if letters[i] < 0:
                return False

        return True

1.338 - 2023-12-15 07:56:18 +0000 UTC

Destination City

Code

class Solution:
    def destCity(self, paths: List[List[str]]) -> str:
        paths_from = set()
        for path_from, path_to in paths:
            paths_from.add(path_from)
        
        ans = ""
        for _, path_to in paths:
            if path_to not in paths_from:
                ans = path_to
                break
        
        return ans

1.339 - 2023-12-15 07:54:52 +0000 UTC

Destination City

Code

class Solution:
    def destCity(self, paths: List[List[str]]) -> str:
        paths_from, paths_to = set(), set()
        for path_from, path_to in paths:
            paths_from.add(path_from)
            paths_to.add(path_to)
        
        return (paths_to - paths_from).pop()

1.340 - 2023-12-14 09:30:55 +0000 UTC

Difference Between Ones and Zeros in Row and Column

Code

class Solution:
    def onesMinusZeros(self, grid: List[List[int]]) -> List[List[int]]:
        m = len(grid)
        n = len(grid[0])

        rows = {}
        for r in range(m):        
            row_sum = 0
            for c in range(n):
                row_sum += grid[r][c]
            
            rows[r] = row_sum

        cols = {}
        for c in range(n):
            col_sum = 0
            for r in range(m):
                col_sum += grid[r][c]
            
            cols[c] = col_sum

        res = [[0] * n for _ in range(m)]

        for r in range(m):
            for c in range(n):
                res[r][c] = rows[r] + cols[c] - (m - rows[r]) - (n - cols[c])
        
        return res

1.341 - 2023-12-13 08:11:00 +0000 UTC

Special Positions in a Binary Matrix

Code

class Solution:
    def numSpecial(self, mat: List[List[int]]) -> int:
        def get_column_sum(col_idx):
            return sum(row[col_idx] for row in mat)

        special = 0
        for row in mat:
            if sum(row) == 1:
                col_idx = row.index(1)
                special += get_column_sum(col_idx) == 1

        return special

1.342 - 2023-12-12 07:39:45 +0000 UTC

Maximum Product of Two Elements in an Array

Code

class Solution:
    def maxProduct(self, nums: List[int]) -> int:
        biggest = 0
        second_biggest = 0
        for num in nums:
            if num > biggest:
                second_biggest = biggest
                biggest = num
            else:
                second_biggest = max(second_biggest, num)
        
        return (biggest - 1) * (second_biggest - 1)

1.343 - 2023-12-11 12:30:35 +0000 UTC

Keyboard Row

Code

class Solution:
    def findWords(self, words: List[str]) -> List[str]:
        ans = []
        rows = [
            set("qwertyuiop"),
            set("asdfghjkl"), 
            set("zxcvbnm")
        ]
        for word in words:
            for row in rows:
                if len(row.union(word.lower())) == len(row):
                    ans.append(word)
                    break
        return ans

1.344 - 2023-12-11 07:26:55 +0000 UTC

Element Appearing More Than 25% In Sorted Array

Code

class Solution:
    def findSpecialInteger(self, arr: List[int]) -> int:
        prev, count = arr[0], 1
        quarter = len(arr) / 4
        for num in arr[1:]:
            if num == prev:
                count += 1
            else:
                prev = num
                count = 1
            if count > quarter:
                break
        return prev

1.345 - 2023-10-30 13:16:38 +0000 UTC

Find First and Last Position of Element in Sorted Array

Code

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        def binary_search(nums, target, left):
            low, high = 0, len(nums) - 1
            index = -1
            while low <= high:
                mid = (low + high) // 2
                if nums[mid] == target:
                    index = mid
                    if left:
                        high = mid - 1
                    else:
                        low = mid + 1
                elif nums[mid] < target:
                    low = mid + 1
                else:
                    high = mid - 1
            return index

        left_index = binary_search(nums, target, left=True)
        right_index = binary_search(nums, target, left=False)

        return [left_index, right_index]

1.346 - 2023-10-30 09:17:05 +0000 UTC

Binary Tree Right Side View

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        
        q_cur, q_next, answer = deque(), deque(), []
        q_cur.append(root)

        while q_cur:
            last_val = None
            
            while q_cur:
                node = q_cur.popleft()
                last_val = node.val
                if node.left:
                    q_next.append(node.left)
                if node.right:
                    q_next.append(node.right)
            
            q_cur, q_next = q_next, q_cur
            answer.append(last_val)
    
        return answer

1.347 - 2023-10-30 09:10:35 +0000 UTC

Binary Tree Right Side View

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def rightSideView(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []
        cur, nxt = [root], []
        answer = []
        
        while cur:
            last_node = cur.pop()
            if last_node.right:
                nxt.append(last_node.right)
            if last_node.left:
                nxt.append(last_node.left)
            answer.append(last_node.val)
            
            while cur:
                node = cur.pop()
                if node.right:
                    nxt.append(node.right)
                if node.left:
                    nxt.append(node.left)
            
            cur.clear()
            nxt.reverse()
            cur, nxt = nxt, cur

        return answer

1.348 - 2023-10-30 07:51:12 +0000 UTC

Sort Integers by The Number of 1 Bits

Code

class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        return tuple(num for num in sorted(arr, key=lambda num: (num.bit_count(), num)))

1.349 - 2023-10-29 16:36:33 +0000 UTC

Poor Pigs

Code

class Solution:
    def poorPigs(self, buckets: int, a: int, b: int) -> int:
        pigs = 0
        while (b / a + 1) ** pigs < buckets:
            pigs += 1

        return pigs 

1.350 - 2023-10-28 14:51:04 +0000 UTC

Count Vowels Permutation

Code

class Solution:
    def countVowelPermutation(self, n: int) -> int:
        MOD = 10**9 + 7
        
        a, e, i, o, u = 1, 1, 1, 1, 1
        
        for _ in range(1, n):
            a_next = e
            e_next = (a + i) % MOD
            i_next = (a + e + o + u) % MOD
            o_next = (i + u) % MOD
            u_next = a
            
            a, e, i, o, u = a_next, e_next, i_next, o_next, u_next
        
        return (a + e + i + o + u) % MOD

1.351 - 2023-10-27 14:47:50 +0000 UTC

Longest Palindromic Substring

Code

class Solution:
    def longestPalindrome(self, s: str) -> str:
        n = len(s)
        dp = [[False] * n for _ in range(n)]
        ans = [0, 0]
        
        for i in range(n):
            dp[i][i] = True
        
        for i in range(n - 1):
            if s[i] == s[i + 1]:
                dp[i][i + 1] = True
                ans = [i, i + 1]

        for diff in range(2, n):
            for i in range(n - diff):
                j = i + diff
                if s[i] == s[j] and dp[i + 1][j - 1]:
                    dp[i][j] = True
                    ans = [i, j]

        i, j = ans
        return s[i:j + 1]

1.352 - 2023-10-26 20:07:22 +0000 UTC

Binary Trees With Factors

Code

MOD = 10**9 + 7

class Solution:
    def numFactoredBinaryTrees(self, arr: List[int]) -> int:
        arr.sort()
        s = set(arr)
        dp = {x: 1 for x in arr}
        
        for i in arr:
            for j in arr:
                if j > i**0.5:
                    break
                if i % j == 0 and i // j in s:
                    if i // j == j:
                        dp[i] += dp[j] * dp[j]
                    else:
                        dp[i] += dp[j] * dp[i // j] * 2
                    dp[i] %= MOD
        
        return sum(dp.values()) % MOD

1.353 - 2023-10-25 10:37:39 +0000 UTC

Design Add and Search Words Data Structure

Code

class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_word = False

class WordDictionary:

    def __init__(self):
        self.root = TrieNode()

    def addWord(self, word: str) -> None:
        cur = self.root
        for char in word:
            cur = cur.children.setdefault(char, TrieNode())
        cur.is_word = True

    def search(self, word: str) -> bool:
        cur, nxt = [self.root], []
        
        for char in word:
            if not cur:
                return False

            if char == ".":
                for node in cur:
                    nxt.extend(node.children.values())
            else:
                for node in cur:
                    if char in node.children:
                        nxt.append(node.children[char]) 
                
            cur.clear()
            cur, nxt = nxt, cur

        return any(node.is_word for node in cur)
            



# Your WordDictionary object will be instantiated and called as such:
# obj = WordDictionary()
# obj.addWord(word)
# param_2 = obj.search(word)

1.354 - 2023-10-25 08:31:06 +0000 UTC

K-th Symbol in Grammar

Code

class Solution:
    def kthGrammar(self, n: int, k: int) -> int:

        def get(row: int, column: int) -> int:
            if column == 0 or column == 1:
                return column
            
            prev_row_length = 2 ** (row - 1)
            if column >= prev_row_length:
                return 1 ^ get(row - 1, column - prev_row_length)
            return get(row - 1, column)

        return get(n - 1, k - 1)

        # 0
        # 0 1
        # 0 1 1 0
        # 0 1 1 0 1 0 0 1
        # 0 1 1 0 1 0 0 1

1.355 - 2023-10-24 11:55:16 +0000 UTC

Find Largest Value in Each Tree Row

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def largestValues(self, root: Optional[TreeNode]) -> List[int]:
        if not root:
            return []

        largest = []
        cur, nxt = [root], []
        cur_val = None
        while cur or nxt:
            while cur:
                node = cur.pop()
                if cur_val is None or node.val > cur_val:
                    cur_val = node.val
                if node.left:
                    nxt.append(node.left)
                if node.right:
                    nxt.append(node.right)
            largest.append(cur_val)
            cur.clear()
            cur_val = None
            cur, nxt = nxt, cur
        return largest

1.356 - 2023-10-23 09:26:07 +0000 UTC

Power of Four

Code

class Solution:
    def isPowerOfFour(self, n: int) -> bool:
        # Check if the number is greater than zero and is a power of two
        if n > 0 and (n & (n - 1)) == 0:
            # Check if the number is of the form 4^x
            return n & 0x55555555 == n
        else:
            return False

1.357 - 2023-10-22 10:57:47 +0000 UTC

Maximum Score of a Good Subarray

Code

class Solution:
    def maximumScore(self, nums: List[int], k: int) -> int:
        n = len(nums)
        left = k
        right = k
        ans = nums[k]
        curr_min = nums[k]
        
        while left > 0 or right < n - 1:
            if (nums[left - 1] if left else 0) < (nums[right + 1] if right < n - 1 else 0):
                right += 1
                curr_min = min(curr_min, nums[right])
            else:
                left -= 1
                curr_min = min(curr_min, nums[left])

            ans = max(ans, curr_min * (right - left + 1))
        
        return ans

1.358 - 2023-10-21 11:20:53 +0000 UTC

Constrained Subsequence Sum

Code

import heapq

class Solution:
    def constrainedSubsetSum(self, nums: List[int], k: int) -> int:
        heap = [(-nums[0], 0)]
        ans = nums[0]
        
        for i in range(1, len(nums)):
            while i - heap[0][1] > k:
                heapq.heappop(heap)

            curr = max(0, -heap[0][0]) + nums[i]
            ans = max(ans, curr)
            heapq.heappush(heap, (-curr, i))

        return ans

1.359 - 2023-10-20 13:11:39 +0000 UTC

Flatten Nested List Iterator

Code

# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
#    def isInteger(self) -> bool:
#        """
#        @return True if this NestedInteger holds a single integer, rather than a nested list.
#        """
#
#    def getInteger(self) -> int:
#        """
#        @return the single integer that this NestedInteger holds, if it holds a single integer
#        Return None if this NestedInteger holds a nested list
#        """
#
#    def getList(self) -> [NestedInteger]:
#        """
#        @return the nested list that this NestedInteger holds, if it holds a nested list
#        Return None if this NestedInteger holds a single integer
#        """

class NestedIterator:
    def __init__(self, nestedList: [NestedInteger]):
        self.get_next = self.get_next_gen(nestedList)
        self.next_val = next(self.get_next, None)

    def get_next_gen(self, nestedList: List[NestedInteger]) -> Generator[None, None, int]:
        for ni in nestedList:
            if ni.isInteger():
                yield ni.getInteger()
            else:
                yield from self.get_next_gen(ni.getList())

    def next(self) -> int: 
        answer, self.next_val = self.next_val, next(self.get_next, None)
        return answer
    
    def hasNext(self) -> bool:
        return self.next_val is not None

# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())

1.360 - 2023-10-20 13:06:36 +0000 UTC

Flatten Nested List Iterator

Code

# """
# This is the interface that allows for creating nested lists.
# You should not implement it, or speculate about its implementation
# """
#class NestedInteger:
#    def isInteger(self) -> bool:
#        """
#        @return True if this NestedInteger holds a single integer, rather than a nested list.
#        """
#
#    def getInteger(self) -> int:
#        """
#        @return the single integer that this NestedInteger holds, if it holds a single integer
#        Return None if this NestedInteger holds a nested list
#        """
#
#    def getList(self) -> [NestedInteger]:
#        """
#        @return the nested list that this NestedInteger holds, if it holds a nested list
#        Return None if this NestedInteger holds a single integer
#        """

class NestedIterator:
    def __init__(self, nestedList: [NestedInteger]):
        self.list = []
        self.flatten(self.list, nestedList)
        self.cur = 0
        self.length = len(self.list)

    def flatten(self, flatList: List[int], nestedList: List[NestedInteger]):
        for ni in nestedList:
            if ni.isInteger():
                flatList.append(ni.getInteger())
            else:
                self.flatten(flatList, ni.getList())

    def next(self) -> int: 
        answer = self.list[self.cur]
        self.cur += 1
        return answer
    
    def hasNext(self) -> bool:
        return self.cur < self.length

# Your NestedIterator object will be instantiated and called as such:
# i, v = NestedIterator(nestedList), []
# while i.hasNext(): v.append(i.next())

1.361 - 2023-10-19 14:09:46 +0000 UTC

Backspace String Compare

Code

class Solution:
    def backspaceCompare(self, s: str, t: str) -> bool:
        i1, i2 = len(s) - 1, len(t) - 1
        skip1, skip2 = 0, 0

        while i1 >= 0 or i2 >= 0:
            char1, char2 = s[i1] if i1 >= 0 else "", t[i2] if i2 >= 0 else ""
            if char1 == "#":
                i1 -= 1
                skip1 += 1
            elif char2 == "#":
                i2 -= 1
                skip2 += 1
            elif skip1 > 0:
                i1 -= 1
                skip1 -= 1
            elif skip2 > 0:
                i2 -= 1
                skip2 -= 1
            elif char1 != char2:
                return False
            else:
                i1 -= 1
                i2 -= 1
        
        return True 

1.362 - 2023-10-18 16:38:53 +0000 UTC

Parallel Courses III

Code

class Solution:
    def minimumTime(self, n: int, relations: List[List[int]], time: List[int]) -> int:
        graph = defaultdict(list)
        indegree = [0] * n
        
        for (x, y) in relations:
            graph[x - 1].append(y - 1)
            indegree[y - 1] += 1
        
        queue = deque()
        max_time = [0] * n
        for node in range(n):
            if indegree[node] == 0:
                queue.append(node)
                max_time[node] = time[node]

        while queue:
            node = queue.popleft()
            for neighbor in graph[node]:
                max_time[neighbor] = max(max_time[neighbor], max_time[node] + time[neighbor])
                indegree[neighbor] -= 1
                if indegree[neighbor] == 0:
                    queue.append(neighbor)

        return max(max_time)

1.363 - 2023-10-17 15:45:21 +0000 UTC

Validate Binary Tree Nodes

Code

class Solution:
    def validateBinaryTreeNodes(self, n: int, leftChild: List[int], rightChild: List[int]) -> bool:
        parents = [-1] * n

        for i in range(n):
            left, right = leftChild[i], rightChild[i] 
            left_valid, right_valid = left != -1, right != -1
            if (left_valid and parents[left] != -1) or (
                right_valid and parents[right] != -1
            ):
                return False
            if left_valid:
                parents[left] = i
            if right_valid:
                parents[right] = i

            parent = parents[i]
            if parent != -1 and (parent == left or parent == right):
                return False

        root = None
        for i, node in enumerate(parents):
            if node == -1 and root is not None:
                return False
            if node == -1:
                root = i

        if root is None:
            return False

        to_visit = [root]
        visited = set()

        while to_visit:
            node = to_visit.pop()
            if node in visited:
                return False
            visited.add(node)
            left, right = leftChild[node], rightChild[node]
            if left != -1:
                to_visit.append(left)
            if right != -1:
                to_visit.append(right)

        return len(visited) == n 
        

1.364 - 2023-10-16 17:32:07 +0000 UTC

Pascal’s Triangle II

Code

class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        cur, prev = [], [1]
        row = 0

        while row < rowIndex:
            cur.append(1)
            for i in range(1, len(prev)):
                cur.append(prev[i] + prev[i-1])
            cur.append(1)
            prev.clear()
            cur, prev = prev, cur
            row += 1
        
        return prev 

1.365 - 2023-10-15 10:05:28 +0000 UTC

Number of Ways to Stay in the Same Place After Some Steps

Code

class Solution:
    def numWays(self, steps: int, arrLen: int) -> int:
        @cache
        def dp(curr, remain):
            if remain == 0:
                if curr == 0:
                    return 1
                
                return 0
            
            ans = dp(curr, remain - 1)
            if curr > 0:
                ans = (ans + dp(curr - 1, remain - 1)) % MOD
            
            if curr < arrLen - 1:
                ans = (ans + dp(curr + 1, remain - 1)) % MOD
                
            return ans
        
        MOD = 10 ** 9 + 7
        return dp(0, steps)

1.366 - 2023-10-14 16:53:26 +0000 UTC

Painting the Walls

Code

class Solution:
    def paintWalls(self, cost: List[int], time: List[int]) -> int:
        @cache
        def dp(i, remain):
            if remain <= 0:
                return 0
            if i == n:
                return inf
            
            paint = cost[i] + dp(i + 1, remain - 1 - time[i])
            dont_paint = dp(i + 1, remain)
            return min(paint, dont_paint)
    
        n = len(cost)
        return dp(0, n)

1.367 - 2023-10-14 07:14:40 +0000 UTC

Min Cost Climbing Stairs

Code

class Solution:
    def minCostClimbingStairs(self, cost):
        n = len(cost)
        dp = [0] * n
        dp[0] = cost[0]
        dp[1] = cost[1]
        
        for i in range(2, n):
            dp[i] = cost[i] + min(dp[i-1], dp[i-2])
        
        return min(dp[n-1], dp[n-2])

1.368 - 2023-10-12 09:09:45 +0000 UTC

Find in Mountain Array

Code

class Solution:
    def findInMountainArray(self, target: int, mountain_arr: 'MountainArray') -> int:
        # Save the length of the mountain array
        length = mountain_arr.length()

        # 1. Find the index of the peak element
        low = 1
        high = length - 2
        while low != high:
            test_index = (low + high) // 2
            if mountain_arr.get(test_index) < mountain_arr.get(test_index + 1):
                low = test_index + 1
            else:
                high = test_index
        peak_index = low

        # 2. Search in the strictly increasing part of the array
        low = 0
        high = peak_index
        while low != high:
            test_index = (low + high) // 2
            if mountain_arr.get(test_index) < target:
                low = test_index + 1
            else:
                high = test_index    
        # Check if the target is present in the strictly increasing part
        if mountain_arr.get(low) == target:
            return low
        
        # 3. Otherwise, search in the strictly decreasing part
        low = peak_index + 1
        high = length - 1
        while low != high:
            test_index = (low + high) // 2
            if mountain_arr.get(test_index) > target:
                low = test_index + 1
            else:
                high = test_index
        # Check if the target is present in the strictly decreasing part
        if mountain_arr.get(low) == target:
            return low
        
        # Target is not present in the mountain array
        return -1

1.369 - 2023-10-11 13:06:35 +0000 UTC

Number of Flowers in Full Bloom

Code

class Solution:
    def fullBloomFlowers(self, flowers: List[List[int]], people: List[int]) -> List[int]:
        flowers.sort()
        sorted_people = sorted(people)
        dic = {}
        heap = []
        
        i = 0
        for person in sorted_people:
            while i < len(flowers) and flowers[i][0] <= person:
                heapq.heappush(heap, flowers[i][1])
                i += 1
            
            while heap and heap[0] < person:
                heapq.heappop(heap)
            
            dic[person] = len(heap)

        return [dic[x] for x in people]

1.370 - 2023-10-10 05:23:28 +0000 UTC

Minimum Number of Operations to Make Array Continuous

Code

class Solution:
    def minOperations(self, nums: List[int]) -> int:
        n = len(nums)
        ans = n
        new_nums = sorted(set(nums))
        
        for i in range(len(new_nums)):
            left = new_nums[i]
            right = left + n - 1
            j = bisect_right(new_nums, right)
            count = j - i
            ans = min(ans, n - count)

        return ans

1.371 - 2023-10-09 11:15:25 +0000 UTC

Find First and Last Position of Element in Sorted Array

Code

class Solution:
    def searchRange(self, nums: List[int], target: int) -> List[int]:
        def binary_search(nums, target, left):
            low, high = 0, len(nums) - 1
            index = -1
            while low <= high:
                mid = (low + high) // 2
                if nums[mid] == target:
                    index = mid
                    if left:
                        high = mid - 1
                    else:
                        low = mid + 1
                elif nums[mid] < target:
                    low = mid + 1
                else:
                    high = mid - 1
            return index

        left_index = binary_search(nums, target, left=True)
        right_index = binary_search(nums, target, left=False)

        return [left_index, right_index]

1.372 - 2023-10-08 07:39:44 +0000 UTC

Max Dot Product of Two Subsequences

Code

class Solution:
    def maxDotProduct(self, nums1: List[int], nums2: List[int]) -> int:
        @cache
        def dp(i, j):
            if i == len(nums1) or j == len(nums2):
                return 0
            
            use = nums1[i] * nums2[j] + dp(i + 1, j + 1)
            return max(use, dp(i + 1, j), dp(i, j + 1))
            
        if max(nums1) < 0 and min(nums2) > 0:
            return max(nums1) * min(nums2)
        
        if min(nums1) > 0 and max(nums2) < 0:
            return min(nums1) * max(nums2)
        
        return dp(0, 0)

1.373 - 2023-10-07 16:48:10 +0000 UTC

Build Array Where You Can Find The Maximum Exactly K Comparisons

Code

class Solution:
    def numOfArrays(self, n: int, m: int, k: int) -> int:
        @cache
        def dp(i, max_so_far, remain):
            if i == n:
                if remain == 0:
                    return 1
                
                return 0
            
            ans = (max_so_far * dp(i + 1, max_so_far, remain)) % MOD
            for num in range(max_so_far + 1, m + 1):
                ans = (ans + dp(i + 1, num, remain - 1)) % MOD
                
            return ans
        
        MOD = 10 ** 9 + 7
        return dp(0, 0, k)

1.374 - 2023-10-06 09:24:39 +0000 UTC

Integer Break

Code

class Solution:
    def integerBreak(self, n: int) -> int:
        if n < 4:
            return n - 1
        
        @cache
        def dp(num: int) -> int:
            if num <= 3:
                return num
            ans = num
            for i in range(2, num):
                ans = max(ans, i * dp(num - i))
            return ans

        return dp(n)

1.375 - 2023-10-06 09:24:09 +0000 UTC

Integer Break

Code

class Solution:
    def integerBreak(self, n: int) -> int:
        @cache
        def dp(num: int) -> int:
            if num <= 3:
                return num
            ans = num
            for i in range(2, num):
                ans = max(ans, i * dp(num - i))
            return ans

        return dp(n) if n > 3 else n - 1

1.376 - 2023-10-05 06:46:37 +0000 UTC

Majority Element II

Code

class Solution:
    def majorityElement(self, nums: List[int]) -> List[int]:
        nums.sort()
        threshold = len(nums) // 3
        cur_num, cur_count = nums[0], 1
        answer = []
        for num in nums[1:]:
            if num == cur_num:
                cur_count += 1
                continue
            if cur_count > threshold:
                answer.append(cur_num)
            cur_num, cur_count = num, 1
        if cur_count > threshold:
            answer.append(cur_num)
        return answer

1.377 - 2023-10-04 06:00:01 +0000 UTC

Design HashMap

Code

class ListNode:
    def __init__(self, key, value):
        self.key = key
        self.value = value
        self.next = None

class MyHashMap:

    def __init__(self):
        self.size = 1000
        self.table = [None] * self.size

    def _index(self, key: int) -> int:
        return key % self.size

    def put(self, key: int, value: int) -> None:
        idx = self._index(key)
        if not self.table[idx]:
            self.table[idx] = ListNode(key, value)
            return
        current = self.table[idx]
        while current:
            if current.key == key:
                current.value = value
                return
            if not current.next:
                current.next = ListNode(key, value)
                return
            current = current.next

    def get(self, key: int) -> int:
        idx = self._index(key)
        current = self.table[idx]
        while current:
            if current.key == key:
                return current.value
            current = current.next
        return -1

    def remove(self, key: int) -> None:
        idx = self._index(key)
        current = self.table[idx]
        if not current:
            return
        if current.key == key:
            self.table[idx] = current.next
            return
        while current.next:
            if current.next.key == key:
                current.next = current.next.next
                return
            current = current.next


# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)

1.378 - 2023-10-04 05:57:26 +0000 UTC

Design HashMap

Code

class MyHashMap:
    def __init__(self):
        self.data = [None] * 1000001

    def put(self, key: int, val: int) -> None:
        self.data[key] = val
        
    def get(self, key: int) -> int:
        val = self.data[key]
        return -1 if val is None else val

    def remove(self, key: int) -> None:
        self.data[key] = None
        


# Your MyHashMap object will be instantiated and called as such:
# obj = MyHashMap()
# obj.put(key,value)
# param_2 = obj.get(key)
# obj.remove(key)

1.379 - 2023-10-03 06:14:03 +0000 UTC

Number of Good Pairs

Code

class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:
        counter = Counter(nums)
        return sum((count ** 2 - count) // 2 for count in counter.values() if count > 1)

1.380 - 2023-10-03 06:13:40 +0000 UTC

Number of Good Pairs

Code

class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:        
        return sum((count ** 2 - count) // 2 for count in Counter(nums).values() if count > 1)

1.381 - 2023-10-03 06:13:11 +0000 UTC

Number of Good Pairs

Code

class Solution:
    def numIdenticalPairs(self, nums: List[int]) -> int:
        counter = Counter(nums)
        
        return sum((count ** 2 - count) // 2 for count in counter.values() if count > 1)

1.382 - 2023-10-02 12:20:53 +0000 UTC

Remove Colored Pieces if Both Neighbors are the Same Color

Code

class Solution:
    def winnerOfGame(self, colors: str) -> bool:
        cur_char, cur_conseq = colors[0], 1
        moves = {"A": 0, "B": 0}
        for char in colors[1:]:
            if char == cur_char:
                cur_conseq += 1
            else:
                moves[cur_char] += max(0, cur_conseq - 2)
                cur_char, cur_conseq = char, 1
        if cur_conseq > 2:
            moves[cur_char] += cur_conseq - 2
        return moves["A"] > moves["B"]

1.383 - 2023-10-01 13:29:08 +0000 UTC

Reverse Words in a String III

Code

class Solution:
    def reverseWords(self, s: str) -> str:
        return ' '.join(map(lambda word: word[::-1], s.split()))

1.384 - 2023-09-30 07:17:26 +0000 UTC

Merge Intervals

Code

class Solution:
    def merge(self, intervals: List[List[int]]) -> List[List[int]]:

        intervals.sort(key=lambda item: item[0])

        merged = []
        for start, end in intervals:
            # if the list of merged intervals is empty or if the current
            # interval does not overlap with the previous, simply append it.
            if not merged or merged[-1][1] < start:
                merged.append([start, end])
            else:
            # otherwise, there is overlap, so we merge the current and previous
            # intervals.
                merged[-1][1] = max(merged[-1][1], end)

        return merged

1.385 - 2023-09-30 07:09:04 +0000 UTC

132 Pattern

Code

class Solution:
    def find132pattern(self, nums: List[int]) -> bool:
        if len(nums) < 3:
            return False
        min_array = [-1] * len(nums)
        min_array[0] = nums[0]
        for i in range(1, len(nums)):
            min_array[i] = min(min_array[i - 1], nums[i])

        k = len(nums)
        for j in range(len(nums) - 1, -1, -1):
            if nums[j] <= min_array[j]:
                continue
            while k < len(nums) and nums[k] <= min_array[j]:
                k += 1
            if k < len(nums) and nums[k] < nums[j]:
                return True
            k -= 1
            nums[k] = nums[j]
        return False

1.386 - 2023-09-30 07:05:56 +0000 UTC

132 Pattern

Code

class Solution:
    def find132pattern(self, nums: List[int]) -> bool:
        if len(nums) < 3:
            return False
        stack = []
        min_array = [-1] * len(nums)
        min_array[0] = nums[0]
        for i in range(1, len(nums)):
            min_array[i] = min(min_array[i - 1], nums[i])

        for j in reversed(range(len(nums))):
            if nums[j] <= min_array[j]:
                continue
            while stack and stack[-1] <= min_array[j]:
                stack.pop()
            if stack and stack[-1] < nums[j]:
                return True
            stack.append(nums[j])
        return False

1.387 - 2023-09-29 05:36:09 +0000 UTC

Monotonic Array

Code

class Solution:
    def isMonotonic(self, nums: List[int]) -> bool:
        length = len(nums)
        if length < 3:
            return True
        is_increasing = None
        for i in range(1, length):
            cur, prev = nums[i], nums[i-1]
            if cur == prev:
                continue
            is_increasing_cur = cur > prev
            if is_increasing is None:
                is_increasing = is_increasing_cur
                continue
            if is_increasing and not is_increasing_cur or (
                not is_increasing and is_increasing_cur
            ):
                return False
        return True

1.388 - 2023-09-28 07:17:33 +0000 UTC

Sort Array By Parity

Code

class Solution:
    def sortArrayByParity(self, nums: List[int]) -> List[int]:
        left, right = 0, len(nums) - 1
        while left < right:
            while left < right and nums[left] % 2 == 0:
                left += 1
            while left < right and nums[right] % 2 == 1:
                right -= 1
            nums[left], nums[right] = nums[right], nums[left]
        return nums

1.389 - 2023-09-28 07:13:16 +0000 UTC

Sort Array By Parity

Code

class Solution:
    def sortArrayByParity(self, nums: List[int]) -> List[int]:
        length = len(nums)
        left, right = 0, length - 1
        answer = [None] * length
        for num in nums:
            if num % 2 == 0:
                answer[left] = num
                left += 1
            else:
                answer[right] = num
                right -= 1
        return answer

1.390 - 2023-09-27 15:11:20 +0000 UTC

Decoded String at Index

Code

class Solution:
    def decodeAtIndex(self, s: str, k: int) -> str:
        length = 0
        i = 0
        
        while length < k:
            if s[i].isdigit():
                length *= int(s[i])
            else:
                length += 1
            i += 1
        
        for j in range(i-1, -1, -1):
            char = s[j]
            if char.isdigit():
                length //= int(char)
                k %= length
            else:
                if k == 0 or k == length:
                    return char
                length -= 1

1.391 - 2023-09-26 10:43:09 +0000 UTC

Remove Duplicate Letters

Code

class Solution:
    def removeDuplicateLetters(self, s: str) -> str:
        stack = []
        seen = set() 
        last_occ = {char: i for i, char in enumerate(s)}
        
        for i, char in enumerate(s):
            if char in seen:
                continue
                
            while stack and char < stack[-1] and i < last_occ[stack[-1]]:
                seen.discard(stack.pop())
            seen.add(char)
            stack.append(char)
        
        return ''.join(stack)

1.392 - 2023-09-25 06:17:00 +0000 UTC

Find Minimum in Rotated Sorted Array

Code

class Solution:
    def findMin(self, nums: List[int]) -> int:
        length = len(nums)
        if length == 1:
            return nums[0]
        first, last = nums[0], nums[-1]
        if first < last:
            return first
        left, right = 0, length - 1
        while left <= right:
            mid = left + (right - left) // 2
            left_num = nums[mid - 1] if mid > 0 else first
            mid_num = nums[mid] 
            right_num = nums[mid + 1] if mid + 1 < length else last
            if left_num > mid_num <= right_num:
                return mid_num
            if left_num > mid_num or (left_num <= mid_num and mid_num >= first):
                left = mid + 1
            else:
                right = mid
        return nums[left]

1.393 - 2023-09-25 05:28:38 +0000 UTC

Find the Difference

Code

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        return chr(reduce(operator.xor, (ord(char) for char in chain(s, t))))

1.394 - 2023-09-25 05:26:39 +0000 UTC

Find the Difference

Code

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        count = Counter(s)
        for char in t:
            count[char] -= 1
            if count[char] == -1:
                return char

1.395 - 2023-09-24 11:37:54 +0000 UTC

Bitwise AND of Numbers Range

Code

class Solution:
    def rangeBitwiseAnd(self, left: int, right: int) -> int:
        shift = 0        
        while left < right:
            left >>= 1
            right >>= 1
            shift += 1
        return left << shift

1.396 - 2023-09-24 10:28:55 +0000 UTC

Container With Most Water

Code

class Solution:
    def maxArea(self, height: List[int]) -> int:
        left = 0
        right = len(height) - 1
        maxArea = 0

        while left < right:
            currentArea = min(height[left], height[right]) * (right - left)
            if currentArea > maxArea:
                maxArea = currentArea

            if height[left] < height[right]:
                left += 1
            else:
                right -= 1

        return maxArea

1.397 - 2023-09-24 10:26:28 +0000 UTC

Max Points on a Line

Code

class Solution:
    def maxPoints(self, points: List[List[int]]) -> int:
        lines = defaultdict(set)
        length = len(points)
        if length < 3:
            return length
        for i in range(length):
            x1, y1 = points[i]
            for j in range(i + 1, length):
                x2, y2 = points[j]
                k1, k2 = None, None
                if y1 == y2:
                    k2 = y1
                elif x1 == x2:
                    k1 = x1
                else: 
                    k1 = (y2 - y1) / (x2 - x1)
                    k2 = y1 - k1 * x1
                lines[(k1, k2)].update(((x1, y1), (x2, y2)))
        return max((len(points) for points in lines.values()), default=0)

1.398 - 2023-09-24 10:00:11 +0000 UTC

Candy

Code

class Solution:
    def candy(self, ratings: List[int]) -> int:
        child_count = len(ratings)
        candies = [1] * child_count 

        for i in range(1, child_count):
            if ratings[i] > ratings[i-1]:
                candies[i] = candies[i-1] + 1

        for i in reversed(range(child_count - 1)):
            if ratings[i] > ratings[i+1]:
                candies[i] = max(candies[i], candies[i+1] + 1)
        
        return sum(candies)

1.399 - 2023-09-24 09:59:51 +0000 UTC

Longest Substring Without Repeating Characters

Code

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        length = len(s)
        if length < 2:
            return length
        
        max_length, left, charset = 1, 0, set([s[0]])
        for right in range(1, length):
            letter = s[right]
            if letter not in charset:
                charset.add(letter)
                continue

            this_length = right - left
            if this_length > max_length:
                max_length = this_length
            
            while letter in charset:
                charset.remove(s[left])
                left += 1
            
            charset.add(letter)

        return max(max_length, length - left)

1.400 - 2023-09-24 09:59:24 +0000 UTC

Populating Next Right Pointers in Each Node II

Code

from collections import deque

class Solution:
  def connect(self, root: 'Node') -> 'Node':
    # Edge case - If the root is None, then return None
    if root is None:
        return None
    
    # Create a queue and enqueue the root node
    q = deque([root])
    
    # Traverse the tree level by level
    while q:
        
        # Get the number of nodes of the current level
        level_size = len(q)
        
        # Process the nodes of the current level
        for i in range(level_size):
            
            # Dequeue a node from the front of the queue
            node = q.popleft()
            
            # Assign the next pointer of the node
            if i < level_size - 1:
                node.next = q[0]
            
            # Enqueue the children of the node (if any)
            if node.left is not None:
                q.append(node.left)
            if node.right is not None:
                q.append(node.right)
    
    # Return the root node
    return root

1.401 - 2023-09-24 09:56:43 +0000 UTC

Binary Search Tree Iterator

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class BSTIterator:

    def __init__(self, root: Optional[TreeNode]):
        def generate(node: TreeNode) -> int:
            if not node:
                return
            yield from generate(node.left)
            yield node
            yield from generate(node.right)

        self._generate = generate(root)
        self._next = next(self._generate)

    def next(self) -> int:
        next_val = self._next.val
        self._next = next(self._generate, None)
        return next_val 

    def hasNext(self) -> bool:
        return self._next is not None


# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()

1.402 - 2023-09-24 09:56:22 +0000 UTC

Implement Trie (Prefix Tree)

Code

class Trie:

    def __init__(self):
        self.root = {}

    def insert(self, word: str) -> None:
        cur = self.root
        for char in word:
            if char not in cur:
                cur[char] = {}
            cur = cur[char]
        
        cur["_is_word"] = None

    def search(self, word: str) -> bool:
        cur = self.root
        for char in word:
            if char not in cur:
                return False
            cur = cur[char]
        
        return "_is_word" in cur

    def startsWith(self, prefix: str) -> bool:
        cur = self.root
        for char in prefix:
            if char not in cur:
                return False
            cur = cur[char]
            
        return True


# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)

1.403 - 2023-09-24 09:55:57 +0000 UTC

Combinations

Code

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        current = []
        
        def backtrack(first: int) -> Generator[None, None, List[int]]:
            if len(current) == k:
                yield tuple(current[:])
                return

            for i in range(first, n + 1):
                current.append(i)
                yield from backtrack(i + 1)
                current.pop()
            
            return

        return tuple(combination for combination in backtrack(1)) 

1.404 - 2023-09-24 09:55:41 +0000 UTC

Permutations

Code

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:

        length = len(nums)
        current = []
        current_contains = [False] * length

        def backtrack() -> Generator[None, None, List[int]]:
            if len(current) == length:
                yield tuple(current[:])
                return

            for i in range(length):
                if current_contains[i]:
                    continue

                current_contains[i] = True
                current.append(nums[i])

                yield from backtrack()

                current_contains[i] = False
                current.pop()
            
            return

        return tuple(combination for combination in backtrack()) 

1.405 - 2023-09-24 09:55:19 +0000 UTC

Generate Parentheses

Code

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:

        current = []
        current_max = n * 2
        chars = "()"


        def backtrack(open: int, closed: int) -> Generator[None, None, List[str]]:
            if len(current) == current_max:
                yield "".join(current)
            
            if open:
                current.append(chars[0])
                yield from backtrack(open - 1, closed)
                current.pop()
            
            if closed and closed > open:
                current.append(chars[1])
                yield from backtrack(open, closed - 1)
                current.pop()
        
        return tuple(combination for combination in backtrack(n, n))

1.406 - 2023-09-24 09:54:51 +0000 UTC

Maximum Subarray

Code

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        length = len(nums)
        if length == 0:
            return 0
        if length == 1:
            return nums[0]
        max_cur, max_overall = 0, float("-inf")
        for num in nums:
            max_cur += num
            if max_cur > max_overall:
                max_overall = max_cur
            if max_cur < 0:
                max_cur = 0
        return max_overall
        

1.407 - 2023-09-24 09:53:12 +0000 UTC

Median of Two Sorted Arrays

Code

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        m, n = len(nums1), len(nums2)
        p1, p2 = 0, 0
        
        # Get the smaller value between nums1[p1] and nums2[p2].
        def get_min():
            nonlocal p1, p2
            if p1 < m and p2 < n:
                if nums1[p1] < nums2[p2]:
                    ans = nums1[p1]
                    p1 += 1
                else:
                    ans = nums2[p2]
                    p2 += 1
            elif p2 == n:
                ans = nums1[p1]
                p1 += 1
            else:
                ans = nums2[p2]
                p2 += 1
            return ans
        
        if (m + n) % 2 == 0:
            for _ in range((m + n) // 2 - 1):
                _ = get_min()
            return (get_min() + get_min()) / 2
        else:
            for _ in range((m + n) // 2):
                _ = get_min()
            return get_min()

1.408 - 2023-09-24 09:52:56 +0000 UTC

Search in Rotated Sorted Array

Code

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        nums_count = len(nums)
        left, right = 0, len(nums) - 1

        first_num, last_num = nums[0], nums[-1]
        if first_num == target:
            return 0
        if last_num == target:
            return nums_count - 1
        
        # Find the index of the pivot element (the smallest element)
        while left <= right:
            mid = left + (right - left) // 2
            if nums[mid] > last_num:
                left = mid + 1
            else:
                right = mid - 1
        
        pivot_num = nums[left]
        if pivot_num == target:
            return left
        
        if pivot_num < target < last_num:
            right = nums_count - 1
        else:
            left = 0
        
        while left <= right:
            mid = left + (right - left) // 2
            mid_num = nums[mid]
            if mid_num == target:
                return mid
            elif mid_num > target:
                right = mid - 1
            else:
                left = mid + 1
        
        return -1

1.409 - 2023-09-24 09:52:34 +0000 UTC

Single Number II

Code

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        nums.sort()
        length = len(nums)
        for i in range(0, length, 3):
            if i == length - 1:
                return nums[i]
    
            num_1, num_2, num_3 = nums[i], nums[i+1], nums[i+2]

            if num_1 == num_2 == num_3:
                continue
            
            if num_2 == num_3:
                return num_1
            
            if num_1 == num_3:
                return num_2
            
            return num_3
            

1.410 - 2023-09-24 09:52:13 +0000 UTC

Single Number

Code

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return reduce(xor, nums)

1.411 - 2023-09-24 09:51:48 +0000 UTC

Number of 1 Bits

Code

class Solution:
    def hammingWeight(self, n: int) -> int:
        count = 0
        while n > 0:
            if n & 1 != 0:
                count += 1
            n >>= 1
        return count

1.412 - 2023-09-24 09:50:52 +0000 UTC

Reverse Bits

Code

class Solution:
    def reverseBits(self, n: int) -> int:
        # Initialize the reversed number to 0
        reversed_num = 0
        
        # Iterate over all 32 bits of the given number
        for i in range(32):
            # Left shift the reversed number by 1 and add the last bit of the given number to it
            reversed_num = (reversed_num << 1) | (n & 1)
            # remove the last bit from the original number
            n >>= 1
        
        # Return the reversed number
        return reversed_num

1.413 - 2023-09-24 09:50:33 +0000 UTC

Add Binary

Code

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        answer = []
        carry = 0
        for char1, char2 in zip_longest(reversed(a), reversed(b)):
            num1, num2 = int(char1) if char1 else 0, int(char2) if char2 else 0
            cur_sum = num1 + num2 + carry
            carry = 0
            if cur_sum > 1:
                cur_sum -= 2
                carry = 1
            
            answer.append(str(cur_sum))
        
        if carry:
            answer.append("1")

        return "".join(reversed(answer))

1.414 - 2023-09-24 09:47:07 +0000 UTC

Factorial Trailing Zeroes

Code

class Solution:
    def trailingZeroes(self, n: int) -> int:
        zeros = 0
        while n != 0:
            new_n = n // 5
            zeros += new_n
            n = new_n
        return zeros
        

1.415 - 2023-09-24 09:44:33 +0000 UTC

Factorial Trailing Zeroes

Code

class Solution:
    def trailingZeroes(self, n: int) -> int:
        a, b, zeros = 1, 5, 0
        while (5**a) <= n:
            zeros += n // b
            a += 1
            b *= 5
        return zeros

1.416 - 2023-09-24 09:41:55 +0000 UTC

Pow(x, n)

Code

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n == 0:
            return 1

        if n < 0:
            n *= -1
            x = 1 / x

        result = 1
        while n:
            if n % 2:
                result *= x
                n -= 1
            x *= x
            n //= 2
        
        return result

1.417 - 2023-09-24 09:41:37 +0000 UTC

Plus One

Code

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        carry = 1
        for i in reversed(range(len(digits))):
            new_digit = digits[i] + carry
            if new_digit > 9:
                carry = 1
                new_digit %= 10
            else:
                carry = 0
            digits[i] = new_digit
        
        if carry:
            digits.insert(0, carry)
        
        return digits

1.418 - 2023-09-24 09:40:45 +0000 UTC

Partition List

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
        before_head, after_head = ListNode(0), ListNode(0)
        before_tail, after_tail = before_head, after_head
        
        while head: 
            if head.val < x:
                before_tail.next, before_tail = head, head
            else:
                after_tail.next, after_tail = head, head
            head = head.next
        
        after_tail.next, before_tail.next = None, after_head.next
        
        return before_head.next

1.419 - 2023-09-24 09:40:14 +0000 UTC

Reverse Linked List II

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        cur_node = 1
        left_head, left_tail = head if left > 1 else None, None

        while cur_node < left:
            cur_node += 1
            head, left_tail = head.next, head

        cur_node += 1
        mid_head, mid_tail, head = head, head, head.next
        mid_head.next = None

        while cur_node <= right:
            cur_node += 1
            mid_head, head.next, head = head, mid_head, head.next
    
        mid_tail.next = head
        if left_head:
            left_tail.next = mid_head
        else:
            left_head = mid_head

        return left_head

1.420 - 2023-09-24 09:39:52 +0000 UTC

Copy List with Random Pointer

Code

"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""

class Solution:
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
        
        copied = {None: None}

        def copy_node(node: Node) -> Node:
            if node in copied:
                return copied[node]
            
            new_node = Node(node.val)
            copied[node] = new_node
            new_node.next = copy_node(node.next)
            new_node.random = copy_node(node.random)
            return new_node
        
        return copy_node(head)

1.421 - 2023-09-24 09:38:31 +0000 UTC

Remove Duplicates from Sorted List II

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        tail, before_tail = head, None
        remove_tail = False
        while tail:
            if tail.next and tail.val == tail.next.val:
                tail.next = tail.next.next
                remove_tail = True
                continue
            if not remove_tail:
                before_tail, tail = tail, tail.next
                continue
            remove_tail = False
            if before_tail is None:
                tail = head.next
                head.next, head = None, head.next
            else:
                before_tail.next = tail.next
                tail = tail.next
        return head

1.422 - 2023-09-24 09:09:18 +0000 UTC

Champagne Tower

Code

class Solution:
    def champagneTower(self, poured: int, query_row: int, query_glass: int) -> float:
        if query_row == 0:
            return min(1, poured)
        if query_glass in (0, query_row):
            while query_row and poured:
                poured = (poured - 1) / 2 if poured > 1 else 0
                query_row -= 1
            return min(1, poured)

        cur_row, next_row = [0] * (query_row + 2), [0] * (query_row + 2)
        cur_row[0] = poured
        for row in range(query_row + 1):
            next_row[0] = 0
            for col in range(row + 1):
                overflow = (cur_row[col] - 1) / 2
                if overflow > 0:
                    next_row[col] += overflow
                    next_row[col + 1] = overflow
                else:
                    next_row[col + 1] = 0
            cur_row, next_row = next_row, cur_row
        return min(1, next_row[query_glass])

1.423 - 2023-09-23 18:54:59 +0000 UTC

Remove Nth Node From End of List

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        cur_length, target_length, before_removed = 0, n + 1, head
        tail = head
        while tail and cur_length != target_length:
            tail = tail.next
            cur_length += 1
        if not tail and cur_length != target_length:
            return head.next
        while tail:
            before_removed = before_removed.next
            tail = tail.next
        before_removed.next = before_removed.next.next
        return head

1.424 - 2023-09-23 15:06:03 +0000 UTC

Rotate List

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def rotateRight(self, head: Optional[ListNode], k: int) -> Optional[ListNode]:
        if k == 0 or not head:
            return head
        temp_head, tail, length = head, head, 0
        while temp_head:
            length += 1
            tail, temp_head = temp_head, temp_head.next
        rotation = k % length
        if rotation == 0:
            return head
        new_head_idx = length - rotation
        new_tail_idx = new_head_idx - 1 
        i, new_head, new_tail = 0, None, None
        temp_head = head
        while temp_head:
            if i == new_head_idx:
                new_head = temp_head
                break
            if i == new_tail_idx:
                new_tail = temp_head
            i += 1
            temp_head = temp_head.next
        tail.next = head
        new_tail.next = None
        return new_head

            

1.425 - 2023-09-23 10:19:00 +0000 UTC

Longest String Chain

Code

class Solution:
    def longestStrChain(self, words: List[str]) -> int:
        words.sort(key=len)
        dp = {}
        max_chain = 0
        for word in words:
            dp[word] = 1
            for i in range(len(word)):
                prev_word = word[:i] + word[i+1:]
                if prev_word in dp:
                    dp[word] = max(dp[word], dp[prev_word] + 1)
            max_chain = max(max_chain, dp[word])
        return max_chain

1.426 - 2023-09-22 15:29:58 +0000 UTC

Minimum Bit Flips to Convert Number

Code

class Solution:
    def minBitFlips(self, start: int, goal: int) -> int:
        flips_count = 0
        while start or goal:
            start_is_one, goal_is_one = start & 1, goal & 1
            if start_is_one and not goal_is_one or (not start_is_one and goal_is_one):
                flips_count += 1
            start >>= 1
            goal >>= 1
        return flips_count

1.427 - 2023-09-22 10:51:50 +0000 UTC

Sum of All Subset XOR Totals

Code

class Solution:
    def subsetXORSum(self, nums: List[int]) -> int:
        return reduce(operator.or_, nums) * 1 << (len(nums) - 1)
        

1.428 - 2023-09-22 10:49:11 +0000 UTC

Sum of All Subset XOR Totals

Code

class Solution:
    def subsetXORSum(self, nums: List[int]) -> int:
        subsets_count = 2**(len(nums) - 1)
        return reduce(operator.or_, nums) * subsets_count
        

1.429 - 2023-09-22 09:14:22 +0000 UTC

Longest Nice Substring

Code

class Solution:
    def longestNiceSubstring(self, s: str) -> str:
        sSet = set(s)
        for i in range(len(s)):
            if s[i].lower() not in sSet or s[i].upper() not in sSet:
                lns1 = self.longestNiceSubstring(s[:i])
                lns2 = self.longestNiceSubstring(s[i+1:])

                return max(lns1, lns2, key=len)

        return s

1.430 - 2023-09-22 08:34:42 +0000 UTC

Count the Number of Consistent Strings

Code

class Solution:
    def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
        allowed = set(allowed)
        count = 0
        for word in words:
            if all(char in allowed for char in word):
                count += 1
        return count

1.431 - 2023-09-22 08:27:41 +0000 UTC

Count the Number of Consistent Strings

Code

class Solution:
    def countConsistentStrings(self, allowed: str, words: List[str]) -> int:
        allowed = set(allowed)
        count = 0
        for word in words:
            if not set(word) - allowed:
                count += 1
        return count

1.432 - 2023-09-22 08:23:55 +0000 UTC

XOR Operation in an Array

Code

class Solution:
    def xorOperation(self, n: int, start: int) -> int:
        return reduce(lambda total, i: total ^ (start + 2 * i), chain((0, ), range(n)))

1.433 - 2023-09-22 07:24:39 +0000 UTC

Binary Gap

Code

class Solution:
    def binaryGap(self, n: int) -> int:
        i, first_bit = 0, None
        max_distance = 0
        while n:
            is_one = n & 1 == 1
            if is_one and first_bit is None:
                first_bit = i
            elif is_one:
                max_distance, first_bit = max(max_distance, i - first_bit), i
            n >>= 1
            i += 1
        
        return max_distance 

1.434 - 2023-09-22 05:57:07 +0000 UTC

Is Subsequence

Code

class Solution:
    def isSubsequence(self, s: str, t: str) -> bool:
        i = 0
        length = len(s)
        for char in t:
            if i == length:
                break
            if s[i] == char:
                i += 1
            
        return i == length

1.435 - 2023-09-22 05:51:25 +0000 UTC

Prime Number of Set Bits in Binary Representation

Code

class Solution:
    def countPrimeSetBits(self, left: int, right: int) -> int:
        prime_bits = (2, 3, 5, 7, 11, 13, 17, 19)
        answer = 0
        for num in range(left, right + 1):
            bit_count = num.bit_count()
            if bit_count in prime_bits:
                answer += 1
            
        return answer

1.436 - 2023-09-21 16:36:09 +0000 UTC

Set Mismatch

Code

class Solution:
    def findErrorNums(self, nums: List[int]) -> List[int]:
        length = len(nums)
        # dupl_xor_miss = duplicate ^ missing
        dupl_xor_miss = reduce(lambda total, i: total ^ i ^ nums[i - 1], range(length + 1))
        rightmost_set_bit = dupl_xor_miss & -dupl_xor_miss
        xor_group1 = xor_group2 = 0
        for i in range(1, length + 1):
            if i & rightmost_set_bit:
                xor_group1 ^= i
            else:
                xor_group2 ^= i
            if nums[i - 1] & rightmost_set_bit:
                xor_group1 ^= nums[i - 1]
            else:
                xor_group2 ^= nums[i - 1]
        for num in nums:
            if num == xor_group1:
                return num, xor_group2
            if num == xor_group2:
                return num, xor_group1 
        
        raise Exception()

1.437 - 2023-09-21 16:11:34 +0000 UTC

Set Mismatch

Code

class Solution:
    def findErrorNums(self, nums: List[int]) -> List[int]:
        n = len(nums)
        dupl_xor_miss = 0
        for i in range(1, n+1):
            dupl_xor_miss ^= i ^ nums[i-1]
        
        # example for get rightmost set bit
        # x:             01110000
        # ~x:            10001111
        # -x or ~x + 1:  10010000
        # x & -x:        00010000

        # example for unset rightmost set bit
        # x:             01110000
        # x-1:           01101111
        # x & (x-1):     01100000
        rightmost_set_bit = dupl_xor_miss & -dupl_xor_miss
        xor_group1 = xor_group2 = 0
        for i in range(1, n + 1):
            if i & rightmost_set_bit:
                xor_group1 ^= i
            else:
                xor_group2 ^= i
            if nums[i-1] & rightmost_set_bit:
                xor_group1 ^= nums[i-1]
            else:
                xor_group2 ^= nums[i-1]
        
        for num in nums:
            if num == xor_group1:
                return [num, xor_group2]
            if num == xor_group2:
                return [num, xor_group1]

        return []

1.438 - 2023-09-21 15:33:03 +0000 UTC

Number Complement

Code

class Solution:
    def findComplement(self, num: int) -> int:
        return ~num + (1 << num.bit_length())

1.439 - 2023-09-21 06:51:52 +0000 UTC

Median of Two Sorted Arrays

Code

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        m, n = len(nums1), len(nums2)
        p1, p2 = 0, 0
        
        # Get the smaller value between nums1[p1] and nums2[p2].
        def get_min():
            nonlocal p1, p2
            if p1 < m and p2 < n:
                if nums1[p1] < nums2[p2]:
                    ans = nums1[p1]
                    p1 += 1
                else:
                    ans = nums2[p2]
                    p2 += 1
            elif p2 == n:
                ans = nums1[p1]
                p1 += 1
            else:
                ans = nums2[p2]
                p2 += 1
            return ans
        
        if (m + n) % 2 == 0:
            for _ in range((m + n) // 2 - 1):
                _ = get_min()
            return (get_min() + get_min()) / 2
        else:
            for _ in range((m + n) // 2):
                _ = get_min()
            return get_min()

1.440 - 2023-09-20 19:32:26 +0000 UTC

Sum of Values at Indices With K Set Bits

Code

class Solution:
    def sumIndicesWithKSetBits(self, nums: List[int], k: int) -> int:
        return sum(num for i, num in enumerate(nums) if i.bit_count() == k)

1.441 - 2023-09-20 19:28:16 +0000 UTC

Sort Integers by The Number of 1 Bits

Code

class Solution:
    def sortByBits(self, arr: List[int]) -> List[int]:
        return tuple(num for num in sorted(arr, key=lambda num: (num.bit_count(), num)))

1.442 - 2023-09-20 19:22:48 +0000 UTC

Number of Even and Odd Bits

Code

class Solution:
    def evenOddBit(self, n: int) -> List[int]:
        return (n & 0x55555555).bit_count(), (n & 0xaaaaaaaa).bit_count()

1.443 - 2023-09-20 19:20:17 +0000 UTC

Number of Even and Odd Bits

Code

class Solution:
    def evenOddBit(self, n: int) -> List[int]:
        even, odd = n & 0x55555555, n & 0xaaaaaaaa
        even_count, odd_count = 0, 0
        while even:
            if even & 1 == 1:
                even_count += 1
            even >>= 1
            
        while odd:
            if odd & 1 == 1:
                odd_count += 1
            odd >>= 1
        
        return even_count, odd_count

1.444 - 2023-09-20 16:50:56 +0000 UTC

Binary Number with Alternating Bits

Code

class Solution:
    def hasAlternatingBits(self, n: int) -> bool:
        return n & (n >> 1) == 0 and n & (n >> 2) == n >> 2

1.445 - 2023-09-20 16:35:10 +0000 UTC

Power of Three

Code

class Solution:
    def isPowerOfThree(self, n: int) -> bool:
        #                3 ** 20
        return n > 0 and 3486784401 % n == 0

1.446 - 2023-09-20 16:07:10 +0000 UTC

Power of Two

Code

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        return n > 0 and n & (n - 1) == 0

1.447 - 2023-09-20 15:36:36 +0000 UTC

Power of Four

Code

class Solution:
    def isPowerOfFour(self, n: int) -> bool:
        # Check if the number is greater than zero and is a power of two
        if n > 0 and (n & (n - 1)) == 0:
            # Check if the number is of the form 4^x
            return n & 0x55555555 == n
        else:
            return False

1.448 - 2023-09-20 15:32:58 +0000 UTC

Power of Four

Code

class Solution:
    def isPowerOfFour(self, n: int) -> bool:
        return n and not (n & (n - 1)) and (n & 0x55555555)

1.449 - 2023-09-20 15:32:51 +0000 UTC

Power of Four

Code

class Solution:
    def isPowerOfFour(self, n: int) -> bool:
        return n and not (n & (n - 1)) and (n & 0x55555555)

1.450 - 2023-09-20 15:32:34 +0000 UTC

Power of Four

Code

class Solution:
    def isPowerOfFour(self, n: int) -> bool:
        return n and not (n & (n - 1)) and (n & 0x55555555)

1.451 - 2023-09-20 15:02:39 +0000 UTC

Missing Number

Code

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        def xor(total: int, i: int) -> int:
            return total ^ nums[i] ^ (i + 1)
        return reduce(xor, chain((0, ), range(len(nums))))

1.452 - 2023-09-20 15:01:50 +0000 UTC

Missing Number

Code

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        return reduce(lambda total, i: total ^ nums[i] ^ (i + 1), chain((0, ), range(len(nums))))

1.453 - 2023-09-20 14:28:42 +0000 UTC

Missing Number

Code

class Solution:
    def missingNumber(self, nums: List[int]) -> int:
        length = len(nums)
        return ((length + 1) * length) // 2 - sum(nums)

1.454 - 2023-09-20 14:07:50 +0000 UTC

Reverse Bits

Code

class Solution:
    def reverseBits(self, n: int) -> int:
        # Initialize the reversed number to 0
        reversed_num = 0
        
        # Iterate over all 32 bits of the given number
        for i in range(32):
            # Left shift the reversed number by 1 and add the last bit of the given number to it
            reversed_num = (reversed_num << 1) | (n & 1)
            # remove the last bit from the original number
            n >>= 1
        
        # Return the reversed number
        return reversed_num

1.455 - 2023-09-20 13:31:32 +0000 UTC

Add Binary

Code

class Solution:
    def addBinary(self, a: str, b: str) -> str:
        answer = []
        carry = 0
        for char1, char2 in zip_longest(reversed(a), reversed(b)):
            num1, num2 = int(char1) if char1 else 0, int(char2) if char2 else 0
            cur_sum = num1 + num2 + carry
            carry = 0
            if cur_sum > 1:
                cur_sum -= 2
                carry = 1
            
            answer.append(str(cur_sum))
        
        if carry:
            answer.append("1")

        return "".join(reversed(answer))

1.456 - 2023-09-20 08:47:24 +0000 UTC

Minimum Operations to Reduce X to Zero

Code

class Solution:
    def minOperations(self, nums: List[int], x: int) -> int:
        target, length = sum(nums) - x, len(nums)
        max_len = cur_sum = left = 0
        
        if target == 0:
            return length
        
        for right, val in enumerate(nums):
            cur_sum += val
            while left <= right and cur_sum > target:
                cur_sum -= nums[left]
                left += 1
            if cur_sum == target:
                max_len = max(max_len, right - left + 1)
        
        return length - max_len if max_len else -1

1.457 - 2023-09-19 18:08:16 +0000 UTC

Design Bitset

Code

class Bitset:

    def __init__(self, size: int):
        self.bits = [0] * size
        self.ones_count = 0
        self.do_flip = False
        self.size = size

    def fix(self, idx: int) -> None:
        cur = self.bits[idx]
        if self.do_flip and cur == 1:
            self.ones_count -= 1
            self.bits[idx] = 0
        elif not self.do_flip and cur == 0:
            self.ones_count += 1
            self.bits[idx] = 1

    def unfix(self, idx: int) -> None:
        cur = self.bits[idx]
        if self.do_flip and cur == 0:
            self.ones_count += 1
            self.bits[idx] = 1
        elif not self.do_flip and cur == 1:
            self.ones_count -= 1
            self.bits[idx] = 0

    def flip(self) -> None:
        self.do_flip = not self.do_flip

    def all(self) -> bool:
        return self.count() == self.size

    def one(self) -> bool:
        return self.count() > 0

    def count(self) -> int:
        return self.size - self.ones_count if self.do_flip else self.ones_count

    def toString(self) -> str:
        target = (bit ^ 1 for bit in self.bits) if self.do_flip else self.bits
        return "".join(str(num) for num in target)


# Your Bitset object will be instantiated and called as such:
# obj = Bitset(size)
# obj.fix(idx)
# obj.unfix(idx)
# obj.flip()
# param_4 = obj.all()
# param_5 = obj.one()
# param_6 = obj.count()
# param_7 = obj.toString()

1.458 - 2023-09-19 17:00:19 +0000 UTC

Find the Duplicate Number

Code

class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        freqs = [False] * (10**5 + 1)
        for num in nums:
            if freqs[num] == True:
                return num
            freqs[num] = True

        raise Exception()

1.459 - 2023-09-19 16:58:37 +0000 UTC

Find the Duplicate Number

Code

class Solution:
    def findDuplicate(self, nums: List[int]) -> int:
        freqs = [0] * (10**5 + 1)
        for num in nums:
            freqs[num] += 1
            if freqs[num] > 1:
                return num

        raise Exception()

1.460 - 2023-09-18 12:46:36 +0000 UTC

Product of the Last K Numbers

Code

class ProductOfNumbers:

    def __init__(self):
        self.products = [1]

    def add(self, num: int) -> None:
        if num == 0:
            self.products.clear()
            self.products.append(1)
            return
        self.products.append(num * self.products[-1])

    def getProduct(self, k: int) -> int:
        if len(self.products) - 1 < k:
            return 0
        return self.products[-1] // self.products[-(k + 1)]


# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)

1.461 - 2023-09-18 12:46:14 +0000 UTC

Product of the Last K Numbers

Code

class ProductOfNumbers:

    def __init__(self):
        self.products = [1]

    def add(self, num: int) -> None:
        if num == 0:
            self.products = [1]
            return
        self.products.append(num * self.products[-1])

    def getProduct(self, k: int) -> int:
        if len(self.products) - 1 < k:
            return 0
        return self.products[-1] // self.products[-(k + 1)]


# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)

1.462 - 2023-09-18 12:38:04 +0000 UTC

Product of the Last K Numbers

Code

class ProductOfNumbers:

    def __init__(self):
        self.products, self.last_zero, self.length = [], -1, 0

    def add(self, num: int) -> None:
        if num == 0:
            self.last_zero = self.length
            num = 1
        self.products.append(num * (self.products[-1] if self.products else 1))
        self.length += 1

    def getProduct(self, k: int) -> int:
        first_elem = self.length - k
        if self.last_zero >= first_elem:
            return 0
        if first_elem == 0:
            return self.products[-1]
        return self.products[-1] // self.products[first_elem - 1]


# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)

1.463 - 2023-09-18 12:35:47 +0000 UTC

Product of the Last K Numbers

Code

class ProductOfNumbers:

    def __init__(self):
        self.products, self.zero_indexes = [], []

    def add(self, num: int) -> None:
        if num == 0:
            self.zero_indexes.append(len(self.products))
            num = 1
        new_product = num * (self.products[-1] if self.products else 1)
        self.products.append(new_product)

    def getProduct(self, k: int) -> int:
        first_elem = len(self.products) - k
        if self.zero_indexes and self.zero_indexes[-1] >= first_elem:
            return 0
        if first_elem == 0:
            return self.products[-1]
        return self.products[-1] // self.products[first_elem - 1]


# Your ProductOfNumbers object will be instantiated and called as such:
# obj = ProductOfNumbers()
# obj.add(num)
# param_2 = obj.getProduct(k)

1.464 - 2023-09-18 12:12:57 +0000 UTC

Find Consecutive Integers from a Data Stream

Code

class DataStream:

    def __init__(self, value: int, k: int):
        self.required, self.value, self.value_count = k, value, 0

    def consec(self, num: int) -> bool:
        if num != self.value:
            self.value_count = 0
            return False
        self.value_count += 1
        return self.value_count >= self.required


# Your DataStream object will be instantiated and called as such:
# obj = DataStream(value, k)
# param_1 = obj.consec(num)

1.465 - 2023-09-18 12:12:07 +0000 UTC

Find Consecutive Integers from a Data Stream

Code

class DataStream:

    def __init__(self, value: int, k: int):
        self.required, self.value, self.value_count = k, value, 0
        

    def consec(self, num: int) -> bool:
        if num != self.value:
            self.value_count = 0
            return False
        
        self.value_count += 1
        return self.value_count >= self.required


# Your DataStream object will be instantiated and called as such:
# obj = DataStream(value, k)
# param_1 = obj.consec(num)

1.466 - 2023-09-18 12:00:25 +0000 UTC

Smallest Number in Infinite Set

Code

class SmallestInfiniteSet:

    def __init__(self):
        self.heap, self.next_num, self.nums = [], 1, set() 

    def popSmallest(self) -> int:
        if self.heap:
            val = heappop(self.heap)
            self.nums.remove(val)
            return val
        self.next_num += 1
        return self.next_num - 1

    def addBack(self, num: int) -> None:
        if num in self.nums or num >= self.next_num:
            return
        self.nums.add(num)
        heappush(self.heap, num)


# Your SmallestInfiniteSet object will be instantiated and called as such:
# obj = SmallestInfiniteSet()
# param_1 = obj.popSmallest()
# obj.addBack(num)

1.467 - 2023-09-18 11:59:16 +0000 UTC

Smallest Number in Infinite Set

Code

class SmallestInfiniteSet:

    def __init__(self):
        self.heap, self.next_num, self.nums = [], 1, set() 


    def popSmallest(self) -> int:
        if not self.heap:
            self.next_num += 1
            return self.next_num - 1
            
        val = heappop(self.heap)
        if val < self.next_num:
            self.nums.remove(val)
            return val
        heappush(self.heap, val)
        self.next_num += 1
        return self.next_num - 1
        

    def addBack(self, num: int) -> None:
        if num in self.nums or num >= self.next_num:
            return
        self.nums.add(num)
        heappush(self.heap, num)


# Your SmallestInfiniteSet object will be instantiated and called as such:
# obj = SmallestInfiniteSet()
# param_1 = obj.popSmallest()
# obj.addBack(num)

1.468 - 2023-09-18 11:37:29 +0000 UTC

Find Elements in a Contaminated Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class FindElements:

    def __init__(self, root: Optional[TreeNode]):
        root.val = 0
        nodes = [root]
        self.values = set((0, )) 
        while nodes:
            node = nodes.pop()
            if node.left:
                val = 2 * node.val + 1
                node.left.val = val
                nodes.append(node.left)
                self.values.add(val)
            if node.right:
                val = 2 * node.val + 2
                node.right.val = val
                nodes.append(node.right)
                self.values.add(val)

    def find(self, target: int) -> bool:
        return target in self.values

# Your FindElements object will be instantiated and called as such:
# obj = FindElements(root)
# param_1 = obj.find(target)

1.469 - 2023-09-18 11:34:48 +0000 UTC

Find Elements in a Contaminated Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class FindElements:

    def __init__(self, root: Optional[TreeNode]):
        self.root = root
        root.val = 0
        nodes = [root]
        while nodes:
            node = nodes.pop()
            new_val = 2 * node.val
            if node.left:
                node.left.val = new_val + 1
                nodes.append(node.left)
            if node.right:
                node.right.val = new_val + 2
                nodes.append(node.right)

    def dfs(self, node: TreeNode, target: int) -> bool:
        if not node or node.val > target:
            return False
        if node.val == target:
            return True
        return self.dfs(node.left, target) or self.dfs(node.right, target)

    def find(self, target: int) -> bool:
        return self.dfs(self.root, target)

# Your FindElements object will be instantiated and called as such:
# obj = FindElements(root)
# param_1 = obj.find(target)

1.470 - 2023-09-18 10:54:11 +0000 UTC

Range Frequency Queries

Code

class RangeFreqQuery:
    def __init__(self, arr: List[int]):
        self.l = [[] for _ in range(10001)]
        for i, v in enumerate(arr):
            self.l[v].append(i)
            
    def query(self, left: int, right: int, v: int) -> int:
        return bisect_right(self.l[v], right) - bisect_left(self.l[v], left)

# Your RangeFreqQuery object will be instantiated and called as such:
# obj = RangeFreqQuery(arr)
# param_1 = obj.query(left,right,value)

1.471 - 2023-09-18 06:47:53 +0000 UTC

The K Weakest Rows in a Matrix

Code

class Solution:
    def kWeakestRows(self, mat: List[List[int]], k: int) -> List[int]:
        rows_count, cols_count = len(mat), len(mat[0])
        heap = []

        for i, row in enumerate(mat):
            count = 0
            for j, val in enumerate(row):
                if val == 0:
                    count = j
                    break
            else:
                count = cols_count
        
            heappush(heap, (count, i))
        
        return tuple(item[1] for item in nsmallest(k, heap))

1.472 - 2023-09-17 13:27:05 +0000 UTC

Implement Magic Dictionary

Code

class MagicDictionary:

    def __init__(self):
        self.dict = []

    def buildDict(self, dictionary: List[str]) -> None:
        self.dict = dictionary

    def search(self, searchWord: str) -> bool:
        target_length = len(searchWord)
        for word in self.dict:
            if len(word) != target_length or word == searchWord:
                continue
            found_diff = False
            for i in range(target_length):
                if word[i] == searchWord[i]:
                    continue
                if found_diff:
                    break

                found_diff = True
            else:
                return True

        return False

# Your MagicDictionary object will be instantiated and called as such:
# obj = MagicDictionary()
# obj.buildDict(dictionary)
# param_2 = obj.search(searchWord)

1.473 - 2023-09-17 13:16:53 +0000 UTC

Encode and Decode TinyURL

Code

class Codec:

    def __init__(self):
        self.urls = []

    def encode(self, longUrl: str) -> str:
        """Encodes a URL to a shortened URL.
        """
        self.urls.append(longUrl)
        return len(self.urls)
        

    def decode(self, shortUrl: str) -> str:
        """Decodes a shortened URL to its original URL.
        """
        return self.urls[shortUrl - 1]
        

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))

1.474 - 2023-09-17 13:14:59 +0000 UTC

Encode and Decode TinyURL

Code

class Codec:

    def __init__(self):
        self.urls = {}
        self.id = 0

    def encode(self, longUrl: str) -> str:
        """Encodes a URL to a shortened URL.
        """
        id = self.id
        self.urls[id] = longUrl
        self.id += 1
        return id
        

    def decode(self, shortUrl: str) -> str:
        """Decodes a shortened URL to its original URL.
        """
        return self.urls[int(shortUrl)]
        

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))

1.475 - 2023-09-17 13:12:53 +0000 UTC

Encode and Decode TinyURL

Code

class Codec:

    def __init__(self):
        self.urls = []

    def encode(self, longUrl: str) -> str:
        """Encodes a URL to a shortened URL.
        """
        self.urls.append(longUrl)
        return str(len(self.urls) - 1)
        

    def decode(self, shortUrl: str) -> str:
        """Decodes a shortened URL to its original URL.
        """
        return self.urls[int(shortUrl)]
        

# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.decode(codec.encode(url))

1.476 - 2023-09-17 13:08:12 +0000 UTC

Design Twitter

Code

class Twitter:

    def __init__(self):
        self.tweets = []
        self.following = defaultdict(set)

    def postTweet(self, userId: int, tweetId: int) -> None:
        self.tweets.append((userId, tweetId))

    def getNewsFeed(self, userId: int) -> List[int]:
        tweets, following = [], self.following[userId]
        for poster, tweet in reversed(self.tweets):
            if poster != userId and poster not in following:
                continue
            tweets.append(tweet)
            if len(tweets) == 10:
                break
            
        return tweets

    def follow(self, followerId: int, followeeId: int) -> None:
        self.following[followerId].add(followeeId)

    def unfollow(self, followerId: int, followeeId: int) -> None:
        self.following[followerId].discard(followeeId)

# Your Twitter object will be instantiated and called as such:
# obj = Twitter()
# obj.postTweet(userId,tweetId)
# param_2 = obj.getNewsFeed(userId)
# obj.follow(followerId,followeeId)
# obj.unfollow(followerId,followeeId)

1.477 - 2023-09-17 08:45:39 +0000 UTC

Shortest Path Visiting All Nodes

Code

from collections import deque, namedtuple

class Solution:
    def shortestPathLength(self, graph):
        n = len(graph)
        all_mask = (1 << n) - 1
        visited = set()
        Node = namedtuple('Node', ['node', 'mask', 'cost'])

        q = deque()
        for i in range(n):
            mask_value = (1 << i)
            this_node = Node(i, mask_value, 1)
            q.append(this_node)
            visited.add((i, mask_value))

        while q:
            curr = q.popleft()

            if curr.mask == all_mask:
                return curr.cost - 1

            for adj in graph[curr.node]:
                both_visited_mask = curr.mask | (1 << adj)
                this_node = Node(adj, both_visited_mask, curr.cost + 1)

                if (adj, both_visited_mask) not in visited:
                    visited.add((adj, both_visited_mask))
                    q.append(this_node)

        return -1

1.478 - 2023-09-17 08:44:04 +0000 UTC

Implement Trie (Prefix Tree)

Code

class Trie:

    def __init__(self):
        self.root = {}

    def insert(self, word: str) -> None:
        cur = self.root
        for char in word:
            if char not in cur:
                cur[char] = {}
            cur = cur[char]
        
        cur["_is_word"] = None

    def search(self, word: str) -> bool:
        cur = self.root
        for char in word:
            if char not in cur:
                return False
            cur = cur[char]
        
        return "_is_word" in cur

    def startsWith(self, prefix: str) -> bool:
        cur = self.root
        for char in prefix:
            if char not in cur:
                return False
            cur = cur[char]
            
        return True


# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)

1.479 - 2023-09-17 08:40:01 +0000 UTC

Implement Trie (Prefix Tree)

Code

class Node:
    def __init__(self):
        self.ch, self.is_word = [None] * 128, False

class Trie:

    def __init__(self):
        self.head = Node()

    def insert(self, word: str) -> None:
        cur_node = self.head
        for i in range(len(word)):
            char = ord(word[i])
            if cur_node.ch[char] is None:
                cur_node.ch[char] = Node()
            cur_node = cur_node.ch[char]
        cur_node.is_word = True

    def search(self, word: str) -> bool:
        cur_node = self.head
        for i in range(len(word)):
            char = ord(word[i])
            if cur_node.ch[char] is None:
                return False
            cur_node = cur_node.ch[char]
        
        return cur_node.is_word

    def startsWith(self, prefix: str) -> bool:
        cur_node = self.head
        for i in range(len(prefix)):
            char = ord(prefix[i])
            if cur_node.ch[char] is None:
                return False
            cur_node = cur_node.ch[char]
        
        return True


# Your Trie object will be instantiated and called as such:
# obj = Trie()
# obj.insert(word)
# param_2 = obj.search(word)
# param_3 = obj.startsWith(prefix)

1.480 - 2023-09-16 18:10:06 +0000 UTC

Apply Discount Every n Orders

Code

class Cashier:

    def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):
        self.freq, self.discount = n, (100 - discount) / 100
        self.cur = 0
        self.products = {id: price for id, price in zip(products, prices)}

    def getBill(self, product: List[int], amount: List[int]) -> float:
        self.cur += 1
        total = sum(amount[i] * self.products[product[i]] for i in range(len(product)))
        if self.cur < self.freq:
            return total
        self.cur = 0
        return total * self.discount
        


# Your Cashier object will be instantiated and called as such:
# obj = Cashier(n, discount, products, prices)
# param_1 = obj.getBill(product,amount)

1.481 - 2023-09-16 18:07:33 +0000 UTC

Apply Discount Every n Orders

Code

class Cashier:

    def __init__(self, n: int, discount: int, products: List[int], prices: List[int]):
        self.freq, self.discount = n, (100 - discount) / 100
        self.cur = 0
        self.products = {id: price for id, price in zip(products, prices)}

    def getBill(self, product: List[int], amount: List[int]) -> float:
        self.cur += 1
        multiplier = 1
        if self.cur == self.freq:
            self.cur, multiplier = 0, self.discount
        total = sum(amount[i] * self.products[product[i]] for i in range(len(product)))
        return total * multiplier
        


# Your Cashier object will be instantiated and called as such:
# obj = Cashier(n, discount, products, prices)
# param_1 = obj.getBill(product,amount)

1.482 - 2023-09-16 17:44:34 +0000 UTC

Design Underground System

Code

class UndergroundSystem:

    def __init__(self):
        self.from_to = defaultdict(lambda: defaultdict(list))
        self.in_transit = {}

    def checkIn(self, id: int, stationName: str, t: int) -> None:
        self.in_transit[id] = (stationName, t)

    def checkOut(self, id: int, stationName: str, t: int) -> None:
        station_from, time_from = self.in_transit.pop(id)
        self.from_to[station_from][stationName].append(t - time_from)

    def getAverageTime(self, startStation: str, endStation: str) -> float:
        times = self.from_to[startStation][endStation]
        return sum(times) / len(times)


# Your UndergroundSystem object will be instantiated and called as such:
# obj = UndergroundSystem()
# obj.checkIn(id,stationName,t)
# obj.checkOut(id,stationName,t)
# param_3 = obj.getAverageTime(startStation,endStation)

1.483 - 2023-09-16 17:20:21 +0000 UTC

Design an Ordered Stream

Code

class OrderedStream:

    def __init__(self, n: int):
        self.data = [None]*n
        self.ptr = 0 # 0-indexed 

    def insert(self, id: int, value: str) -> List[str]:
        id -= 1 # 0-indexed 
        self.data[id] = value 
        if id > self.ptr: return [] # not reaching ptr 
        
        while self.ptr < len(self.data) and self.data[self.ptr]: self.ptr += 1 # update self.ptr 
        return self.data[id:self.ptr]



# Your OrderedStream object will be instantiated and called as such:
# obj = OrderedStream(n)
# param_1 = obj.insert(idKey,value)

1.484 - 2023-09-16 17:18:19 +0000 UTC

Design an Ordered Stream

Code

class OrderedStream:

    def __init__(self, n: int):
        self.values = [None] * n
        self.length = n
        self.cur = 0

    def insert(self, idKey: int, value: str) -> List[str]:
        self.values[idKey - 1] = value
        for i in range(self.cur, self.length):
            if self.values[i] is not None:
                continue
            
            self.cur, answer = i, self.values[self.cur:i]
            return answer

        return self.values[self.cur:]



# Your OrderedStream object will be instantiated and called as such:
# obj = OrderedStream(n)
# param_1 = obj.insert(idKey,value)

1.485 - 2023-09-16 12:46:43 +0000 UTC

Design Authentication Manager

Code

class AuthenticationManager:

    def __init__(self, timeToLive: int):
        self.ttl = timeToLive
        self.tokens = {}

    def generate(self, tokenId: str, currentTime: int) -> None:
        self.tokens[tokenId] = currentTime + self.ttl

    def renew(self, tokenId: str, currentTime: int) -> None:
        if currentTime < self.tokens.get(tokenId, currentTime):
            self.generate(tokenId, currentTime)
        else:
            self.tokens.pop(tokenId, None)

    def countUnexpiredTokens(self, currentTime: int) -> int:
        count = 0
        remove_tokens = []
        for token, expir_time in self.tokens.items():
            if currentTime < expir_time:
                count += 1
            else:
                remove_tokens.append(token)
        
        for token in remove_tokens:
            self.tokens.pop(token)
        
        return count


# Your AuthenticationManager object will be instantiated and called as such:
# obj = AuthenticationManager(timeToLive)
# obj.generate(tokenId,currentTime)
# obj.renew(tokenId,currentTime)
# param_3 = obj.countUnexpiredTokens(currentTime)

1.486 - 2023-09-16 12:35:37 +0000 UTC

Seat Reservation Manager

Code

class SeatManager:

    def __init__(self, n: int):
        self.heap = list(range(1, n + 1))  

    def reserve(self) -> int:
        return heappop(self.heap)

    def unreserve(self, seatNumber: int) -> None:
        heappush(self.heap, seatNumber)


# Your SeatManager object will be instantiated and called as such:
# obj = SeatManager(n)
# param_1 = obj.reserve()
# obj.unreserve(seatNumber)

1.487 - 2023-09-16 12:34:15 +0000 UTC

Seat Reservation Manager

Code

class SeatManager:

    def __init__(self, n: int):
        self.heap = list(range(1, n + 1))
        heapify(self.heap)        

    def reserve(self) -> int:
        return heappop(self.heap)

    def unreserve(self, seatNumber: int) -> None:
        heappush(self.heap, seatNumber)


# Your SeatManager object will be instantiated and called as such:
# obj = SeatManager(n)
# param_1 = obj.reserve()
# obj.unreserve(seatNumber)

1.488 - 2023-09-16 08:35:52 +0000 UTC

Simple Bank System

Code

class Bank:

    def __init__(self, balance: List[int]):
        self.balance = balance
        self.size = len(balance)

    def transfer(self, account1: int, account2: int, money: int) -> bool:
        if not 0 < account1 <= self.size or not 0 < account2 <= self.size or (
            self.balance[account1-1] < money
        ):
            return False
        self.balance[account2-1] += money
        self.balance[account1-1] -= money
        return True

    def deposit(self, account: int, money: int) -> bool:
        if not 0 < account <= self.size:
            return False
        self.balance[account-1] += money
        return True

    def withdraw(self, account: int, money: int) -> bool:
        if not 0 < account <= self.size or self.balance[account-1] < money:
            return False
        self.balance[account-1] -= money
        return True


# Your Bank object will be instantiated and called as such:
# obj = Bank(balance)
# param_1 = obj.transfer(account1,account2,money)
# param_2 = obj.deposit(account,money)
# param_3 = obj.withdraw(account,money)

1.489 - 2023-09-16 08:25:54 +0000 UTC

Path With Minimum Effort

Code

class Solution:

    def minimumEffortPath(self, heights: List[List[int]]) -> int:
        rows, cols = len(heights), len(heights[0])
        directions = [(0, 1), (0, -1), (1, 0), (-1, 0)]
        dist = [[math.inf for _ in range(cols)] for _ in range(rows)]
        dist[0][0] = 0
        minHeap = [(0, 0, 0)] 
        while minHeap:
            effort, x, y = heappop(minHeap)
            if x == rows - 1 and y == cols - 1:
                return effort
            for dx, dy in directions:
                nx, ny = x + dx, y + dy
                if 0 <= nx < rows and 0 <= ny < cols:
                    new_effort = max(effort, abs(heights[x][y] - heights[nx][ny]))
                    if new_effort < dist[nx][ny]:
                        dist[nx][ny] = new_effort
                        heappush(minHeap, (new_effort, nx, ny))

1.490 - 2023-09-15 16:59:56 +0000 UTC

Design a Number Container System

Code

class NumberContainers:

    def __init__(self):
        self.num_indices = defaultdict(list)
        self.num_at_index = {}
        

    def change(self, index: int, number: int) -> None:
        self.num_at_index[index] = number
        heapq.heappush(self.num_indices[number], index)
        

    def find(self, number: int) -> int:
        while self.num_indices[number] and self.num_at_index[self.num_indices[number][0]] != number:
            heapq.heappop(self.num_indices[number])
        
        return self.num_indices[number][0] if len(self.num_indices[number]) > 0 else -1
        


# Your NumberContainers object will be instantiated and called as such:
# obj = NumberContainers()
# obj.change(index,number)
# param_2 = obj.find(number)

1.491 - 2023-09-15 16:53:02 +0000 UTC

Design a Number Container System

Code

import sortedcontainers

class NumberContainers:

    def __init__(self):
        self._idx_number = {}
        self._number_idx = defaultdict(sortedcontainers.SortedSet)

    def change(self, index: int, number: int) -> None:
        cur_number = self._idx_number.get(index, -1)
        if cur_number != -1:
            self._number_idx[cur_number].remove(index)
        self._idx_number[index] = number
        self._number_idx[number].add(index)

    def find(self, number: int) -> int:
        ids = self._number_idx[number]
        return ids[0] if ids else -1


# Your NumberContainers object will be instantiated and called as such:
# obj = NumberContainers()
# obj.change(index,number)
# param_2 = obj.find(number)

1.492 - 2023-09-15 16:34:44 +0000 UTC

Finding Pairs With a Certain Sum

Code

class FindSumPairs:

    def __init__(self, nums1: List[int], nums2: List[int]):
        self._nums1, self._nums2, self._nums2_raw = Counter(nums1), Counter(nums2), nums2

    def add(self, index: int, val: int) -> None:
        nums2_raw, nums2 = self._nums2_raw, self._nums2
        cur_val = nums2_raw[index]
        new_val = cur_val + val
        if nums2[cur_val] > 0:
            nums2[cur_val] -= 1
        
        nums2_raw[index] = new_val
        nums2[new_val] += 1

    def count(self, tot: int) -> int:       
        return sum(num1_count * self._nums2.get(tot - num1, 0) 
                   for num1, num1_count in self._nums1.items())


# Your FindSumPairs object will be instantiated and called as such:
# obj = FindSumPairs(nums1, nums2)
# obj.add(index,val)
# param_2 = obj.count(tot)

1.493 - 2023-09-15 16:33:23 +0000 UTC

Finding Pairs With a Certain Sum

Code

class FindSumPairs:

    def __init__(self, nums1: List[int], nums2: List[int]):
        self._nums1, self._nums2, self._nums2_raw = Counter(nums1), Counter(nums2), nums2

    def add(self, index: int, val: int) -> None:
        nums2_raw, nums2 = self._nums2_raw, self._nums2
        cur_val = nums2_raw[index]
        new_val = cur_val + val
        if nums2[cur_val] > 0:
            nums2[cur_val] -= 1
        
        nums2_raw[index] = new_val
        nums2[new_val] += 1

    def count(self, tot: int) -> int:
        sum_count = 0
        nums2 = self._nums2
        for num1, num1_count in self._nums1.items():
            sum_count += num1_count * nums2.get(tot - num1, 0) 

        return sum_count


# Your FindSumPairs object will be instantiated and called as such:
# obj = FindSumPairs(nums1, nums2)
# obj.add(index,val)
# param_2 = obj.count(tot)

1.494 - 2023-09-15 16:12:52 +0000 UTC

Design Browser History

Code

class BrowserHistory:

    def __init__(self, homepage: str):
        self._history = [homepage]
        self._cur = 0

    def visit(self, url: str) -> None:
        self._history[self._cur+1:] = (url, )
        self._cur += 1

    def back(self, steps: int) -> str:
        self._cur = max(0, self._cur - steps)
        return self._history[self._cur]

    def forward(self, steps: int) -> str:
        self._cur = min(len(self._history) - 1, self._cur + steps)
        return self._history[self._cur]


# Your BrowserHistory object will be instantiated and called as such:
# obj = BrowserHistory(homepage)
# obj.visit(url)
# param_2 = obj.back(steps)
# param_3 = obj.forward(steps)

1.495 - 2023-09-15 16:05:16 +0000 UTC

Design a Stack With Increment Operation

Code

class CustomStack:

    def __init__(self, maxSize: int):
        self._stack = []
        self._max_size = maxSize

    def push(self, x: int) -> None:
        if len(self._stack) != self._max_size:
            self._stack.append(x)

    def pop(self) -> int:
        return self._stack.pop() if self._stack else -1 
        
    def increment(self, k: int, val: int) -> None:
        for i in range(min(k, len(self._stack))):
            self._stack[i] += val


# Your CustomStack object will be instantiated and called as such:
# obj = CustomStack(maxSize)
# obj.push(x)
# param_2 = obj.pop()
# obj.increment(k,val)

1.496 - 2023-09-15 16:02:42 +0000 UTC

Design a Stack With Increment Operation

Code

class CustomStack:

    def __init__(self, maxSize: int):
        self._stack = []
        self._max_size = maxSize
        self._size = 0

    def push(self, x: int) -> None:
        if self._size == self._max_size:
            return
        self._stack.append(x)
        self._size += 1

    def pop(self) -> int:
        if self._size == 0:
            return -1
        last = self._stack.pop()
        self._size -= 1
        return last

    def increment(self, k: int, val: int) -> None:
        for i in range(min(k, self._size)):
            self._stack[i] += val


# Your CustomStack object will be instantiated and called as such:
# obj = CustomStack(maxSize)
# obj.push(x)
# param_2 = obj.pop()
# obj.increment(k,val)

1.497 - 2023-09-15 15:53:00 +0000 UTC

Design Linked List

Code

class Node:
    def __init__(self, val: int = 0, prev_node: 'Node' = None, next_node: 'Node' = None):
        self.val, self.prev, self.next = val, prev_node, next_node

class MyLinkedList:

    def __init__(self):
        self._head, self._tail = Node(float("-inf")), Node(float("inf"))
        self._head.next, self._tail.prev = self._tail, self._head
        self._length = 0

    def _getNode(self, index: int) -> Node:
        if not 0 <= index < self._length:
            return None
        if index == 0:
            return self._head.next
        if index == self._length - 1:
            return self._tail.prev

        cur_idx, cur_node = 0, self._head.next
        while cur_idx < index:
            cur_node = cur_node.next
            cur_idx += 1

        return cur_node
    
    def get(self, index: int) -> int:
        node = self._getNode(index)
        return node.val if node else -1

    def addAtHead(self, val: int) -> None:
        old_first = self._head.next
        new_node = Node(val, self._head, old_first)
        self._head.next, old_first.prev = new_node, new_node
        self._length += 1

    def addAtTail(self, val: int) -> None:
        old_tail = self._tail.prev
        new_node = Node(val, old_tail, self._tail)
        self._tail.prev, old_tail.next = new_node, new_node
        self._length += 1

    def addAtIndex(self, index: int, val: int) -> None:
        if not 0 <= index <= self._length:
            return
        if index == 0:
            self.addAtHead(val)
            return
        if index == self._length:
            self.addAtTail(val)
            return
        
        target_node = self._getNode(index)
        prev_node = target_node.prev
        new_node = Node(val, prev_node, target_node)
        prev_node.next, target_node.prev = new_node, new_node
        self._length += 1

    def deleteAtIndex(self, index: int) -> None:
        if not 0 <= index < self._length:
            return
        
        target_node = self._getNode(index)
        old_prev, old_next = target_node.prev, target_node.next
        old_prev.next, old_next.prev = old_next, old_prev
        self._length -= 1

# Your MyLinkedList object will be instantiated and called as such:
# obj = MyLinkedList()
# param_1 = obj.get(index)
# obj.addAtHead(val)
# obj.addAtTail(val)
# obj.addAtIndex(index,val)
# obj.deleteAtIndex(index)

1.498 - 2023-09-15 14:07:59 +0000 UTC

Range Sum Query 2D - Immutable

Code

class NumMatrix:

    def __init__(self, matrix: List[List[int]]):
        self.dp=[[0] * (len(matrix[0])+1) for _ in range(len(matrix)+1)]
        
		# calculate prefix sum
        for r in range(len(self.dp)-1):
            for c in range(len(self.dp[0])-1):
                self.dp[r+1][c+1]=matrix[r][c] + self.dp[r][c+1] + self.dp[r+1][c] - self.dp[r][c]
        
    def sumRegion(self, row1: int, col1: int, row2: int, col2: int) -> int:
        return self.dp[row2+1][col2+1] - self.dp[row1][col2+1] - self.dp[row2+1][col1] + self.dp[row1][col1]
                

1.499 - 2023-09-15 09:51:11 +0000 UTC

Peeking Iterator

Code

# Below is the interface for Iterator, which is already defined for you.
#
# class Iterator:
#     def __init__(self, nums):
#         """
#         Initializes an iterator object to the beginning of a list.
#         :type nums: List[int]
#         """
#
#     def hasNext(self):
#         """
#         Returns true if the iteration has more elements.
#         :rtype: bool
#         """
#
#     def next(self):
#         """
#         Returns the next element in the iteration.
#         :rtype: int
#         """

class PeekingIterator:
    def __init__(self, iterator):
        """
        Initialize your data structure here.
        :type iterator: Iterator
        """
        self._iter = iterator
        self._next = iterator.next()
        

    def peek(self):
        """
        Returns the next element in the iteration without advancing the iterator.
        :rtype: int
        """
        return self._next
        

    def next(self):
        """
        :rtype: int
        """
        cur_next = self._next
        self._next = self._iter.next() if self._iter.hasNext() else None
        return cur_next
        

    def hasNext(self):
        """
        :rtype: bool
        """
        return self._next is not None
        

# Your PeekingIterator object will be instantiated and called as such:
# iter = PeekingIterator(Iterator(nums))
# while iter.hasNext():
#     val = iter.peek()   # Get the next element but not advance the iterator.
#     iter.next()         # Should return the same value as [val].

1.500 - 2023-09-15 06:59:15 +0000 UTC

Min Cost to Connect All Points

Code

def manhattan_distance(p1: List[int], p2: List[int]) -> int:
    return abs(p1[0] - p2[0]) + abs(p1[1] - p2[1])

class Solution:
    def minCostConnectPoints(self, points: List[List[int]]) -> int:
        n = len(points)
        visited = [False] * n
        heap_dict = {0: 0}  
        min_heap = [(0, 0)]
        
        mst_weight = 0
        
        while min_heap:
            w, u = heappop(min_heap)
            
            if visited[u] or heap_dict.get(u, float('inf')) < w:
                continue
            
            visited[u] = True
            mst_weight += w
            
            for v in range(n):
                if not visited[v]:
                    new_distance = manhattan_distance(points[u], points[v])
      
                    if new_distance < heap_dict.get(v, float('inf')):
                        heap_dict[v] = new_distance
                        heappush(min_heap, (new_distance, v))
        
        return mst_weight

1.501 - 2023-09-14 16:02:15 +0000 UTC

Frequency Tracker

Code

class FrequencyTracker:

    def __init__(self):
        self._num_freq = defaultdict(int)
        self._freq_nums = defaultdict(set)    

    def add(self, number: int) -> None:
        cur_freq = self._num_freq[number]
        self._num_freq[number] = cur_freq + 1
        self._freq_nums[cur_freq].discard(number)
        self._freq_nums[cur_freq + 1].add(number)

    def deleteOne(self, number: int) -> None:
        cur_freq = self._num_freq[number]
        if cur_freq == 0:
            return    
        self._num_freq[number] = cur_freq - 1 
        self._freq_nums[cur_freq].discard(number)
        if cur_freq != 1:
            self._freq_nums[cur_freq - 1].add(number)

    def hasFrequency(self, frequency: int) -> bool:
        return len(self._freq_nums[frequency]) != 0


# Your FrequencyTracker object will be instantiated and called as such:
# obj = FrequencyTracker()
# obj.add(number)
# obj.deleteOne(number)
# param_3 = obj.hasFrequency(frequency)

1.502 - 2023-09-14 15:45:02 +0000 UTC

Design an ATM Machine

Code

class ATM:

    def __init__(self):
        self._banknotes = (0, ) * 5
        self._values = (20, 50, 100, 200, 500)

    def deposit(self, banknotesCount: List[int]) -> None:
        self._banknotes = tuple(banknotesCount[i] + self._banknotes[i] for i in range(5))

    def withdraw(self, amount: int) -> List[int]:
        withdrawn = [0] * 5
        for i in reversed(range(5)):
            value, notes_left = self._values[i], self._banknotes[i]
            notes_need = min(notes_left, amount // value)
            
            if notes_need == 0:
                continue
            
            amount -= value * notes_need
            withdrawn[i] = notes_need

            if amount == 0:
                self._banknotes = tuple(self._banknotes[i] - withdrawn[i] 
                                        for i in range(5))
                return withdrawn

        return (-1, )


# Your ATM object will be instantiated and called as such:
# obj = ATM()
# obj.deposit(banknotesCount)
# param_2 = obj.withdraw(amount)

1.503 - 2023-09-14 15:44:27 +0000 UTC

Design an ATM Machine

Code

class ATM:

    def __init__(self):
        self._banknotes = (0, ) * 5
        self._values = (20, 50, 100, 200, 500)

    def deposit(self, banknotesCount: List[int]) -> None:
        self._banknotes = tuple(banknotesCount[i] + self._banknotes[i] for i in range(5))

    def withdraw(self, amount: int) -> List[int]:
        withdrawn = [0] * 5
        for i in reversed(range(5)):
            value, notes_left = self._values[i], self._banknotes[i]
            notes_need = min(notes_left, amount // value)
            
            if notes_need == 0:
                continue
            
            amount -= value * notes_need
            withdrawn[i] = notes_need

            if amount == 0:
                self._banknotes = tuple(self._banknotes[i] - withdrawn[i] 
                                        for i in range(5))
                return withdrawn

        return (-1, )


# Your ATM object will be instantiated and called as such:
# obj = ATM()
# obj.deposit(banknotesCount)
# param_2 = obj.withdraw(amount)

1.504 - 2023-09-14 15:40:55 +0000 UTC

Design an ATM Machine

Code

class ATM:

    def __init__(self):
        self._banknotes = [0] * 5
        self._values = (20, 50, 100, 200, 500)

    def deposit(self, banknotesCount: List[int]) -> None:
        for i in range(5):
            self._banknotes[i] += banknotesCount[i]

    def withdraw(self, amount: int) -> List[int]:
        withdrawn = [0] * 5
        for i in reversed(range(5)):
            value, notes_left = self._values[i], self._banknotes[i]
            notes_need = min(notes_left, amount // value)
            
            if notes_need == 0:
                continue
            
            amount -= value * notes_need
            withdrawn[i] = notes_need

            if amount == 0:
                for i in range(5):
                    self._banknotes[i] -= withdrawn[i]
                return withdrawn

        return [-1]


# Your ATM object will be instantiated and called as such:
# obj = ATM()
# obj.deposit(banknotesCount)
# param_2 = obj.withdraw(amount)

1.505 - 2023-09-14 15:08:10 +0000 UTC

Design Memory Allocator

Code

class Allocator:

    def __init__(self, n: int):
      self._units = [1] * n
      self._units[0] = n
      self._id_units = defaultdict(list)
      self._units_count = n

    def find_avail_units(self, start: int, size: int) -> Tuple[int, int]:
        i = start
        count = 0
        while i < self._units_count and i - start < size:
            units_avail = self._units[i]
            if units_avail < 0:
                return i + units_avail if i == start else i, count
            i += units_avail
            count += units_avail

        return i, count
            

    def allocate(self, size: int, mID: int) -> int:
        i = 0
        units_start, units_count = None, 0
        while i < self._units_count and units_count < size:
            units_avail = self._units[i]
            if units_avail < 0:
                i += -units_avail
                units_start, units_count = None, 0
                continue

            if units_start is None:
                units_start = i
            units_count += units_avail
            i += units_avail

        if units_count < size:
            return -1 

        self._units[units_start] = -size
        if units_count > size:
            self._units[units_start + size] = units_count - size
        self._id_units[mID].append(units_start)
        return units_start

    def free(self, mID: int) -> int:
        count = 0
        conseq_units = self._id_units[mID]
        while conseq_units:
            units_start = conseq_units.pop()
            units_freed = -self._units[units_start]
            count += units_freed
            self._units[units_start] = units_freed

        return count


# Your Allocator object will be instantiated and called as such:
# obj = Allocator(n)
# param_1 = obj.allocate(size,mID)
# param_2 = obj.free(mID)

1.506 - 2023-09-14 11:41:43 +0000 UTC

Reconstruct Itinerary

Code

class Solution:
    def findItinerary(self, tickets: List[List[str]]) -> List[str]:
        graph = defaultdict(list)
        
        for src, dst in sorted(tickets, reverse=True):
            graph[src].append(dst)
            
        itinerary = []
        def dfs(airport: str) -> None:
            while graph[airport]:
                dfs(graph[airport].pop())
            
            itinerary.append(airport)
        
        dfs("JFK")
        
        return itinerary[::-1]

1.507 - 2023-09-13 16:20:05 +0000 UTC

Detect Squares

Code

class DetectSquares:

    def __init__(self):
        self._row_col = defaultdict(lambda: defaultdict(int))

    def add(self, point: List[int]) -> None:
        self._row_col[point[0]][point[1]] += 1

    def count(self, point: List[int]) -> int:
        ways_count = 0
        row1, col1 = point
        for col2, col2_count in self._row_col[row1].items():
            if col2 == col1:
                continue

            side = col2 - col1
            for row2 in (row1 + side, row1 - side):
                point3_count = self._row_col[row2][col1]
                point4_count = self._row_col[row2][col2]
                ways_count += col2_count * point3_count * point4_count

        return ways_count

# Your DetectSquares object will be instantiated and called as such:
# obj = DetectSquares()
# obj.add(point)
# param_2 = obj.count(point)

1.508 - 2023-09-13 08:18:48 +0000 UTC

Candy

Code

class Solution:
    def candy(self, ratings: List[int]) -> int:
        child_count = len(ratings)
        candies = [1] * child_count 

        for i in range(1, child_count):
            if ratings[i] > ratings[i-1]:
                candies[i] = candies[i-1] + 1

        for i in reversed(range(child_count - 1)):
            if ratings[i] > ratings[i+1]:
                candies[i] = max(candies[i], candies[i+1] + 1)
        
        return sum(candies)

1.509 - 2023-09-12 16:36:36 +0000 UTC

Tweet Counts Per Frequency

Code

class TweetCounts:

    def __init__(self):
        self._tweets = defaultdict(list)
        self._chunk_ranges = {
            "minute": 60, 
            "hour": 3600, 
            "day": 86400
        }

    def recordTweet(self, tweetName: str, time: int) -> None:
        self._tweets[tweetName].append(time)

    def getTweetCountsPerFrequency(self, freq: str, tweetName: str, startTime: int, endTime: int) -> List[int]:
        chunk_range = self._chunk_ranges[freq]
        chunks = [0] * (1 + (endTime - startTime) // chunk_range)

        for tweet in self._tweets[tweetName]:
            if not startTime <= tweet <= endTime:
                continue
            chunks[(tweet - startTime) // chunk_range] += 1
        
        return chunks




# Your TweetCounts object will be instantiated and called as such:
# obj = TweetCounts()
# obj.recordTweet(tweetName,time)
# param_2 = obj.getTweetCountsPerFrequency(freq,tweetName,startTime,endTime)

1.510 - 2023-09-12 13:32:10 +0000 UTC

Snapshot Array

Code

class SnapshotArray:

    def __init__(self, length: int):
        self._cur_snap = 0
        self._elems = [[(0, 0)] for _ in range(length)]

    def set(self, index: int, val: int) -> None:
        values = self._elems[index]
        if values[-1][0] == self._cur_snap:
            values.pop()
        values.append((self._cur_snap, val))

    def snap(self) -> int:
        self._cur_snap += 1
        return self._cur_snap - 1 

    def get(self, index: int, snap_id: int) -> int:
        for cur_snap_id, val in reversed(self._elems[index]):
            if cur_snap_id > snap_id:
                continue
            return val
        
        return -1
        


# Your SnapshotArray object will be instantiated and called as such:
# obj = SnapshotArray(length)
# obj.set(index,val)
# param_2 = obj.snap()
# param_3 = obj.get(index,snap_id)

1.511 - 2023-09-12 12:42:35 +0000 UTC

Time Based Key-Value Store

Code

class TimeMap:

    def __init__(self):
        self._cache = defaultdict(list)
        

    def set(self, key: str, value: str, timestamp: int) -> None:
        self._cache[key].append((timestamp, value))

    def get(self, key: str, timestamp: int) -> str:
        for cur_timestamp, value in reversed(self._cache[key]):
            if cur_timestamp > timestamp:
                continue
            return value

        return ""

# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap()
# obj.set(key,value,timestamp)
# param_2 = obj.get(key,timestamp)

1.512 - 2023-09-12 12:27:56 +0000 UTC

Design Parking System

Code

class ParkingSystem:

    def __init__(self, big: int, medium: int, small: int):
        self._slots = [0, big, medium, small]

    def addCar(self, carType: int) -> bool:
        slots_avail = self._slots[carType]
        if not slots_avail:
            return False
        self._slots[carType] = slots_avail - 1
        return True


# Your ParkingSystem object will be instantiated and called as such:
# obj = ParkingSystem(big, medium, small)
# param_1 = obj.addCar(carType)

1.513 - 2023-09-12 12:23:56 +0000 UTC

Design Parking System

Code

class ParkingSystem:

    def __init__(self, big: int, medium: int, small: int):
        self._slots = [big, medium, small]

    def addCar(self, carType: int) -> bool:
        if self._slots[carType-1] == 0:
            return False
        self._slots[carType-1] -= 1
        return True


# Your ParkingSystem object will be instantiated and called as such:
# obj = ParkingSystem(big, medium, small)
# param_1 = obj.addCar(carType)

1.514 - 2023-09-12 12:21:06 +0000 UTC

Number of Recent Calls

Code

class RecentCounter:

    def __init__(self):
        self._queue = deque()

    def ping(self, t: int) -> int:
        self._queue.append(t)
        while self._queue:
            if t - self._queue[0] > 3000:
                self._queue.popleft()
            else:
                break

        return len(self._queue) 


# Your RecentCounter object will be instantiated and called as such:
# obj = RecentCounter()
# param_1 = obj.ping(t)

1.515 - 2023-09-12 11:23:58 +0000 UTC

Range Sum Query - Immutable

Code

class NumArray:

    def __init__(self, nums: List[int]):
        self._sums = tuple(accumulate(nums))

    def sumRange(self, left: int, right: int) -> int:
        # [-2, 0, 3, -5, 2, -1], [-2, -2, 1, -4, -2, -3]
        # [0, 2] -> 1
        if left == 0:
            return self._sums[right]

        return self._sums[right] - self._sums[left-1]


# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)

1.516 - 2023-09-12 11:12:53 +0000 UTC

Range Sum Query - Immutable

Code

class NumArray:

    def __init__(self, nums: List[int]):
        self._nums = nums

    @cache
    def sumRange(self, left: int, right: int) -> int:
        if right == left:
            return self._nums[left]
        if right - left == 1:
            return self._nums[right] + self._nums[left]
        mid = left + (right - left) // 2
        return self.sumRange(left, mid) + self.sumRange(mid + 1, right)


# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)

1.517 - 2023-09-12 11:07:17 +0000 UTC

Range Sum Query - Immutable

Code

class NumArray:

    def __init__(self, nums: List[int]):
        self._nums = nums

    def sumRange(self, left: int, right: int) -> int:
        return sum(self._nums[left:right+1])


# Your NumArray object will be instantiated and called as such:
# obj = NumArray(nums)
# param_1 = obj.sumRange(left,right)

1.518 - 2023-09-12 11:05:44 +0000 UTC

Binary Search Tree Iterator

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class BSTIterator:

    def __init__(self, root: Optional[TreeNode]):
        def generate(node: TreeNode) -> int:
            if not node:
                return
            yield from generate(node.left)
            yield node
            yield from generate(node.right)

        self._generate = generate(root)
        self._next = next(self._generate)

    def next(self) -> int:
        next_val = self._next.val
        self._next = next(self._generate, None)
        return next_val 

    def hasNext(self) -> bool:
        return self._next is not None


# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()

1.519 - 2023-09-12 11:05:12 +0000 UTC

Binary Search Tree Iterator

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class BSTIterator:

    def __init__(self, root: Optional[TreeNode]):
        def generate(node: TreeNode) -> int:
            if not node:
                return
            yield from generate(node.left)
            yield node
            yield from generate(node.right)

        self._generate = generate(root)
        self._next = next(self._generate)

    def next(self) -> int:
        next_val = self._next.val
        self._next = next(self._generate, None)
        return next_val 

    def hasNext(self) -> bool:
        return not self._next is None


# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()

1.520 - 2023-09-12 11:01:45 +0000 UTC

Binary Search Tree Iterator

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class BSTIterator:

    def __init__(self, root: Optional[TreeNode]):
        self._stack = []
        while root:
            self._stack.append(root)
            root = root.left

    def next(self) -> int:
        node = self._stack.pop()
        right = node.right
        while right:
            self._stack.append(right)
            right = right.left
        
        return node.val

    def hasNext(self) -> bool:
        return self._stack


# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext()

1.521 - 2023-09-12 08:17:46 +0000 UTC

Balanced Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isBalanced(self, root: Optional[TreeNode]) -> bool:
        def get_height(node: TreeNode) -> int:
            if not node:
                return 0
            
            h_left = get_height(node.left)
            if h_left < 0:
                return -1
            h_right = get_height(node.right)
            if h_right < 0 or abs(h_left - h_right) > 1:
                return -1

            return max(h_left, h_right) + 1
        
        return get_height(root) >= 0

1.522 - 2023-09-12 07:55:04 +0000 UTC

Minimum Deletions to Make Character Frequencies Unique

Code

class Solution:
    def minDeletions(self, s: str) -> int:
        length = len(s)
        char_count = Counter(s)
        counts = set()
        deleted_chars = 0

        for char, count in char_count.items():
            while count != 0 and count in counts:
                count -= 1
                deleted_chars += 1
            if count != 0:
                counts.add(count)
            
        return deleted_chars

1.523 - 2023-09-11 16:32:16 +0000 UTC

Intersection of Two Linked Lists

Code

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        if not headA or not headB:
            return None
        
        tail1, tail2 = headA, headB
        while tail1 != tail2:
            tail1 = tail1.next if tail1 else headB
            tail2 = tail2.next if tail2 else headA
        
        return tail2
    

1.524 - 2023-09-11 16:31:11 +0000 UTC

Intersection of Two Linked Lists

Code

class Solution:
    def getIntersectionNode(self, headA: ListNode, headB: ListNode) -> Optional[ListNode]:
        if headA and headB:
            A, B = headA, headB
            while A != B:
                A = A.next if A else headB
                B = B.next if B else headA
            return B
        

1.525 - 2023-09-11 16:16:39 +0000 UTC

Pascal’s Triangle II

Code

class Solution:
    def getRow(self, rowIndex: int) -> List[int]:
        prev_row = (1,)
        
        for i in range(1, rowIndex + 1):
            prev_row = (1, *(prev_row[j] + prev_row[j+1] for j in range(len(prev_row) - 1)), 1)
        
        return prev_row

1.526 - 2023-09-11 16:06:00 +0000 UTC

Single Number

Code

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return reduce(xor, nums)

1.527 - 2023-09-11 15:58:15 +0000 UTC

Single Number

Code

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        return reduce(lambda total, element: total ^ element, nums)

1.528 - 2023-09-11 15:55:49 +0000 UTC

Single Number

Code

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        nums_count = len(nums)
        if nums_count == 1:
            return nums[0]
        
        nums.sort()
        for i in range(0, nums_count, 2):
            if i + 1 == nums_count:
                return nums[i]

            cur_num, next_num = nums[i], nums[i+1]
            if cur_num == next_num:
                continue
            
            return cur_num
        
        return 0

1.529 - 2023-09-11 15:46:11 +0000 UTC

Minimum Depth of Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def minDepth(self, root: Optional[TreeNode]) -> int:
        
        def dfs(node: TreeNode) -> int:
            if not node:
                return 0

            return 1 + min((depth for depth in (dfs(node.left), dfs(node.right)) if depth > 0),
                           default=0)

        return dfs(root)

1.530 - 2023-09-11 15:31:16 +0000 UTC

Binary Tree Inorder Traversal

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        def get_nodes(root: TreeNode) -> Generator[None, None, TreeNode]:
            if not root:
                return

            yield from get_nodes(root.left)
            yield root.val
            yield from get_nodes(root.right)
        
        return tuple(get_nodes(root))

1.531 - 2023-09-11 15:30:56 +0000 UTC

Binary Tree Inorder Traversal

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def inorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        def get_nodes(root: TreeNode) -> Generator[None, None, TreeNode]:
            if not root:
                return

            if root.left:
                yield from get_nodes(root.left)
            
            yield root.val

            if root.right:
                yield from get_nodes(root.right)
        
        return tuple(get_nodes(root))

1.532 - 2023-09-11 12:06:55 +0000 UTC

Group the People Given the Group Size They Belong To

Code

class Solution:
    def groupThePeople(self, groupSizes: List[int]) -> List[List[int]]:
        answer = []
        cur_groups = defaultdict(list)
        
        for i in range(len(groupSizes)):
            size = groupSizes[i]
            group = cur_groups[size]
            group.append(i)
            if len(group) == size:
                answer.append(group)
                del cur_groups[size]
        
        return answer

1.533 - 2023-09-10 09:48:15 +0000 UTC

Count All Valid Pickup and Delivery Options

Code

class Solution:
    def countOrders(self, n: int) -> int:
        # P1, D1                 [01] -> (P1, D1)
        # P1, D1, P2, D2         [06] -> (P1, P2, D1, D2), (P1, P2, D2, D1), 
        #                                (P1, D1, P2, D2), (P2, P1, D1, D2), 
        #                                (P2, P1, D2, D1), (P2, D2, P1, D1).
        # P1, D1, P2, D2, P3, D3 [90]
        
        ways_count = 1
        mod = 10**9 + 7
        for order in range(2, n + 1):
            pos_avail_count = 1 + (order - 1) * 2
            cur_ways_count = pos_avail_count * (pos_avail_count + 1) // 2
            ways_count = (ways_count * cur_ways_count) % mod

        return ways_count

1.534 - 2023-09-10 09:37:39 +0000 UTC

Count All Valid Pickup and Delivery Options

Code

class Solution:
    def countOrders(self, n: int) -> int:
        # P1, D1                 [01] -> (P1, D1)
        # P1, D1, P2, D2         [06] -> (P1, P2, D1, D2), (P1, P2, D2, D1), 
        #                                (P1, D1, P2, D2), (P2, P1, D1, D2), 
        #                                (P2, P1, D2, D1), (P2, D2, P1, D1).
        # P1, D1, P2, D2, P3, D3 [90]
        
        ways_count = 1
        for order in range(2, n + 1):
            avail_pos_count = 1 + (order - 1) * 2
            ways_count *= sum(avail_pos_count - pos for pos in range(avail_pos_count))

        return ways_count % (10**9 + 7)

1.535 - 2023-09-09 17:12:03 +0000 UTC

Decode Ways

Code

class Solution:
    def numDecodings(self, s: str) -> int:
        char_count = len(s)

        @cache
        def dfs(i: int) -> int:
            if i == char_count: 
                return 1
            if s[i] == "0": 
                return 0
            return dfs(i + 1) + (
                dfs(i + 2) if i + 1 < char_count and s[i:i+2] < "27" else 0
            )

        return dfs(0)

1.536 - 2023-09-09 17:11:23 +0000 UTC

Decode Ways

Code

class Solution:
    def numDecodings(self, s: str) -> int:
        char_count = len(s)

        @cache
        def dfs(i: int) -> int:
            if i == char_count: 
                return 1
            if s[i] == "0": 
                return 0
            return dfs(i + 1) + (dfs(i + 2) if i + 1 < char_count and s[i:i+2] < "27" else 0)

        return dfs(0)

1.537 - 2023-09-09 17:10:19 +0000 UTC

Decode Ways

Code

class Solution:
    def numDecodings(self, s: str) -> int:
        char_count = len(s)

        @cache
        def dfs(i: int) -> int:
            if i == char_count: 
                return 1
            if s[i] == "0": 
                return 0
            ways_count = dfs(i + 1)
            if i + 1 < char_count and s[i:i+2] < "27":
                ways_count += dfs(i + 2)
            return ways_count

        return dfs(0)

1.538 - 2023-09-09 13:06:56 +0000 UTC

Snakes and Ladders

Code

class Solution:
    def snakesAndLadders(self, board: List[List[int]]) -> int:
        n = len(board)
        board.reverse()

        def intToPos(square):
            r = (square - 1) // n
            c = (square - 1) % n
            if r % 2:
                c = n - 1 - c
            return [r, c]

        q = deque()
        q.append([1, 0]) 
        visit = set()
        while q:
            square, moves = q.popleft()
            for i in range(1, 7):
                nextSquare = square + i
                r, c = intToPos(nextSquare)
                if board[r][c] != -1:
                    nextSquare = board[r][c]
                if nextSquare == n * n:
                    return moves + 1
                if nextSquare not in visit:
                    visit.add(nextSquare)
                    q.append([nextSquare, moves + 1])
        return -1

1.539 - 2023-09-09 07:20:58 +0000 UTC

Combination Sum IV

Code

class Solution:
    def combinationSum4(self, nums: List[int], target: int) -> int:

        @cache
        def dp(cur_sum: int) -> int:
            if cur_sum == target:
                return 1
            if cur_sum > target:
                return 0
            
            return sum(dp(cur_sum + num) for num in nums)

        return dp(0)
            

1.540 - 2023-09-09 07:20:26 +0000 UTC

Combination Sum IV

Code

class Solution:
    def combinationSum4(self, nums: List[int], target: int) -> int:

        @cache
        def backtrack(cur_sum: int) -> int:
            if cur_sum == target:
                return 1
            if cur_sum > target:
                return 0
            
            return sum(backtrack(cur_sum + num) for num in nums)

        return backtrack(0)
            

1.541 - 2023-09-08 10:41:10 +0000 UTC

Pascal’s Triangle

Code

class Solution:
    def generate(self, numRows: int) -> List[List[int]]:
        answer = [[1]]
        numRows -= 1

        while numRows > 0:
            cur, prev = [1], answer[-1]
            for i in range(len(prev) - 1):
                cur.append(prev[i] + prev[i+1])
            cur.append(1)
            answer.append(cur)
            numRows -= 1
        
        return answer

1.542 - 2023-09-07 17:09:04 +0000 UTC

Word Search

Code

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        row_count, col_count = len(board), len(board[0])
        word_length = len(word)
        delta = ((0, 1), (0, -1), (1, 0), (-1, 0))

        if word_length == 1:
            return any(word in row for row in board)
        if word_length > row_count * col_count:
            return False

        visited = set()

        def backtrack(row: int, col: int, target: int) -> bool:
            if target == word_length:
                return True
            if not 0 <= row < row_count or not 0 <= col < col_count or (
                (row, col) in visited or board[row][col] != word[target]
            ):
                return False

            visited.add((row, col))
            answer = any(backtrack(row + delta_row, col + delta_col, target + 1)
                         for delta_row, delta_col in delta)
            visited.remove((row, col))
            return answer

        return any(backtrack(row, col, 0) 
                   for row in range(row_count) 
                   for col in range(col_count))

1.543 - 2023-09-07 17:00:09 +0000 UTC

Word Search

Code

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        row_count, col_count = len(board), len(board[0])
        word_length = len(word)
        delta = ((0, 1), (0, -1), (1, 0), (-1, 0))

        if word_length == 1:
            return any(word in row for row in board)

        def backtrack(row: int, col: int, visited: Set, target: int) -> bool:
            if (row, col) in visited or not 0 <= row < row_count or not 0 <= col < col_count:
                return False

            if board[row][col] != word[target]:
                return False
            
            if target == word_length - 1:
                return True

            visited.add((row, col))
            if any(backtrack(row + delta_row, col + delta_col, visited, target + 1)
                   for delta_row, delta_col in delta):
                return True
            visited.remove((row, col))
            return False
        
        start_char = word[0]

        return any(backtrack(row, col, set(), 0) 
                   for row in range(row_count) 
                   for col in range(col_count)
                   if board[row][col] == start_char)

1.544 - 2023-09-07 16:55:32 +0000 UTC

Word Search

Code

class Solution:
    def exist(self, board: List[List[str]], word: str) -> bool:
        row_count, col_count = len(board), len(board[0])
        word_length = len(word)
        delta = ((0, 1), (0, -1), (1, 0), (-1, 0))

        if word_length == 1:
            return any(word in row for row in board)

        def backtrack(row: int, col: int, visited: Set, target: int) -> bool:
            if (row, col) in visited or not 0 <= row < row_count or not 0 <= col < col_count:
                return False

            if board[row][col] != word[target]:
                return False
            
            if target == word_length - 1:
                return True

            visited.add((row, col))
            if any(backtrack(row + delta_row, col + delta_col, visited, target + 1)
                   for delta_row, delta_col in delta):
                return True
            visited.remove((row, col))
            return False
        
        for row in range(row_count):
            for col in range(col_count):
                if backtrack(row, col, set(), 0):
                    return True
        
        return False

1.545 - 2023-09-07 14:13:51 +0000 UTC

Reverse Linked List II

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        cur_node = 1
        left_head, left_tail = head if left > 1 else None, None

        while cur_node < left:
            cur_node += 1
            head, left_tail = head.next, head

        cur_node += 1
        mid_head, mid_tail, head = head, head, head.next
        mid_head.next = None

        while cur_node <= right:
            cur_node += 1
            mid_head, head.next, head = head, mid_head, head.next
    
        mid_tail.next = head
        if left_head:
            left_tail.next = mid_head
        else:
            left_head = mid_head

        return left_head

1.546 - 2023-09-07 14:13:34 +0000 UTC

Reverse Linked List II

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        cur_node = 1
        left_head, left_tail = head if left > 1 else None, None

        while cur_node < left:
            cur_node += 1
            head, left_tail = head.next, head

        cur_node += 1
        mid_head, mid_tail, head = head, head, head.next
        mid_head.next = None

        while cur_node <= right:
            cur_node += 1
            next_node = head.next
            mid_head, head.next = head, mid_head
            head = next_node
    
        mid_tail.next = head
        if left_head:
            left_tail.next = mid_head
        else:
            left_head = mid_head

        return left_head

1.547 - 2023-09-07 14:12:50 +0000 UTC

Reverse Linked List II

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseBetween(self, head: Optional[ListNode], left: int, right: int) -> Optional[ListNode]:
        cur_node = 1
        left_head, left_tail = head if left > 1 else None, None

        while cur_node < left:
            cur_node += 1
            head, left_tail = head.next, head

        cur_node += 1
        mid_head, mid_tail, head = head, head, head.next
        mid_head.next = None

        while cur_node <= right:
            cur_node += 1
            next_node = head.next
            head.next = mid_head
            mid_head = head
            head = next_node
    
        mid_tail.next = head
        if left_head:
            left_tail.next = mid_head
        else:
            left_head = mid_head

        return left_head

1.548 - 2023-09-06 11:59:03 +0000 UTC

Split Linked List in Parts

Code

class Solution:
    def splitListToParts(self, head: Optional[ListNode], k: int) -> List[Optional[ListNode]]:        
        nodes_count = 0
        tail = head
        while tail:
            tail = tail.next
            nodes_count += 1
        
        quotient, remainder = divmod(nodes_count, k)
        answer = []
        for i in range(k):
            size = quotient + 1 if (remainder := remainder - 1) >= 0 else quotient

            answer.append(head)
            last = None
            while size > 0:
                last = head
                head = head.next
                size -= 1
            if last: 
                last.next = None
                
        return answer

1.549 - 2023-09-05 08:41:23 +0000 UTC

Copy List with Random Pointer

Code

"""
# Definition for a Node.
class Node:
    def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random
"""

class Solution:
    def copyRandomList(self, head: 'Optional[Node]') -> 'Optional[Node]':
        
        copied = {None: None}

        def copy_node(node: Node) -> Node:
            if node in copied:
                return copied[node]
            
            new_node = Node(node.val)
            copied[node] = new_node
            new_node.next = copy_node(node.next)
            new_node.random = copy_node(node.random)
            return new_node
        
        return copy_node(head)

1.550 - 2023-09-04 12:54:45 +0000 UTC

Combination Sum

Code

class Solution:
    def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:
        result = set()
        cur_nums = []

        def backtrack(cur_sum: int) -> None:
            if cur_sum == target:
                result.add(tuple(sorted(cur_nums[:])))
            if cur_sum >= target:
                return

            for num in candidates:
                cur_nums.append(num)
                backtrack(num + cur_sum)
                cur_nums.pop() 

        backtrack(0)

        return result

1.551 - 2023-09-04 09:44:01 +0000 UTC

Convert Sorted Array to Binary Search Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> Optional[TreeNode]:
        nums_count = len(nums)
        if nums_count == 0:
            return None
        
        mid = nums_count // 2
        return TreeNode(nums[mid], 
                        self.sortedArrayToBST(nums[:mid]), 
                        self.sortedArrayToBST(nums[mid+1:]))

1.552 - 2023-09-04 06:37:09 +0000 UTC

Linked List Cycle

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow_p, fast_p = head, head.next if head else None
        while fast_p and fast_p.next:
            if slow_p == fast_p:
                return True
            slow_p, fast_p = slow_p.next, fast_p.next.next

        return False

1.553 - 2023-09-03 17:06:29 +0000 UTC

Game of Life

Code

class Solution:
    def gameOfLife(self, board: List[List[int]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        rows_count, cols_count = len(board), len(board[0])
        moves = ((0, 1), (0, -1), (1, 0), (-1, 0), (1, 1), (1, -1), (-1, 1), (-1, -1))
        flip_cells = set()
        
        for row in range(rows_count):
            for col in range(cols_count):
                live_neighbors = 0
                is_alive = board[row][col] == 1

                for row_delta, col_delta in moves:
                    new_row, new_col = row + row_delta, col + col_delta
                    if not 0 <= new_row < rows_count or not 0 <= new_col < cols_count:
                        continue
                    if board[new_row][new_col] == 1:
                        live_neighbors += 1

                if (is_alive and (live_neighbors < 2 or live_neighbors > 3)) or (
                    not is_alive and live_neighbors == 3
                ):
                    flip_cells.add((row, col))
        
        while flip_cells:
            row, col = flip_cells.pop()
            board[row][col] = 0 if board[row][col] == 1 else 1

1.554 - 2023-09-03 16:49:38 +0000 UTC

Set Matrix Zeroes

Code

class Solution:
    def setZeroes(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        rows_count, cols_count = len(matrix), len(matrix[0])
        flip_rows, flip_cols = set(), set()

        for row in range(rows_count):
            for col in range(cols_count):
                if matrix[row][col] == 0:
                    flip_rows.add(row)
                    flip_cols.add(col)

        while flip_rows:
            row = flip_rows.pop()
            for col in range(cols_count):
                if matrix[row][col] != 0:
                    matrix[row][col] = 0
        
        while flip_cols:
            col = flip_cols.pop()
            for row in range(rows_count):
                if matrix[row][col] != 0:
                    matrix[row][col] = 0
        
            

1.555 - 2023-09-03 08:23:58 +0000 UTC

Unique Paths

Code

class Solution:
    def uniquePaths(self, m: int, n: int) -> int:

        @cache
        def dp(row: int, col: int) -> int:
            if not 0 <= row < m or not 0 <= col < n:
                return 0
            
            if row == m - 1 and col == n - 1:
                return 1
            
            return dp(row + 1, col) + dp(row, col + 1)

        return dp(0, 0)

1.556 - 2023-09-02 13:26:14 +0000 UTC

Rotate Image

Code

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        side_length = len(matrix)

        for row in range(side_length // 2):
            matrix[row], matrix[-row-1] = matrix[-row-1], matrix[row]
        
        for i in range(side_length):
            for j in range(i):
                matrix[i][j], matrix[j][i] = matrix[j][i], matrix[i][j]

1.557 - 2023-09-02 07:50:42 +0000 UTC

Extra Characters in a String

Code

class Solution:
    def minExtraChar(self, s: str, dictionary: List[str]) -> int:
        chars_count = len(s)

        @cache
        def dp(i: int) -> int:
            chars_left = chars_count - i
            if chars_left == 0:
                return 0
            
            min_extra_chars = chars_left

            for word in dictionary:
                word_length = len(word)

                if word_length > chars_left or s[i:i+word_length] != word:
                    continue
                
                if word_length == chars_left:
                    return 0

                min_extra_chars = min(min_extra_chars, dp(i + word_length))

            return min(min_extra_chars, 1 + dp(i + 1))
        
        return dp(0)

                

1.558 - 2023-09-01 15:41:17 +0000 UTC

Text Justification

Code

class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        words_count = len(words)
        
        def get_line(word_idx: int) -> Tuple[List[str], int]:
            line = []
            line_length = 0

            for i in range(word_idx, words_count):
                word = words[i]
                word_length = len(word)
                if line_length + word_length > maxWidth:
                    break

                line.append(word)
                line_length += word_length + 1 

            return line, line_length
        
        def create_line(line: List[str], line_length: int, word_idx: int) -> str:
            base_length = line_length - 1
            extra_spaces = maxWidth - base_length

            if len(line) == 1 or word_idx == words_count:
                return " ".join(line) + " " * extra_spaces

            word_count = len(line) - 1
            spaces_per_word = extra_spaces // word_count
            needs_extra_space = extra_spaces % word_count

            for j in range(needs_extra_space):
                line[j] += " "

            for j in range(word_count):
                line[j] += " " * spaces_per_word

            return " ".join(line)

        result = []
        i = 0
        while i < words_count:
            line, line_length = get_line(i)
            i += len(line)
            result.append(create_line(line, line_length, i))

        return result

1.559 - 2023-09-01 15:38:28 +0000 UTC

Course Schedule

Code

class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        
        nodes = [[] for _ in range(numCourses)]
        for target, required in prerequisites:
            nodes[target].append(required)

        visited = set()

        @cache
        def dfs(course: int) -> bool:
            if course in visited:
                return False
    
            edges = nodes[course]
            if not edges:
                return True
            
            visited.add(course)
            return all(dfs(edge) for edge in edges)

        for course in range(numCourses):
            if not dfs(course):
                return False
            visited.clear()
        
        return True

1.560 - 2023-09-01 15:37:48 +0000 UTC

Course Schedule

Code

class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        
        nodes = [[] for _ in range(numCourses)]
        for target, required in prerequisites:
            nodes[target].append(required)

        visited = set()

        @cache
        def dfs(course: int) -> bool:
            if course in visited:
                return False
    
            edges = nodes[course]
            if not edges:
                return True
            
            visited.add(course)
            return all(dfs(edge) for edge in edges)

        for course in range(numCourses):
            if not dfs(course):
                return False
            visited.clear()
        
        return True

1.561 - 2023-09-01 06:58:21 +0000 UTC

Counting Bits

Code

class Solution:
    def countBits(self, n: int) -> List[int]:
        ans = [0] * (n + 1)
        for i in range(1, n + 1):
            ans[i] = ans[i >> 1] + (i & 1)
        return ans

1.562 - 2023-09-01 06:55:13 +0000 UTC

Counting Bits

Code

class Solution:
    def countBits(self, n: int) -> List[int]:
        return tuple(bin(i).count("1") for i in range(n + 1))

1.563 - 2023-08-31 19:14:58 +0000 UTC

Evaluate Division

Code

class Solution:
    def calcEquation(self, equations: List[List[str]], values: List[float], queries: List[List[str]]) -> List[float]:
        equations_count = len(equations)
        queries_count = len(queries) 
        edges = defaultdict(dict)
        seen_nodes = set()
        invalid = -1.0

        def dfs(val1: str, val2: str) -> float:
            if val1 == val2:
                return 1.0

            if val2 in edges[val1]:
                return edges[val1][val2]

            if val1 in seen_nodes:
                return invalid

            seen_nodes.add(val1)

            for connected_node in edges[val1]:
                new_edge_res = dfs(connected_node, val2)
                if new_edge_res == invalid:
                    continue
                new_edge_res *= edges[val1][connected_node]
                edges[val1][val2] = new_edge_res
                return new_edge_res
            
            return invalid

        for i in range(equations_count):
            (val1, val2), res = equations[i], values[i]
            edges[val1][val2], edges[val2][val1] = res, 1 / res
        
        for i in range(queries_count):
            res, (val1, val2) = -1, queries[i]
            if val1 in edges and val2 in edges:
                seen_nodes.clear()
                res = dfs(val1, val2)
            queries[i] = res

        return queries

1.564 - 2023-08-31 17:45:02 +0000 UTC

Clone Graph

Code

"""
# Definition for a Node.
class Node:
    def __init__(self, val = 0, neighbors = None):
        self.val = val
        self.neighbors = neighbors if neighbors is not None else []
"""

class Solution:
    def cloneGraph(self, node: 'Node') -> 'Node':
        old_to_new = {}
        
        def clone(node: Node) -> Node:
            if node in old_to_new:
                return old_to_new[node]
            
            new_node = Node(node.val)
            old_to_new[node] = new_node
            new_node.neighbors = [clone(neighbor) for neighbor in node.neighbors]

            return new_node

        return clone(node) if node else node

1.565 - 2023-08-31 17:35:52 +0000 UTC

Surrounded Regions

Code

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        row_count, col_count = len(board), len(board[0])
        moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
        ignore_cells = set()

        def bfs(row: int, col: int) -> None:
            if not 0 <= row < row_count or not 0 <= col < col_count:
                return
            if (row, col) in ignore_cells or board[row][col] == "X":
                return

            ignore_cells.add((row, col))
            for row_delta, col_delta in moves:
                bfs(row + row_delta, col + col_delta)
        
        for row, col in itertools.chain(
            ((0, col) for col in range(col_count)),
            ((row_count - 1, col) for col in range(col_count)),
            ((row, 0) for row in range(row_count)),
            ((row, col_count - 1) for row in range(row_count))
        ):
            bfs(row, col)
        
        for row in range(1, row_count - 1):
            for col in range(1, col_count - 1):
                if (row, col) in ignore_cells:
                    continue

                board[row][col] = "X"
        

1.566 - 2023-08-31 17:35:00 +0000 UTC

Surrounded Regions

Code

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        row_count, col_count = len(board), len(board[0])
        moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
        ignore_stack = set()

        def bfs(row: int, col: int) -> None:
            if not 0 <= row < row_count or not 0 <= col < col_count:
                return
            if (row, col) in ignore_stack or board[row][col] == "X":
                return

            ignore_stack.add((row, col))
            for row_delta, col_delta in moves:
                bfs(row + row_delta, col + col_delta)
        
        for row, col in itertools.chain(
            ((0, col) for col in range(col_count)),
            ((row_count - 1, col) for col in range(col_count)),
            ((row, 0) for row in range(row_count)),
            ((row, col_count - 1) for row in range(row_count))
        ):
            bfs(row, col)
        
        flip_x = True
        for row in range(1, row_count - 1):
            for col in range(1, col_count - 1):
                if (row, col) in ignore_stack:
                    continue

                board[row][col] = "X"
        

1.567 - 2023-08-31 17:34:31 +0000 UTC

Surrounded Regions

Code

class Solution:
    def solve(self, board: List[List[str]]) -> None:
        """
        Do not return anything, modify board in-place instead.
        """
        row_count, col_count = len(board), len(board[0])
        moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
        ignore_stack = set()

        @cache
        def bfs(row: int, col: int) -> None:
            if not 0 <= row < row_count or not 0 <= col < col_count:
                return
            if (row, col) in ignore_stack or board[row][col] == "X":
                return

            ignore_stack.add((row, col))
            for row_delta, col_delta in moves:
                bfs(row + row_delta, col + col_delta)
        
        for row, col in itertools.chain(
            ((0, col) for col in range(col_count)),
            ((row_count - 1, col) for col in range(col_count)),
            ((row, 0) for row in range(row_count)),
            ((row, col_count - 1) for row in range(row_count))
        ):
            bfs(row, col)
        
        flip_x = True
        for row in range(1, row_count - 1):
            for col in range(1, col_count - 1):
                if (row, col) in ignore_stack:
                    continue

                board[row][col] = "X"
        

1.568 - 2023-08-31 12:29:43 +0000 UTC

Minimum Number of Taps to Open to Water a Garden

Code

class Solution:
    def minTaps(self, n: int, ranges: List[int]) -> int:
        inf = float("inf")
        dp = [inf] * (n + 1)
        dp[0] = 0
        
        for i in range(n + 1):
            cur_range = ranges[i]
            tap_start, tap_end = max(0, i - cur_range), min(n, i + cur_range)
            
            for j in range(tap_start, tap_end + 1):
                dp[tap_end] = min(dp[tap_end], dp[j] + 1)
        
        min_taps = dp[n]
        return -1 if min_taps == inf else min_taps 

1.569 - 2023-08-31 09:14:40 +0000 UTC

Minimum Number of Taps to Open to Water a Garden

Code

class Solution:
    def minTaps(self, n: int, ranges: List[int]) -> int:
        arr = [0] * (n + 1)
        for i, r in enumerate(ranges):
            if r == 0:
                continue
            left = max(0, i - r)
            arr[left] = max(arr[left], i + r)

        end, far_can_reach, cnt = 0, 0, 0
        
        for i, reach in enumerate(arr):
            if i > end:
                if far_can_reach <= end:
                    return -1
                end, cnt = far_can_reach, cnt + 1
            far_can_reach = max(far_can_reach, reach)

        return cnt + (end < n)

1.570 - 2023-08-30 16:06:25 +0000 UTC

Minimum Replacements to Sort the Array

Code

class Solution:
    def minimumReplacement(self, nums: List[int]) -> int:
        nums_count = len(nums)
        operations_count = 0
        for i in reversed(range(nums_count - 1)):
            cur, prev = nums[i], nums[i+1]
            if cur <= prev:
                continue
            
            elements_count = (cur + prev - 1) // prev
            operations_count += elements_count - 1
            nums[i] //= elements_count

        return operations_count

1.571 - 2023-08-29 16:00:49 +0000 UTC

Number of Islands

Code

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        row_count, col_count = len(grid), len(grid[0])
        island_count = 0
        moves = ((0, 1), (0, -1), (1, 0), (-1, 0))

        @cache
        def dfs(row: int, col: int) -> None:
            if not 0 <= row < row_count or not 0 <= col < col_count or grid[row][col] == "0":
                return
            
            grid[row][col] = "0"
            for row_delta, col_delta in moves:
                dfs(row + row_delta, col + col_delta)

        for row in range(row_count):
            for col in range(col_count):
                if grid[row][col] == "0":
                    continue

                dfs(row, col)
                island_count += 1

        return island_count

            

1.572 - 2023-08-29 15:48:22 +0000 UTC

Number of Islands

Code

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        row_count, col_count = len(grid), len(grid[0])
        island_count = 0
        moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
        queue = set((row, col) 
                    for row in range(row_count) 
                    for col in range(col_count) 
                    if grid[row][col] == "1")

        @cache
        def remove_island(row: int, col: int) -> None:
            if not 0 <= row < row_count or not 0 <= col < col_count:
                return

            for row_delta, col_delta in moves:
                new_cell = (row + row_delta, col + col_delta)
                if new_cell in queue:
                    queue.remove(new_cell)
                    remove_island(*new_cell)

        while queue:
            remove_island(*queue.pop())
            island_count += 1

        return island_count

            

1.573 - 2023-08-29 15:48:09 +0000 UTC

Number of Islands

Code

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        row_count, col_count = len(grid), len(grid[0])
        island_count = 0
        moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
        queue = set((row, col) 
                    for row in range(row_count) 
                    for col in range(col_count) 
                    if grid[row][col] == "1")

        @cache
        def remove_island(row: int, col: int) -> None:
            if not 0 <= row < row_count or not 0 <= col < col_count:
                return

            for row_delta, col_delta in moves:
                new_cell = (row + row_delta, col + col_delta)
                if new_cell in queue:
                    queue.remove(new_cell)
                    remove_island(*new_cell)

        while queue:
            remove_island(*queue.pop())
            island_count += 1

        return island_count

            

1.574 - 2023-08-29 15:44:17 +0000 UTC

Number of Islands

Code

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        row_count, col_count = len(grid), len(grid[0])
        island_count = 0
        moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
        queue = set((row, col) 
                    for row in range(row_count) 
                    for col in range(col_count) 
                    if grid[row][col] == "1")

        def remove_island(row: int, col: int) -> None:
            if not 0 <= row < row_count or not 0 <= col < col_count or (row, col) not in queue:
                return

            queue.remove((row, col))

            for row_delta, col_delta in moves:
                remove_island(row + row_delta, col + col_delta)    

        while queue:
            remove_island(*next(iter(queue)))
            island_count += 1

        return island_count

            

1.575 - 2023-08-29 15:43:22 +0000 UTC

Number of Islands

Code

class Solution:
    def numIslands(self, grid: List[List[str]]) -> int:
        row_count, col_count = len(grid), len(grid[0])
        island_count = 0
        moves = ((0, 1), (0, -1), (1, 0), (-1, 0))
        queue = set((row, col) 
                    for row in range(row_count) 
                    for col in range(col_count) 
                    if grid[row][col] == "1")

        @cache
        def remove_island(row: int, col: int) -> None:
            if not 0 <= row < row_count or not 0 <= col < col_count or (row, col) not in queue:
                return

            queue.remove((row, col))

            for row_delta, col_delta in moves:
                remove_island(row + row_delta, col + col_delta)    

        while queue:
            remove_island(*next(iter(queue)))
            island_count += 1

        return island_count

            

1.576 - 2023-08-29 08:50:54 +0000 UTC

Minimum Penalty for a Shop

Code

class Solution:
    def bestClosingTime(self, customers: str) -> int:
        # Start with closing at hour 0, the penalty equals all 'Y' in closed hours.
        cur_penalty = min_penalty = customers.count("Y")
        earliest_hour = 0
        
        for hour, customer in enumerate(customers):
            # If status in hour i is 'Y', moving it to open hours decrement
            # penalty by 1. Otherwise, moving 'N' to open hours increment
            # penatly by 1.
            cur_penalty += 1 if customer == "N" else -1

            # Update earliest_hour if a smaller penatly is encountered
            if cur_penalty < min_penalty:
                earliest_hour = hour + 1
                min_penalty = cur_penalty
                
        return earliest_hour

1.577 - 2023-08-28 10:37:58 +0000 UTC

Map Sum Pairs

Code

class MapSum:

    def __init__(self):
        self._map = {}

    def insert(self, key: str, val: int) -> None:
        self._map[key] = val

    def sum(self, prefix: str) -> int:
        return sum(value for key, value in self._map.items() if key.startswith(prefix))


# Your MapSum object will be instantiated and called as such:
# obj = MapSum()
# obj.insert(key,val)
# param_2 = obj.sum(prefix)

1.578 - 2023-08-28 10:35:54 +0000 UTC

Implement Stack using Queues

Code

class MyStack:

    def __init__(self):
        self._queue = []

    def push(self, x: int) -> None:
        self._queue.append(x)

    def pop(self) -> int:
        return self._queue.pop()

    def top(self) -> int:
        return self._queue[-1]

    def empty(self) -> bool:
        return len(self._queue) == 0 


# Your MyStack object will be instantiated and called as such:
# obj = MyStack()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.top()
# param_4 = obj.empty()

1.579 - 2023-08-27 15:09:36 +0000 UTC

Minimum Absolute Difference in BST

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
        
        def min_node_diff(node: TreeNode, low: int, high: int) -> int:
            if not node:
                return high - low

            return min(min_node_diff(node.left, low, node.val),
                       min_node_diff(node.right, node.val, high))
    
        return min_node_diff(root, -maxsize, maxsize)

1.580 - 2023-08-27 15:03:23 +0000 UTC

Minimum Absolute Difference in BST

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def getMinimumDifference(self, root: Optional[TreeNode]) -> int:
        values = []
        def fall(node: TreeNode) -> None:
            if not node:
                return
            values.append(node.val)
            if node.left:
                fall(node.left)
            if node.right:
                fall(node.right)
        
        fall(root)
        values.sort()
        min_diff = abs(values[1] - values[0])
        for i in range(1, len(values) - 1):
            min_diff = min(min_diff, abs(values[i] - values[i+1]))
        
        return min_diff

1.581 - 2023-08-27 14:55:09 +0000 UTC

Frog Jump

Code

class Solution:
    def canCross(self, stones: List[int]) -> bool:
        m = set(stones)
        @cache
        def dfs(i, j):
            if i == stones[-1]: return True
            return any(x and x + i in m and dfs(x + i, x) for x in range(j - 1, j + 2))
        return dfs(0, 0)

1.582 - 2023-08-26 13:17:44 +0000 UTC

Count Complete Tree Nodes

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        def left_height(root: TreeNode) -> int:
            return 0 if not root else 1 + left_height(root.left)
        
        def right_height(root: TreeNode) -> int:
            return 0 if not root else 1 + right_height(root.right)
        
        left, right = left_height(root), right_height(root)
        if left > right:
            return 1 + self.countNodes(root.left) + self.countNodes(root.right)
        
        return 2**left - 1

        

1.583 - 2023-08-26 13:17:28 +0000 UTC

Count Complete Tree Nodes

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        def left_height(root: TreeNode) -> int:
            return 0 if not root else 1 + left_height(root.left)
        
        def right_height(root: TreeNode) -> int:
            return 0 if not root else 1+ right_height(root.right)
        
        left, right = left_height(root), right_height(root)
        if left > right:
            return 1 + self.countNodes(root.left) + self.countNodes(root.right)
        
        return 2**left - 1

        

1.584 - 2023-08-26 13:16:46 +0000 UTC

Count Complete Tree Nodes

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def countNodes(self, root: Optional[TreeNode]) -> int:
        if not root:
            return 0
        
        def left_height(root: TreeNode) -> int:
            return 0 if not root else 1 + left_height(root.left)
        
        def right_height(root: TreeNode) -> int:
            return 0 if not root else 1+ right_height(root.right)
        
        left, right = left_height(root), right_height(root)
        if left > right:
            return 1 + self.countNodes(root.left) + self.countNodes(root.right)
        
        return 2**left - 1

        

1.585 - 2023-08-26 13:06:04 +0000 UTC

Path Sum

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        node_stack = [(root, 0)]
        while node_stack:
            node, curr_sum = node_stack.pop()
            if not node:
                continue
            
            new_sum = curr_sum + node.val
            if new_sum == targetSum and not node.left and not node.right:
                return True
            
            node_stack.extend(((node.left, new_sum), (node.right, new_sum)))
                
        return False

1.586 - 2023-08-26 12:38:12 +0000 UTC

Symmetric Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        comparison_stack = [(root.left, root.right)]
        while comparison_stack:
            left, right = comparison_stack.pop()
            
            if not left and not right:
                continue
            if not left or not right or left.val != right.val:
                return False

            comparison_stack.extend(((left.left, right.right), (left.right, right.left)))
        
        return True

1.587 - 2023-08-26 12:24:31 +0000 UTC

Symmetric Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        return self.check(root.left, root.right)

    def check(self, left: TreeNode, right: TreeNode) -> bool:
        if not left and not right:
            return True
        
        if not left or not right or left.val != right.val:
            return False
        
        return self.check(left.left, right.right) and self.check(left.right, right.left)

1.588 - 2023-08-26 12:20:18 +0000 UTC

Invert Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root:
            root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
        return root

1.589 - 2023-08-26 12:20:08 +0000 UTC

Invert Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if root:
            root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
        return root 

1.590 - 2023-08-26 12:19:33 +0000 UTC

Invert Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None

        root.left, root.right = self.invertTree(root.right), self.invertTree(root.left)
        return root 

1.591 - 2023-08-26 12:18:57 +0000 UTC

Invert Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None

        self.invertTree(root.left)
        self.invertTree(root.right) 
        root.left, root.right = root.right, root.left
        
        return root 

1.592 - 2023-08-26 09:16:27 +0000 UTC

Maximum Length of Pair Chain

Code

class Solution:
    def findLongestChain(self, pairs: List[List[int]]) -> int:
        pairs_count = len(pairs)
        if pairs_count < 2:
            return pairs_count
        
        pairs.sort()
        
        @cache
        def dp(curr_pair: int) -> int:
            right = pairs[curr_pair][1]
            max_length = 1

            for new_pair in range(curr_pair + 1, pairs_count):
                new_left = pairs[new_pair][0]
                new_length = dp(new_pair) + (1 if new_left > right else 0)

                if new_length > max_length:
                    max_length = new_length
            
            return max_length
        
        return dp(0)

1.593 - 2023-08-25 07:04:50 +0000 UTC

Interleaving String

Code

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        length_1, length_2, length_3 = len(s1), len(s2), len(s3)
        if length_1 + length_2 != length_3:
            return False

        @cache
        def dp(i_1: int, i_2: int, i_3: int) -> bool:
            if i_3 == length_3:
                return True

            target = s3[i_3]
            return (
                i_1 != length_1 and s1[i_1] == target and dp(i_1 + 1, i_2, i_3 + 1)
            ) or (
                i_2 != length_2 and s2[i_2] == target and dp(i_1, i_2 + 1, i_3 + 1)
            )

        return dp(0, 0, 0)

1.594 - 2023-08-24 13:42:07 +0000 UTC

Find K Pairs with Smallest Sums

Code

class Solution:
    def kSmallestPairs(self, nums1: List[int], nums2: List[int], k: int) -> List[List[int]]:
        nums1_count, nums2_count = len(nums1), len(nums2)
        result = []
        visited = set(((0, 0)))
        min_heap = [(nums1[0] + nums2[0], (0, 0))]
        count = 0

        while k > 0 and min_heap:
            _, (i, j) = heappop(min_heap)
            new_i, new_j = i + 1, j + 1
            new_pair1, new_pair2 = (new_i, j), (i, new_j)
            num1, num2 = nums1[i], nums2[j]
            result.append((num1, num2))

            if new_i < nums1_count and new_pair1 not in visited:
                heappush(min_heap, (nums1[new_i] + num2, new_pair1))
                visited.add(new_pair1)

            if new_j < nums2_count and new_pair2 not in visited:
                heappush(min_heap, (num1 + nums2[new_j], new_pair2))
                visited.add(new_pair2)

            k -= 1
        
        return result

1.595 - 2023-08-24 10:45:42 +0000 UTC

Text Justification

Code

class Solution:
    def fullJustify(self, words: List[str], maxWidth: int) -> List[str]:
        words_count = len(words)
        
        def get_line(word_idx: int) -> Tuple[List[str], int]:
            line = []
            line_length = 0

            for i in range(word_idx, words_count):
                word = words[i]
                word_length = len(word)
                if line_length + word_length > maxWidth:
                    break

                line.append(word)
                line_length += word_length + 1 

            return line, line_length
        
        def create_line(line: List[str], line_length: int, word_idx: int) -> str:
            base_length = line_length - 1
            extra_spaces = maxWidth - base_length

            if len(line) == 1 or word_idx == words_count:
                return " ".join(line) + " " * extra_spaces

            word_count = len(line) - 1
            spaces_per_word = extra_spaces // word_count
            needs_extra_space = extra_spaces % word_count

            for j in range(needs_extra_space):
                line[j] += " "

            for j in range(word_count):
                line[j] += " " * spaces_per_word

            return " ".join(line)

        result = []
        i = 0
        while i < words_count:
            line, line_length = get_line(i)
            i += len(line)
            result.append(create_line(line, line_length, i))

        return result

1.596 - 2023-08-23 19:56:37 +0000 UTC

Summary Ranges

Code

class Solution:
    def summaryRanges(self, nums: List[int]) -> List[str]:
        nums_count = len(nums)
        if nums_count == 0:
            return []
        if nums_count == 1:
            return [str(nums[0])]

        ranges = [[nums[0]] * 2]
        for i, num in enumerate(nums[1:]):
            if ranges[-1][1] == num - 1:
                ranges[-1][1] = num
            else:
                ranges.append([num, num])

        return [f"{start}->{end}" if start != end else str(start) for start, end in ranges]

1.597 - 2023-08-23 09:45:05 +0000 UTC

Reorganize String

Code

class Solution:
    def reorganizeString(self, s: str) -> str:
        result = []
        # Min heap ordered by character counts, so we will use
        # negative values for count
        priority_queue = [(-count, char) for char, count in Counter(s).items()]
        heapify(priority_queue)

        while priority_queue:
            count_first, char_first = heappop(priority_queue)
            if not result or char_first != result[-1]:
                result.append(char_first)
                if count_first != -1: 
                    heappush(priority_queue, (count_first + 1, char_first))
                continue
            
            if not priority_queue: 
                return ""
            
            count_second, char_second = heappop(priority_queue)
            result.append(char_second)
            if count_second != -1:
                heappush(priority_queue, (count_second + 1, char_second))
            heappush(priority_queue, (count_first, char_first))

        return "".join(result)

1.598 - 2023-08-22 07:32:27 +0000 UTC

Excel Sheet Column Title

Code

class Solution:
    def convertToTitle(self, columnNumber: int) -> str:
        result = []
        while columnNumber:
            columnNumber, remainder = divmod(columnNumber - 1, 26)
            result.append(chr(65 + remainder))
        return ''.join(reversed(result))

1.599 - 2023-08-21 20:38:46 +0000 UTC

Spiral Matrix

Code

class Solution:
    def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
        row_count, col_count = len(matrix), len(matrix[0])
        if row_count == 1:
            return matrix[0]
        if col_count == 1:
            return [row[0] for row in matrix]


        result = []
        top, bot, left, right = 0, row_count - 1, 0, col_count - 1
        capacity = row_count * col_count

        while len(result) < capacity:
            for col in range(left, right + 1):
                result.append(matrix[top][col])
            top += 1

            for row in range(top, bot + 1):
                result.append(matrix[row][right])
            right -= 1

            if top <= bot:
                for col in range(right, left - 1, -1):
                    result.append(matrix[bot][col])
                bot -= 1
            
            if left <= right:
                for row in range(bot, top - 1, -1):
                    result.append(matrix[row][left])
                left += 1

        return result

1.600 - 2023-08-21 18:08:48 +0000 UTC

Valid Sudoku

Code

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        row_count, column_count = 9, 9
        row_counters = [defaultdict(bool) for _ in range(row_count)]
        column_counters = [defaultdict(bool) for _ in range(column_count)]
        subbox_counters = [[defaultdict(bool) for _ in range(column_count//3)] 
                            for _ in range(row_count//3)]

        for row in range(row_count):
            for column in range(column_count):
                char = board[row][column]
                if char == ".":
                    continue

                counters = (
                    row_counters[row], column_counters[column], 
                    subbox_counters[row//3][column//3]
                )
                for counter in counters:
                    if counter[char]:
                        return False

                    counter[char] = True
        
        return True

        

1.601 - 2023-08-21 18:08:11 +0000 UTC

Valid Sudoku

Code

class Solution:
    def isValidSudoku(self, board: List[List[str]]) -> bool:
        row_count, column_count = 9, 9

        

        row_counters = [defaultdict(bool) for _ in range(row_count)]
        column_counters = [defaultdict(bool) for _ in range(column_count)]
        subbox_counters = [[defaultdict(bool) for _ in range(column_count//3)] 
                            for _ in range(row_count//3)]

        for row in range(row_count):
            for column in range(column_count):
                char = board[row][column]
                if char == ".":
                    continue

                counters = (
                    row_counters[row], column_counters[column], 
                    subbox_counters[row//3][column//3]
                )
                for counter in counters:
                    if counter[char]:
                        return False

                    counter[char] = True
        
        return True

        

1.602 - 2023-08-21 06:29:54 +0000 UTC

Repeated Substring Pattern

Code

class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        length = len(s)
        for i in range(1, length // 2 + 1):
            if length % i != 0:
                continue
            
            if s == s[:i] * (length // i):
                return True
        
        return False

1.603 - 2023-08-20 11:34:41 +0000 UTC

Sort Items by Groups Respecting Dependencies

Code

class Solution:
    def sortItems(self, n, m, group, beforeItems):
        # If an item belongs to zero group, assign it a unique group id.
        group_id = m
        for i in range(n):
            if group[i] == -1:
                group[i] = group_id
                group_id += 1
        
        # Sort all item regardless of group dependencies.
        item_graph = [[] for _ in range(n)]
        item_indegree = [0] * n
        
        # Sort all groups regardless of item dependencies.
        group_graph = [[] for _ in range(group_id)]
        group_indegree = [0] * group_id      
        
        for curr in range(n):
            for prev in beforeItems[curr]:
                # Each (prev -> curr) represents an edge in the item graph.
                item_graph[prev].append(curr)
                item_indegree[curr] += 1
                
                # If they belong to different groups, add an edge in the group graph.
                if group[curr] != group[prev]:
                    group_graph[group[prev]].append(group[curr])
                    group_indegree[group[curr]] += 1      
        
        # Tologlogical sort nodes in graph, return [] if a cycle exists.
        def topologicalSort(graph, indegree):
            visited = []
            stack = [node for node in range(len(graph)) if indegree[node] == 0]
            while stack:
                cur = stack.pop()
                visited.append(cur)
                for neib in graph[cur]:
                    indegree[neib] -= 1
                    if indegree[neib] == 0:
                        stack.append(neib)
            return visited if len(visited) == len(graph) else []

        item_order = topologicalSort(item_graph, item_indegree)
        group_order = topologicalSort(group_graph, group_indegree)
        
        if not item_order or not group_order: 
            return []
        
        # Items are sorted regardless of groups, we need to 
        # differentiate them by the groups they belong to.
        ordered_groups = collections.defaultdict(list)
        for item in item_order:
            ordered_groups[group[item]].append(item)
        
        # Concatenate sorted items in all sorted groups.
        # [group 1, group 2, ... ] -> [(item 1, item 2, ...), (item 1, item 2, ...), ...]
        answer = []
        for group_index in group_order:
            answer += ordered_groups[group_index]
        return answer

1.604 - 2023-08-19 15:48:22 +0000 UTC

Sorting Three Groups

Code

class Solution:
    def minimumOperations(self, nums: List[int]) -> int:
        nums_count = len(nums)
        
        if nums_count == 1:
            return 0
            
        @cache
        def dp(i: int, start_group: int) -> int:
            if i == nums_count:
                return 0
            
            curr_group = nums[i] - 1
            actions_min = None
            
            for group_available in range(start_group, 3):
                actions = dp(i + 1, group_available) + (0 if group_available == curr_group else 1)
                if actions_min is None or actions < actions_min:
                    actions_min = actions
            
            return actions_min
        
        return dp(0, 0)

1.605 - 2023-08-19 15:13:19 +0000 UTC

Make String a Subsequence Using Cyclic Increments

Code

class Solution:
    def canMakeSubsequence(self, str1: str, str2: str) -> bool:
        length1, length2 = len(str1), len(str2)
        
        for i in range(length1):
            if i + length2 > length1:
                break
            
            idx2 = 0
            for idx1 in range(i, length1):
                if ord(str2[idx2]) - ord(str1[idx1]) in (0, 1, -25):
                    idx2 += 1
                
                if idx2 == length2:
                    return True
            
            
        return False

1.606 - 2023-08-19 14:36:50 +0000 UTC

Count Pairs Whose Sum is Less than Target

Code

class Solution:
    def countPairs(self, nums: List[int], target: int) -> int:
        pairs_count = 0
        nums_count = len(nums)
        for i in range(nums_count): 
            num1 = nums[i]
            for j in range(i + 1, nums_count):
                if num1 + nums[j] < target:
                    pairs_count += 1
        
        return pairs_count

1.607 - 2023-08-19 14:13:39 +0000 UTC

Find Critical and Pseudo-Critical Edges in Minimum Spanning Tree

Code

class Solution:

    class UnionFind:
        def __init__(self, n):
            self.parent = list(range(n))
            self.size = [1] * n
            self.max_size = 1

        def find(self, x):
            # Finds the root of x
            if x != self.parent[x]:
                self.parent[x] = self.find(self.parent[x])
            return self.parent[x]

        def union(self, x, y):
            # Connects x and y
            root_x = self.find(x)
            root_y = self.find(y)
            if root_x != root_y:
                if self.size[root_x] < self.size[root_y]:
                    root_x, root_y = root_y, root_x
                self.parent[root_y] = root_x
                self.size[root_x] += self.size[root_y]
                self.max_size = max(self.max_size, self.size[root_x])
                return True
            return False

    def findCriticalAndPseudoCriticalEdges(self, n, edges):
        new_edges = [edge.copy() for edge in edges]
        # Add index to edges for tracking
        for i, edge in enumerate(new_edges):
            edge.append(i)
        # Sort edges based on weight
        new_edges.sort(key=lambda x: x[2])

        # Find MST weight using union-find
        uf_std = self.UnionFind(n)
        std_weight = 0
        for u, v, w, _ in new_edges:
            if uf_std.union(u, v):
                std_weight += w

        # Check each edge for critical and pseudo-critical
        critical = []
        pseudo_critical = []
        for (u, v, w, i) in new_edges:
            # Ignore this edge and calculate MST weight
            uf_ignore = self.UnionFind(n)
            ignore_weight = 0
            for (x, y, w_ignore, j) in new_edges:
                if i != j and uf_ignore.union(x, y):
                    ignore_weight += w_ignore
            # If the graph is disconnected or the total weight is greater,
            # the edge is critical
            if uf_ignore.max_size < n or ignore_weight > std_weight:
                critical.append(i)
                continue

            # Force this edge and calculate MST weight
            uf_force = self.UnionFind(n)
            force_weight = w
            uf_force.union(u, v)
            for (x, y, w_force, j) in new_edges:
                if i != j and uf_force.union(x, y):
                    force_weight += w_force
            # If total weight is the same, the edge is pseudo-critical
            if force_weight == std_weight:
                pseudo_critical.append(i)

        return [critical, pseudo_critical]

1.608 - 2023-08-18 07:52:33 +0000 UTC

Maximal Network Rank

Code

class Solution:
    def maximalNetworkRank(self, n: int, roads: List[List[int]]) -> int:
        city_roads = [set() for _ in range(n)]

        for city_one, city_two in roads:
            city_roads[city_one].add(city_two)
            city_roads[city_two].add(city_one)
        
        max_rank = 0

        for city_one in range(n):
            for city_two in range(city_one + 1, n):
                rank = len(city_roads[city_one]) + len(city_roads[city_two])
                if city_one in city_roads[city_two]:
                    rank -= 1
                
                if rank > max_rank:
                    max_rank = rank
        
        return max_rank

1.609 - 2023-08-17 13:52:59 +0000 UTC

01 Matrix

Code

class Solution:
    def updateMatrix(self, mat: List[List[int]]) -> List[List[int]]:
        if not mat or not mat[0]:
            return []

        row_count, column_count = len(mat), len(mat[0])
        queue = set()
        MAX_VALUE = row_count * column_count
        
        # Initialize the queue with all 0s and set cells with 1s to MAX_VALUE.
        for row in range(row_count):
            for column in range(column_count):
                if mat[row][column] == 0:
                    queue.add((row, column))
                else:
                    mat[row][column] = MAX_VALUE
        
        directions = ((1, 0), (-1, 0), (0, 1), (0, -1))
        
        while queue:
            center_row, center_column = queue.pop()
            distance_from_center = mat[center_row][center_column] + 1

            for delta_row, delta_column in directions:
                new_row, new_column = center_row + delta_row, center_column + delta_column
                if not 0 <= new_row < row_count or not 0 <= new_column < column_count:
                    continue
    
                if mat[new_row][new_column] > distance_from_center:
                    queue.add((new_row, new_column))
                    mat[new_row][new_column] = distance_from_center
        
        return mat

1.610 - 2023-08-16 11:36:21 +0000 UTC

Sliding Window Maximum

Code

import sortedcontainers

class Solution:
    def maxSlidingWindow(self, nums: List[int], k: int) -> List[int]:
        nums_count = len(nums)
        if nums_count <= k:
            return [max(nums)]

        counter = defaultdict(int)
        elems = sortedcontainers.SortedSet()
        
        for num in nums[:k]:
            counter[num] += 1
            elems.add(num)
        
        result = [elems[-1]]
        
        for i in range(k, nums_count):
            new_num = nums[i]
            remove_num = nums[i-k]

            counter[new_num] += 1
            elems.add(new_num)

            counter[remove_num] -= 1
            if counter[remove_num] == 0:
                elems.discard(remove_num)

            result.append(elems[-1])

        return result

1.611 - 2023-08-15 14:06:49 +0000 UTC

Partition List

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
        before_head, after_head = ListNode(0), ListNode(0)
        before_tail, after_tail = before_head, after_head
        
        while head: 
            if head.val < x:
                before_tail.next, before_tail = head, head
            else:
                after_tail.next, after_tail = head, head
            head = head.next
        
        after_tail.next, before_tail.next = None, after_head.next
        
        return before_head.next

1.612 - 2023-08-15 14:02:49 +0000 UTC

Partition List

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def partition(self, head: Optional[ListNode], x: int) -> Optional[ListNode]:
        first_left, last_left, first_right, last_right = None, None, None, None

        while head:
            is_left = head.val < x
            is_right = not is_left
            next_node = head.next
            head.next = first_right if is_left else None
            
            if is_left and last_left:
                last_left.next = head
                last_left = head
            elif is_left and not first_left:
                first_left, last_left = head, head

            if is_right and first_right:
                last_right.next = head
                last_right = head
            elif is_right and not first_right:
                first_right, last_right = head, head
                if last_left:
                    last_left.next = head

            head = next_node

        return first_left if first_left else first_right

1.613 - 2023-08-14 08:17:39 +0000 UTC

Kth Largest Element in an Array

Code

class Solution:
    def findKthLargest(self, nums, k):
        heap = []
        for num in nums:
            heapq.heappush(heap, num)
            if len(heap) > k:
                heapq.heappop(heap)
        
        return heap[0]

1.614 - 2023-08-13 15:35:13 +0000 UTC

Check if There is a Valid Partition For The Array

Code

class Solution:
    def validPartition(self, nums: List[int]) -> bool:
        n = len(nums)
        dp = [True] + [False] * n

        # Determine if the prefix array nums[0 ~ i] has a valid partition
        for i in range(n):
            dp_index = i + 1

            # Check 3 possibilities
            if i > 0 and nums[i] == nums[i - 1]:
                dp[dp_index] |= dp[dp_index - 2]
            if i > 1 and nums[i] == nums[i - 1] == nums[i - 2]:
                dp[dp_index] |= dp[dp_index - 3]
            if i > 1 and nums[i] == nums[i - 1] + 1 == nums[i - 2] + 2:
                dp[dp_index] |= dp[dp_index - 3]
 
        return dp[n]

1.615 - 2023-08-12 14:50:41 +0000 UTC

Unique Paths II

Code

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        row_count = len(obstacleGrid)
        column_count = len(obstacleGrid[0])
        
        if obstacleGrid[0][0] == 1 or obstacleGrid[-1][-1] == 1:
            return 0

        dp = [[0] * column_count for _ in range(row_count)]
        dp[0][0] = 1

        for column in range(1, column_count):
            if obstacleGrid[0][column] == 1:
                break

            dp[0][column] = dp[0][column-1]

        for row in range(1, row_count):
            if obstacleGrid[row][0] == 0:
                dp[row][0] = dp[row-1][0]

            for column in range(1, column_count):
                if obstacleGrid[row][column] == 1:
                    continue
                
                dp[row][column] = dp[row-1][column] + dp[row][column-1]
                     
        return dp[-1][-1]

1.616 - 2023-08-11 14:52:07 +0000 UTC

3Sum

Code

class Solution:
    def threeSum(self, nums: List[int]) -> List[List[int]]:
        result = set()

        #1. Split nums into three lists: negative numbers, positive numbers, and zeros
        negatives, positives, zeros = [], [], []
        for num in nums:
            if num > 0:
                positives.append(num)
            elif num < 0: 
                negatives.append(num)
            else:
                zeros.append(num)

        #2. Create a separate set for negatives and positives for O(1) look-up times
        negatives_count, positives_count, zeros_count = len(negatives), len(positives), len(zeros)
        negatives_set, positives_set = set(negatives), set(positives)

        #3. If there is at least 1 zero in the list, add all cases where -num exists in N and num exists in P
        #   i.e. (-3, 0, 3) = 0
        for num in positives_set if zeros else []:
            negative = -1 * num
            if negative in negatives_set:
                result.add((negative, 0, num))

        #3. If there are at least 3 zeros in the list then also include (0, 0, 0) = 0
        if zeros_count >= 3:
            result.add((0, 0, 0))

        #4. For all pairs of negative numbers (-3, -1), check to see if their complement (4)
        #   exists in the positive number set
        for i in range(negatives_count):
            negative_1 = negatives[i]
            for j in range(i + 1, negatives_count):
                negative_2 = negatives[j]
                target = -1 * (negative_1 + negative_2)
                if target in positives_set:
                    result.add(tuple(sorted([negative_1, negative_2, target])))

        #5. For all pairs of positive numbers (1, 1), check to see if their complement (-2)
        #   exists in the negative number set
        for i in range(positives_count):
            positive_1 = positives[i]
            for j in range(i + 1, positives_count):
                positive_2 = positives[j]
                target = -1 * (positive_1 + positive_2)
                if target in negatives_set:
                    result.add(tuple(sorted([positive_1, positive_2, target])))

        return result

1.617 - 2023-08-11 09:05:33 +0000 UTC

Product of Array Except Self

Code

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        nums_count = len(nums)
        result = [1] * nums_count
        prefix = 1
        postfix = 1
        for i in range(nums_count):
            result[i] *= prefix
            prefix *= nums[i]

            from_end = -1 * (i + 1)
            result[from_end] *= postfix
            postfix *= nums[from_end]
        
        return result

1.618 - 2023-08-11 09:01:50 +0000 UTC

Product of Array Except Self

Code

class Solution:
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        nums_count = len(nums)
        result = [1] * nums_count
        prefix = 1
        postfix = 1
        for i in range(nums_count):
            result[i] *= prefix
            prefix *= nums[i]
            result[nums_count-i-1] *= postfix
            postfix *= nums[nums_count-i-1]
        
        return result

1.619 - 2023-08-11 08:17:35 +0000 UTC

Coin Change II

Code

class Solution:
    def change(self, amount: int, coins: List[int]) -> int:
        n = len(coins)
        dp = [[0] * (amount + 1) for _ in range(n + 1)]
        for i in range(n):
            dp[i][0] = 1

        for i in range(n - 1, -1, -1):
            for j in range(1, amount + 1):
                if coins[i] > j:
                    dp[i][j] = dp[i + 1][j]
                else:
                    dp[i][j] = dp[i + 1][j] + dp[i][j - coins[i]]

        return dp[0][amount]

1.620 - 2023-08-11 08:12:31 +0000 UTC

Coin Change II

Code

class Solution:
    def change(self, amount: int, coins: List[int]) -> int:
        coins_count = len(coins)
        memo = [[-1] * (amount + 1) for _ in range(coins_count)]
        
        def dp(i: int, amount: int) -> int:
            if amount == 0:
                return 1
            if i == coins_count:
                return 0
            if memo[i][amount] != -1:
                return memo[i][amount]

            value = None

            if coins[i] > amount:
                value = dp(i + 1, amount)
            else:
                value = dp(i, amount - coins[i]) + dp(i + 1, amount)

            memo[i][amount] = value
            return value

        return dp(0, amount)

1.621 - 2023-08-10 14:04:38 +0000 UTC

Search in Rotated Sorted Array II

Code

class Solution:
    def search(self, nums: List[int], target: int) -> bool:
        left, right = 0, len(nums) - 1
        
        while left <= right:
            mid = (left + right) // 2
            
            if nums[mid] == target:
                return True
            
            if nums[mid] == nums[left]:
                left += 1
                continue

            if nums[left] <= nums[mid]:
                if nums[left] <= target < nums[mid]:
                    right = mid - 1
                else:
                    left = mid + 1
            else:
                if nums[mid] < target <= nums[right]:
                    left = mid + 1
                else:
                    right = mid - 1
        
        return False

1.622 - 2023-08-09 12:13:28 +0000 UTC

Best Time to Buy and Sell Stock IV

Code

class Solution:
    def maxProfit(self, k: int, prices: List[int]) -> int:
        # no transaction, no profit
        if k == 0: return 0
        # dp[k][0] = min cost you need to spend at most k transactions
        # dp[k][1] = max profit you can achieve at most k transactions
        dp = [[1000, 0] for _ in range(k + 1)]
        for price in prices:
            for i in range(1, k + 1):
                # price - dp[i - 1][1] is how much you need to spend
                # i.e use the profit you earned from previous transaction to buy the stock
                # we want to minimize it
                dp[i][0] = min(dp[i][0], price - dp[i - 1][1])
                # price - dp[i][0] is how much you can achieve from previous min cost
                # we want to maximize it
                dp[i][1] = max(dp[i][1], price - dp[i][0])
        # return max profit at most k transactions
		# or you can write `return dp[-1][1]`
        return dp[k][1]

1.623 - 2023-08-09 09:05:47 +0000 UTC

Minimize the Maximum Difference of Pairs

Code

class Solution:
    def minimizeMax(self, nums: List[int], p: int) -> int:
        nums.sort()
        nums_count = len(nums)
        
        # Find the number of valid pairs by greedy approach
        def countValidPairs(threshold: int) -> int:
            index, count = 0, 0
            while index < nums_count - 1:
                # If a valid pair is found, skip both numbers.
                if nums[index + 1] - nums[index] <= threshold:
                    count += 1
                    index += 1
                index += 1
            return count
        
        left, right = 0, nums[-1] - nums[0]
        while left < right:
            mid = left + (right - left) // 2

            # If there are enough pairs, look for a smaller threshold.
            # Otherwise, look for a larger threshold.
            if countValidPairs(mid) >= p:
                right = mid
            else:
                left = mid + 1

        return left       

1.624 - 2023-08-08 20:40:50 +0000 UTC

Best Time to Buy and Sell Stock III

Code

class Solution:
	def maxProfit(self, prices: List[int]) -> int:
				
		'''
		dp_2_hold: max profit with 2 transactions, and in hold state
		dp_2_not_hold: max profit with 2 transactions, and not in hold state
		
		dp_1_hold: max profit with 1 transaction, and in hold state
		dp_1_not_hold: max profit with 1 transaction, and not in hold state
		
		Note: it is impossible to have stock in hand and sell on first day, therefore -infinity is set as initial profit value for hold state
		'''
		
		dp_2_hold, dp_2_not_hold = -float('inf'), 0
		dp_1_hold, dp_1_not_hold = -float('inf'), 0
		
		for stock_price in prices:
				
			# either keep being in not-hold state, or sell with stock price today
			dp_2_not_hold = max( dp_2_not_hold, dp_2_hold + stock_price )
	
			# either keep being in hold state, or just buy with stock price today ( add one more transaction )
			dp_2_hold = max( dp_2_hold, dp_1_not_hold - stock_price )
				
			# either keep being in not-hold state, or sell with stock price today
			dp_1_not_hold = max( dp_1_not_hold, dp_1_hold + stock_price )
	
			# either keep being in hold state, or just buy with stock price today ( add one more transaction )
			dp_1_hold = max( dp_1_hold, 0 - stock_price )
				
		return dp_2_not_hold

1.625 - 2023-08-08 20:36:48 +0000 UTC

Best Time to Buy and Sell Stock III

Code

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

        # initialize variables for first buy, first sell, second buy, and second sell
        buy1, buy2 = float('inf'), float('inf')
        sell1, sell2 = 0, 0

        # iterate over prices to update buy and sell values
        for price in prices:
            # update first buy and sell values
            buy1 = min(buy1, price)
            sell1 = max(sell1, price - buy1)
            # update second buy and sell values
            buy2 = min(buy2, price - sell1)
            sell2 = max(sell2, price - buy2)

        return sell2

1.626 - 2023-08-08 19:57:16 +0000 UTC

Longest Palindromic Substring

Code

class Solution:
    def longestPalindrome(self, s: str) -> str:
        n = len(s)
        dp = [[False] * n for _ in range(n)]
        ans = [0, 0]
        
        for i in range(n):
            dp[i][i] = True
        
        for i in range(n - 1):
            if s[i] == s[i + 1]:
                dp[i][i + 1] = True
                ans = [i, i + 1]

        for diff in range(2, n):
            for i in range(n - diff):
                j = i + diff
                if s[i] == s[j] and dp[i + 1][j - 1]:
                    dp[i][j] = True
                    ans = [i, j]

        i, j = ans
        return s[i:j + 1]

1.627 - 2023-08-08 19:56:36 +0000 UTC

Maximal Square

Code

class Solution:
    def maximalSquare(self, matrix: List[List[str]]) -> int:
        row_count, column_count = len(matrix), len(matrix[0])
        
        dp = [[0] * column_count for _ in range(row_count)]
        
        max_size = 0
        for column in range(column_count):
            if matrix[0][column] == "0":
                continue
            dp[0][column] = 1
            max_size = 1

        for row in range(row_count):
            if matrix[row][0] == "0":
                continue
            dp[row][0] = 1
            max_size = 1
        
        for row in range(1, row_count):
            for column in range(1, column_count):
                if matrix[row][column] == "0":
                    continue
                
                value = min(dp[row-1][column], dp[row][column-1], dp[row-1][column-1]) + 1
                dp[row][column] = value
                max_size = max(max_size, value)
        
        return max_size * max_size

1.628 - 2023-08-08 18:50:31 +0000 UTC

Edit Distance

Code

class Solution:
    def minDistance(self, word1: str, word2: str) -> int:
        length1, length2 = len(word1), len(word2)

        @cache
        def dp(i1: int, i2: int) -> int:
            if i1 == length1:
                return length2 - (i2 + 1)

            if i2 == length2:
                return length1 - (i1 + 1)
            
            if word1[i1] == word2[i2]:
                return dp(i1 + 1, i2 + 1)

            return 1 + min((
                # replace or insert
                dp(i1 + 1, i2 + 1),
                # remove from i1
                dp(i1 + 1, i2),
                # remove from i2
                dp(i1, i2 + 1)
            ))
        
        return dp(0, 0) + 1

1.629 - 2023-08-08 18:27:42 +0000 UTC

Interleaving String

Code

class Solution:
    def isInterleave(self, s1: str, s2: str, s3: str) -> bool:
        length_1, length_2, length_3 = len(s1), len(s2), len(s3)
        if length_1 + length_2 != length_3:
            return False
        
        @cache
        def dp(i_1: int, i_2: int, i_3: int) -> bool:
            if i_3 == length_3:
                return True

            target = s3[i_3]
            return (
                i_1 != length_1 and s1[i_1] == target and dp(i_1 + 1, i_2, i_3 + 1)
            ) or (
                i_2 != length_2 and s2[i_2] == target and dp(i_1, i_2 + 1, i_3 + 1)
            )

        return dp(0, 0, 0)

1.630 - 2023-08-08 18:02:11 +0000 UTC

Unique Paths II

Code

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        row_count = len(obstacleGrid)
        column_count = len(obstacleGrid[0])
        
        if obstacleGrid[0][0] == 1 or obstacleGrid[-1][-1] == 1:
            return 0

        dp = [[0] * column_count for _ in range(row_count)]
        dp[0][0] = 1

        for column in range(1, column_count):
            if obstacleGrid[0][column] == 1:
                break

            dp[0][column] = dp[0][column-1]

        for row in range(1, row_count):
            if obstacleGrid[row][0] == 0:
                dp[row][0] = dp[row-1][0]

            for column in range(1, column_count):
                if obstacleGrid[row][column] == 1:
                    continue
                
                dp[row][column] = dp[row-1][column] + dp[row][column-1]
                     
        return dp[-1][-1]

1.631 - 2023-08-08 17:47:19 +0000 UTC

Unique Paths II

Code

class Solution:
    def uniquePathsWithObstacles(self, obstacleGrid: List[List[int]]) -> int:
        row_count = len(obstacleGrid)
        column_count = len(obstacleGrid[0])
        # dp = [[0] * column_count for _ in range(row_count)]

        # for row in range(row_count):
        #     for column in range(column_count):

        @cache
        def dp(row: int, column: int) -> int:
            if row == row_count or column == column_count or obstacleGrid[row][column] == 1:
                return 0
            
            if row == row_count - 1 and column == column_count - 1:
                return 1
            
            return dp(row + 1, column) + dp(row, column + 1)
        
        return dp(0, 0)

1.632 - 2023-08-08 17:31:21 +0000 UTC

Minimum Path Sum

Code

class Solution:
    def minPathSum(self, grid: List[List[int]]) -> int:
        row_count = len(grid)
        column_count = len(grid[0]) if grid else None
        if not row_count or not column_count:
            return 0

        dp = [[0] * column_count for _ in range(row_count)]
        dp[0][0] = grid[0][0]

        for column in range(1, column_count):
            dp[0][column] = grid[0][column] + dp[0][column - 1]

        for row in range(1, row_count):
            dp[row][0] = grid[row][0] + dp[row - 1][0]

            for column in range(1, column_count):
                dp[row][column] = grid[row][column] + min(
                    dp[row - 1][column], dp[row][column-1]
                )

        # @cache
        # def dp(row: int, column: int) -> int:
        #     if row == row_count or column == column_count:
        #         return 0
        #     return grid[row][column] + min(dp(row + 1, column), dp(row, column + 1))
        #return dp(0, 0)

        return dp[-1][-1]

1.633 - 2023-08-08 16:53:50 +0000 UTC

Triangle

Code

class Solution:
    def minimumTotal(self, triangle: List[List[int]]) -> int:
        row_count = len(triangle)
        dp = [[0] * row_count for _ in range(row_count)]
        dp[0][0] = triangle[0][0]

        for row in range(1, row_count):
            dp[row][0] = triangle[row][0] + dp[row-1][0]
            dp[row][row] = triangle[row][row] + dp[row-1][row-1]

            for column in range(1, row):
                dp[row][column] = triangle[row][column] + min(
                    dp[row-1][column], dp[row-1][column-1]
                )

        return min(dp[-1])

1.634 - 2023-08-08 16:34:48 +0000 UTC

Triangle

Code

class Solution:
    def minimumTotal(self, triangle: List[List[int]]) -> int:
        row_count = len(triangle)


        @cache
        def dp(row: int, column: int) -> int:
            if row == row_count or column == row + 1:
                return 0
        
            return triangle[row][column] + min(dp(row + 1, column), dp(row + 1, column + 1))

        return dp(0, 0)

1.635 - 2023-08-08 11:36:45 +0000 UTC

Kth Largest Element in an Array

Code

class Solution:
    def findKthLargest(self, nums, k):
        heap = []
        for num in nums:
            heapq.heappush(heap, num)
            if len(heap) > k:
                heapq.heappop(heap)
        
        return heap[0]

1.636 - 2023-08-08 10:55:40 +0000 UTC

Search in Rotated Sorted Array

Code

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        nums_count = len(nums)
        left, right = 0, len(nums) - 1

        first_num, last_num = nums[0], nums[-1]
        if first_num == target:
            return 0
        if last_num == target:
            return nums_count - 1
        
        # Find the index of the pivot element (the smallest element)
        while left <= right:
            mid = left + (right - left) // 2
            if nums[mid] > last_num:
                left = mid + 1
            else:
                right = mid - 1
        
        pivot_num = nums[left]
        if pivot_num == target:
            return left
        
        if pivot_num < target < last_num:
            right = nums_count - 1
        else:
            left = 0
        
        while left <= right:
            mid = left + (right - left) // 2
            mid_num = nums[mid]
            if mid_num == target:
                return mid
            elif mid_num > target:
                right = mid - 1
            else:
                left = mid + 1
        
        return -1

1.637 - 2023-08-08 10:55:01 +0000 UTC

Search in Rotated Sorted Array

Code

class Solution:
    def search(self, nums: List[int], target: int) -> int:
        nums_count = len(nums)
        left, right = 0, len(nums) - 1

        first_num, last_num = nums[0], nums[-1]
        if first_num == target:
            return 0
        if last_num == target:
            return nums_count - 1
        
        # Find the index of the pivot element (the smallest element)
        while left <= right:
            mid = left + (right - left) // 2
            if nums[mid] > last_num:
                left = mid + 1
            else:
                right = mid - 1
        
        pivot_num = nums[left]
        if pivot_num == target:
            return left
        
        if pivot_num < target < last_num:
            right = nums_count - 1
        else:
            left = 0
        
        while left <= right:
            mid = (left + right) // 2
            mid_num = nums[mid]
            if mid_num == target:
                return mid
            elif mid_num > target:
                right = mid - 1
            else:
                left = mid + 1
        
        return -1

1.638 - 2023-08-07 14:24:07 +0000 UTC

Longest Increasing Subsequence

Code

class Solution:
    def lengthOfLIS(self, nums: List[int]) -> int:
        nums_count = len(nums)
        dp = [0] * nums_count
        dp[0] = 1
        for i in range(1, nums_count):
            length = 0
            start = nums[i]

            for j in range(0, i):
                if start > nums[j]:
                    length = max(length, dp[j])

            dp[i] = 1 + length
            
        return max(dp)

1.639 - 2023-08-07 11:39:05 +0000 UTC

Coin Change

Code

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        dp = [amount + 1] * (amount + 1)
        dp[0] = 0

        for current_amount in range(1, amount + 1):
            for coin in coins:
                diff = current_amount - coin
                if diff < 0:
                    continue
                
                dp[current_amount] = min(dp[current_amount], dp[diff] + 1)

        return dp[-1] if dp[-1] != amount + 1 else -1

1.640 - 2023-08-07 11:27:07 +0000 UTC

Coin Change

Code

class Solution:
    def coinChange(self, coins: List[int], amount: int) -> int:
        if amount == 0:
            return 0
        
        @cache
        def dp(coins_value: int) -> int:
            if coins_value == amount:
                return 0
            
            if coins_value > amount:
                return -1
            
            min_coins_count = -1

            for coin in coins:
                new_count = 1 + dp(coin + coins_value)
                if new_count == 0:
                    continue
                
                if min_coins_count == -1 or new_count < min_coins_count:
                    min_coins_count = new_count
            
            return min_coins_count

        return dp(0)

1.641 - 2023-08-07 10:27:10 +0000 UTC

Word Break

Code

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        n = len(s)
        words = set(wordDict)
        dp = [False] * (n + 1)
        dp[0] = True
        
        for i in range(1, n + 1):
            for j in range(i):
                if dp[j] and s[j:i] in words:
                    dp[i] = True
                    break
        
        return dp[-1]

1.642 - 2023-08-07 10:25:04 +0000 UTC

Word Break

Code

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        @cache
        def dp(i):
            if i < 0: 
                return True

            for word in wordDict:
                if s[i - len(word) + 1:i + 1] == word and dp(i - len(word)):
                    return True
            
            return False
        
        return dp(len(s) - 1)

1.643 - 2023-08-07 10:10:04 +0000 UTC

House Robber

Code

class Solution:
    def rob(self, nums: List[int]) -> int:
        house_count = len(nums)

        prev_1, prev_2 = 0, 0

        for house in range(0, house_count):
            prev_1, prev_2 = max(prev_2 + nums[house], prev_1), prev_1

        return prev_1

1.644 - 2023-08-07 10:07:20 +0000 UTC

House Robber

Code

class Solution:
    def rob(self, nums: List[int]) -> int:
        house_count = len(nums)

        dp = [0 for _ in range(house_count + 1)]
        dp[1] = nums[0]

        for house in range(1, house_count):
            dp[house+1] = max(dp[house-1] + nums[house], dp[house])

        return dp[-1]

1.645 - 2023-08-07 09:57:18 +0000 UTC

House Robber

Code

class Solution:
    def rob(self, nums: List[int]) -> int:
        house_count = len(nums)
        
        @cache
        def dp(house: int) -> int:
            if house >= house_count:
                return 0

            return max(dp(house + 1), nums[house] + dp(house + 2)) 

        return dp(0)

1.646 - 2023-08-07 09:49:57 +0000 UTC

Climbing Stairs

Code

class Solution:
    def climbStairs(self, n: int) -> int:
        if n < 3:
            return n

        minus_one, minus_two = 2, 1
        for step in range(3, n + 1):
            minus_one, minus_two = minus_one + minus_two, minus_one
        
        return minus_one

1.647 - 2023-08-07 09:45:54 +0000 UTC

Climbing Stairs

Code

class Solution:
    def climbStairs(self, n: int) -> int:

        @cache
        def dp(step: int) -> int:
            if step <= 2:
                return step
            
            return dp(step - 1) + dp(step - 2) 
 
        return dp(n)

1.648 - 2023-08-07 09:17:58 +0000 UTC

Search a 2D Matrix

Code

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        length_vertical, length_horizontal = len(matrix), len(matrix[0])


        left, right = 0, length_vertical - 1
        while left <= right:
            mid = left + (right - left) // 2
            mid_number = matrix[mid][0]
            
            if mid_number == target:
                return True
            
            if mid_number > target:
                right = mid - 1
            else:
                left = mid + 1
        
        vertical_index = right
        left, right = 0, length_horizontal - 1
        while left <= right:
            mid = left + (right - left) // 2
            mid_number = matrix[vertical_index][mid]

            if mid_number == target:
                return True
            
            if mid_number > target:
                right = mid - 1
            else:
                left = mid + 1
            
        return False

1.649 - 2023-08-06 15:05:41 +0000 UTC

Faulty Keyboard

Code

class Solution:
    def finalString(self, s: str) -> str:
        result = []
        for char in s:
            if char == "i":
                result.reverse()
            else:
                result.append(char)
        
        return "".join(result)

1.650 - 2023-08-06 15:00:12 +0000 UTC

Maximum Number of Events That Can Be Attended II

Code

class Solution:
    def maxValue(self, events: List[List[int]], k: int) -> int:        
        events.sort()
        n = len(events)
        starts = [start for start, end, value in events]
        dp = [[-1] * n for _ in range(k + 1)]
        
        def dfs(cur_index, count):
            if count == 0 or cur_index == n:
                return 0
            if dp[count][cur_index] != -1:
                return dp[count][cur_index]

            # Find the nearest available event after attending event 0.

            next_index = bisect_right(starts, events[cur_index][1])
            dp[count][cur_index] = max(dfs(cur_index + 1, count), events[cur_index][2] + dfs(next_index, count - 1))
            return dp[count][cur_index]
        
        return dfs(0, k)

1.651 - 2023-08-06 14:37:57 +0000 UTC

Number of Music Playlists

Code

class Solution:
    def numMusicPlaylists(self, n: int, goal: int, k: int) -> int:
        MOD = 10**9 + 7

        # Initialize the DP table
        dp = [[0 for _ in range(n + 1)] for _ in range(goal + 1)]
        dp[0][0] = 1

        for i in range(1, goal + 1):
            for j in range(1, min(i, n) + 1):
                # The i-th song is a new song
                dp[i][j] = dp[i - 1][j - 1] * (n - j + 1) % MOD
                # The i-th song is a song we have played before
                if j > k:
                    dp[i][j] = (dp[i][j] + dp[i - 1][j] * (j - k)) % MOD

        return dp[goal][n]

1.652 - 2023-08-06 14:18:41 +0000 UTC

Smallest Sufficient Team

Code

class Solution:
    def smallestSufficientTeam(self, req_skills: List[str], people: List[List[str]]) -> List[int]:
        req_skills_count = len(req_skills)
        skill_to_people = defaultdict(set)
        for i, person in enumerate(people):
            for skill in person:
                skill_to_people[skill].add(i)

        current = set()
        
        def backtrack(skill: int) -> Tuple[int]:
            if skill == req_skills_count:
                return tuple(current)
            
            suff_team = None
            people_with_skill = skill_to_people[req_skills[skill]] 
            
            if current & people_with_skill:
                return backtrack(skill + 1)
        
            for person in people_with_skill:
                current.add(person)
                new_team = backtrack(skill + 1)
                current.remove(person)

                if suff_team is None or len(new_team) < len(suff_team):
                    suff_team = new_team

            return suff_team

        return backtrack(0)
        

1.653 - 2023-08-05 14:53:24 +0000 UTC

Insert Greatest Common Divisors in Linked List

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def insertGreatestCommonDivisors(self, head: Optional[ListNode]) -> Optional[ListNode]:
        root = head
        
        while head and head.next:
            next = head.next
            new_node = ListNode(math.gcd(head.val, head.next.val), next)
            head.next = new_node
            head = next
        
        return root

1.654 - 2023-08-05 14:40:38 +0000 UTC

Account Balance After Rounded Purchase

Code

class Solution:
    def accountBalanceAfterPurchase(self, purchaseAmount: int) -> int:
        remainder = purchaseAmount % 10
        if remainder == 0:
            return 100 - purchaseAmount

        if remainder >= 5:
            return 100 - ((purchaseAmount // 10) + 1) * 10 
        
        return 100 - (purchaseAmount // 10) * 10

1.655 - 2023-08-05 09:39:41 +0000 UTC

Unique Binary Search Trees II

Code

class Solution:
    def generateTrees(self, n: int) -> List[Optional[TreeNode]]:
        @cache
        def generate_trees(l, r):
            return [None] if l > r else [
                TreeNode(val, left, right)
                for val in range(l, r + 1)
                for left in generate_trees(l, val - 1)
                for right in generate_trees(val + 1, r)
            ]
        
        return generate_trees(1, n)

1.656 - 2023-08-04 16:40:16 +0000 UTC

Maximum Number of Achievable Transfer Requests

Code

class Solution:
    def maximumRequests(self, n, requests):
        current = [0] * n
        length = len(requests)
        
        def backtrack(req_index: int, count: int) -> int:
            if req_index == length:
                return 0 if any(current) else count

            req_from, req_to = requests[req_index]
            
            current[req_from] -= 1
            current[req_to] += 1
            take = backtrack(req_index + 1, count + 1)

            current[req_from] += 1
            current[req_to] -= 1
            non_take = backtrack(req_index + 1, count)
            
            return max(take, non_take)
        
        return backtrack(0, 0)

1.657 - 2023-08-04 16:38:00 +0000 UTC

Word Break

Code

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:

        @cache
        def calculate(i: int) -> bool:
            if i < 0:
                return True
            
            for word in wordDict:
                length = len(word)
                if s[i-length+1:i+1] == word and calculate(i-length):
                    return True
            
            return False

        return calculate(len(s) - 1)
        

1.658 - 2023-08-04 16:37:15 +0000 UTC

Word Break

Code

class Solution:
    def wordBreak(self, s: str, wordDict: List[str]) -> bool:
        words = set(wordDict)
    
        @cache
        def calculate(i: int) -> bool:
            if i < 0:
                return True
            
            for word in wordDict:
                length = len(word)
                if s[i-length+1:i+1] == word and calculate(i-length):
                    return True
            
            return False

        return calculate(len(s) - 1)
        

1.659 - 2023-08-03 09:33:31 +0000 UTC

Letter Combinations of a Phone Number

Code

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        length = len(digits)
        if length == 0:
            return []

        digit_map: Dict[int, str] = {
            "1": [],
            "2": ["a", "b", "c"],
            "3": ["d", "e", "f"],
            "4": ["g", "h", "i"],
            "5": ["j", "k", "l"],
            "6": ["m", "n", "o"],
            "7": ["p", "q", "r", "s"],
            "8": ["t", "u", "v"],
            "9": ["w", "x", "y", "z"],
            "0": [" "]
        }

        current = []
        
        def backtrack(digit: int) -> Generator[None, None, str]:
            if digit == length:
                yield "".join(current[:])
                return
            
            for char in digit_map[digits[digit]]:
                current.append(char)
                yield from backtrack(digit + 1)
                current.pop()

        return tuple(combination for combination in backtrack(0))

1.660 - 2023-08-03 09:32:00 +0000 UTC

Letter Combinations of a Phone Number

Code

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        length = len(digits)
        if length == 0:
            return []

        digit_map: Dict[int, str] = {
            "1": [],
            "2": ["a", "b", "c"],
            "3": ["d", "e", "f"],
            "4": ["g", "h", "i"],
            "5": ["j", "k", "l"],
            "6": ["m", "n", "o"],
            "7": ["p", "q", "r", "s"],
            "8": ["t", "u", "v"],
            "9": ["w", "x", "y", "z"],
            "0": [" "]
        }

        current = []
        
        def backtrack(digit: int) -> Generator[None, None, str]:
            if digit == length:
                yield "".join(current[:])
                return
            
            for char in digit_map[digits[digit]]:
                current.append(char)
                yield from backtrack(digit + 1)
                current.pop()

        return tuple(combination for combination in backtrack(0))

1.661 - 2023-08-02 16:02:58 +0000 UTC

Course Schedule

Code

class Solution:
    def canFinish(self, numCourses: int, prerequisites: List[List[int]]) -> bool:
        courses = defaultdict(set)

        for course, prereq in prerequisites:
            courses[course].add(prereq)

        if not courses:
            return True
        
        stack = set()

        @cache
        def check(course: int) -> bool:
            if course not in courses:
                return True
            
            if course in stack:
                return False

            prereqs = courses[course]

            if prereqs & stack:
                return False

            stack.add(course)

            for prereq in prereqs:
                if not check(prereq):
                    return False
    
            stack.remove(course)
            
            return True

        for course in courses:
            if not check(course):
                return False

        return True

1.662 - 2023-08-02 15:11:45 +0000 UTC

Find Eventual Safe States

Code

class Solution:
    def eventualSafeNodes(self, graph: List[List[int]]) -> List[int]:
        length = len(graph)
        indegree = [0] * length
        adj = [[] for _ in range(length)]

        for i in range(length):
            for edge in graph[i]:
                adj[edge].append(i)
                indegree[i] += 1

        q = deque()
        # Push all the nodes with indegree zero in the queue.
        for i in range(length):
            if indegree[i] == 0:
                q.append(i)

        safe = [False] * length
        while q:
            node = q.popleft()
            safe[node] = True

            for neighbor in adj[node]:
                # Delete the edge "node -> neighbor".
                indegree[neighbor] -= 1
                if indegree[neighbor] == 0:
                    q.append(neighbor)

        safe_nodes = []
        for i in range(length):
            if safe[i]:
                safe_nodes.append(i)

        return safe_nodes

1.663 - 2023-08-02 14:33:24 +0000 UTC

Maximize the Confusion of an Exam

Code

class Solution:
    def maxConsecutiveAnswers(self, answerKey: str, k: int) -> int:
        length = len(answerKey)
        char_t, char_f = "T", "F"
        max_size = k
        count = defaultdict(int)
        
        for char in answerKey[:k]:
            count[char] += 1

        left = 0
        for right in range(k, length):
            count[answerKey[right]] += 1
            
            while min(count[char_t], count[char_f]) > k: 
                count[answerKey[left]] -= 1
                left += 1
            
            size = right - left + 1
            if size > max_size:
                max_size = size
                    
        return max_size



        

1.664 - 2023-08-02 08:09:23 +0000 UTC

Minimum Size Subarray Sum

Code

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        left = 0
        sum_of_subarray = 0
        min_length = float('inf')
        
        for right in range(len(nums)):
            sum_of_subarray += nums[right]
            
            while sum_of_subarray >= target:
                min_length = min(min_length, right - left + 1)
                sum_of_subarray -= nums[left]
                left += 1

        if min_length == float('inf'):
            return 0

        return min_length

1.665 - 2023-08-02 08:07:07 +0000 UTC

Single Number II

Code

class Solution:
    def singleNumber(self, nums: List[int]) -> int:
        nums.sort()
        length = len(nums)
        for i in range(0, length, 3):
            if i == length - 1:
                return nums[i]
    
            num_1, num_2, num_3 = nums[i], nums[i+1], nums[i+2]

            if num_1 == num_2 == num_3:
                continue
            
            if num_2 == num_3:
                return num_1
            
            if num_1 == num_3:
                return num_2
            
            return num_3
            

1.666 - 2023-08-02 08:00:07 +0000 UTC

Buddy Strings

Code

class Solution:
    def buddyStrings(self, s: str, goal: str) -> bool:
        length_1, length_2 = len(s), len(goal)

        if length_1 != length_2:
            return False
        
        if s == goal:
            freq = defaultdict(int)
            for char in s:
                freq[char] += 1
                if freq[char] == 2:
                    return True
            return False
        
        swap_1, swap_2 = -1, -1
        
        for i in range(length_1):
            char_1, char_2 = s[i], goal[i]
            
            if char_1 == char_2:
                continue
            
            if swap_1 == -1:
                swap_1 = i
            elif swap_2 == -1:
                swap_2 = i
            else:
                return False
            

        return swap_2 != -1 and s[swap_1] == goal[swap_2] and s[swap_2] == goal[swap_1]

1.667 - 2023-08-02 07:39:16 +0000 UTC

Generate Parentheses

Code

class Solution:
    def generateParenthesis(self, n: int) -> List[str]:

        current = []
        current_max = n * 2
        chars = "()"


        def backtrack(open: int, closed: int) -> Generator[None, None, List[str]]:
            if len(current) == current_max:
                yield "".join(current)
            
            if open:
                current.append(chars[0])
                yield from backtrack(open - 1, closed)
                current.pop()
            
            if closed and closed > open:
                current.append(chars[1])
                yield from backtrack(open, closed - 1)
                current.pop()
        
        return tuple(combination for combination in backtrack(n, n))

1.668 - 2023-08-02 07:26:02 +0000 UTC

Permutations

Code

class Solution:
    def permute(self, nums: List[int]) -> List[List[int]]:

        length = len(nums)
        current = []
        current_contains = [False] * length

        def backtrack() -> Generator[None, None, List[int]]:
            if len(current) == length:
                yield tuple(current[:])
                return

            for i in range(length):
                if current_contains[i]:
                    continue

                current_contains[i] = True
                current.append(nums[i])

                yield from backtrack()

                current_contains[i] = False
                current.pop()
            
            return

        return tuple(combination for combination in backtrack()) 

1.669 - 2023-08-01 17:38:09 +0000 UTC

Maximum Number of Achievable Transfer Requests

Code

class Solution:
    def maximumRequests(self, n, requests):
        current = [0] * n
        length = len(requests)
        
        def backtrack(req_index: int, count: int) -> int:
            if req_index == length:
                return 0 if any(current) else count

            req_from, req_to = requests[req_index]
            
            current[req_from] -= 1
            current[req_to] += 1
            take = backtrack(req_index + 1, count + 1)

            current[req_from] += 1
            current[req_to] -= 1
            non_take = backtrack(req_index + 1, count)
            
            return max(take, non_take)
        
        return backtrack(0, 0)

1.670 - 2023-08-01 17:19:26 +0000 UTC

Maximum Number of Achievable Transfer Requests

Code

class Solution:
    def __init__(self):
        self.ans = 0

    def helper(self, start, requests, indegree, n, count):
        if start == len(requests):
            for i in range(n):
                if indegree[i] != 0:
                    return
            self.ans = max(self.ans, count)
            return

        # Take 
        indegree[requests[start][0]] -= 1
        indegree[requests[start][1]] += 1
        self.helper(start + 1, requests, indegree, n, count + 1)

        # Not-take
        indegree[requests[start][0]] += 1
        indegree[requests[start][1]] -= 1
        self.helper(start + 1, requests, indegree, n, count)

    def maximumRequests(self, n, requests):
        indegree = [0] * n
        self.helper(0, requests, indegree, n, 0)
        return self.ans

1.671 - 2023-08-01 15:39:03 +0000 UTC

Count Complete Subarrays in an Array

Code

class Solution:
    def countCompleteSubarrays(self, nums: List[int]) -> int:
        length = len(nums)
        elems_count = len(set(nums))
        
        if elems_count == length:
            return 1
        
        if elems_count == 1:
            return length + sum(i for i in range(1, length))
        
        result, elems, min_j = 0, defaultdict(int), 0
        for i in range(length):
            left = nums[i]
            
            for j in range(min_j, length):
                right = nums[j]
                elems[right] += 1
                
                if len(elems) != elems_count:
                    continue
                
                if elems[right] == 1:
                    elems.pop(right)
                else:
                    elems[right] -= 1 
    
                result += length - j
                min_j = j
                break
            else:
                return result
            
            if elems[left] == 1:
                elems.pop(left)
            else:
                elems[left] -= 1
                    
        return result

1.672 - 2023-08-01 14:52:16 +0000 UTC

Number of Employees Who Met the Target

Code

class Solution:
    def numberOfEmployeesWhoMetTarget(self, hours: List[int], target: int) -> int:
        count = 0
        for hour in hours:
            if hour < target:
                continue
            count += 1
        
        return count

1.673 - 2023-08-01 14:35:47 +0000 UTC

Combinations

Code

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        current = []
        
        def backtrack(first: int) -> Generator[None, None, List[int]]:
            if len(current) == k:
                yield tuple(current[:])
                return

            for i in range(first, n + 1):
                current.append(i)
                yield from backtrack(i + 1)
                current.pop()
            
            return

        return tuple(combination for combination in backtrack(1)) 

1.674 - 2023-08-01 14:33:23 +0000 UTC

Combinations

Code

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        current, result = [], []
        
        def backtrack(first: int) -> None:
            if len(current) == k:
                result.append(tuple(current[:]))
                return

            for i in range(first, n + 1):
                current.append(i)
                backtrack(i + 1)
                current.pop()
            
            return

        backtrack(1)

        return result 

1.675 - 2023-08-01 14:14:55 +0000 UTC

Combinations

Code

class Solution:
    def combine(self, n: int, k: int) -> List[List[int]]:
        def generate_combinations(elems: List[int], num: int):
            total = len(elems)
            if num > total:
                return
            curr_indices = list(range(num))
            reversed_num = tuple(reversed(range(num)))

            while True:
                yield list(elems[i] for i in curr_indices)
                
                for idx in reversed_num:
                    if curr_indices[idx] != idx + total - num:
                        break
                else:
                    return

                curr_indices[idx] += 1
                for j in range(idx+1, num):
                    curr_indices[j] = curr_indices[j-1] + 1

        return [combination for combination in generate_combinations(tuple(range(1, n+1)), k)]

1.676 - 2023-07-31 16:28:12 +0000 UTC

Container With Most Water

Code

class Solution:
    def maxArea(self, height: List[int]) -> int:
        left = 0
        right = len(height) - 1
        maxArea = 0

        while left < right:
            currentArea = min(height[left], height[right]) * (right - left)
            if currentArea > maxArea:
                maxArea = currentArea

            if height[left] < height[right]:
                left += 1
            else:
                right -= 1

        return maxArea

1.677 - 2023-07-31 14:17:46 +0000 UTC

Longest Palindromic Substring

Code

class Solution:
    def longestPalindrome(self, s: str) -> str:
        n = len(s)
        dp = [[False] * n for _ in range(n)]
        ans = [0, 0]
        
        for i in range(n):
            dp[i][i] = True
        
        for i in range(n - 1):
            if s[i] == s[i + 1]:
                dp[i][i + 1] = True
                ans = [i, i + 1]

        for diff in range(2, n):
            for i in range(n - diff):
                j = i + diff
                if s[i] == s[j] and dp[i + 1][j - 1]:
                    dp[i][j] = True
                    ans = [i, j]

        i, j = ans
        return s[i:j + 1]

1.678 - 2023-07-31 11:46:40 +0000 UTC

Minimum ASCII Delete Sum for Two Strings

Code

class Solution:
    def minimumDeleteSum(self, s1: str, s2: str) -> int:
        length_1, length_2 = len(s1), len(s2)

        @cache
        def calculate(i: int, j: int) -> int:    
            if i >= length_1 and j >= length_2:
                return 0
            
            if i >= length_1:
                return sum(ord(char) for char in s2[j:])
            
            if j >= length_2:
                return sum(ord(char) for char in s1[i:])
            
            if s1[i] == s2[j]:
                return calculate(i + 1, j + 1)
            
            return min(
                ord(s1[i]) + calculate(i + 1, j),
                ord(s2[j]) + calculate(i, j + 1)
            )

        return calculate(0, 0)

1.679 - 2023-07-30 17:11:15 +0000 UTC

Strange Printer

Code

class Solution:
    def strangePrinter(self, s: str) -> int:
        n = len(s)
        dp = [[n] * n for _ in range(n)]
        for length in range(1, n + 1):
            for left in range(n - length + 1):
                right = left + length - 1
                j = -1
                for i in range(left, right):
                    if s[i] != s[right] and j == -1:
                        j = i
                    if j != -1:
                        dp[left][right] = min(dp[left][right], 1 + dp[j][i] + dp[i + 1][right])
        
                if j == -1:
                    dp[left][right] = 0

        return dp[0][n - 1] + 1

1.680 - 2023-07-30 07:12:02 +0000 UTC

Predict the Winner

Code

class Solution:
    def PredictTheWinner(self, nums: List[int]) -> bool:
        length = len(nums)
        is_even = length % 2 == 0

        if length < 3:
            return True
        
        @cache
        def max_diff(left: int, right: int) -> int:
            left_num, right_num = nums[left], nums[right]
            
            if left == right:
                return left_num
            
            score_by_left = left_num - max_diff(left + 1, right)
            score_by_right = right_num - max_diff(left, right - 1)
            return max(score_by_left, score_by_right)

        return max_diff(0, length - 1) >= 0

1.681 - 2023-07-29 15:54:20 +0000 UTC

Predict the Winner

Code

class Solution:
    def PredictTheWinner(self, nums: List[int]) -> bool:
        length = len(nums)
        is_even = length % 2 == 0

        if length < 3:
            return True
        
        @cache
        def max_diff(left: int, right: int) -> int:
            left_num, right_num = nums[left], nums[right]
            
            if left == right:
                return left_num
            
            score_by_left = left_num - max_diff(left + 1, right)
            score_by_right = right_num - max_diff(left, right - 1)
            return max(score_by_left, score_by_right)

        return max_diff(0, length - 1) >= 0

1.682 - 2023-07-29 15:51:41 +0000 UTC

Predict the Winner

Code

class Solution:
    def PredictTheWinner(self, nums: List[int]) -> bool:
        length = len(nums)
        is_even = length % 2 == 0

        if length < 3:
            return True
        
        def max_diff(left: int, right: int) -> int:
            left_num, right_num = nums[left], nums[right]
            
            if left == right:
                return left_num
            
            score_by_left = left_num - max_diff(left + 1, right)
            score_by_right = right_num - max_diff(left, right - 1)
            return max(score_by_left, score_by_right)

        return max_diff(0, length - 1) >= 0

1.683 - 2023-07-29 10:24:33 +0000 UTC

Soup Servings

Code

class Solution:
    def soupServings(self, n: int) -> float:
        servings = ceil(n / 25)

        states = defaultdict(dict)
        moves = [[-4, 0], [-3, -1], [-2, -2], [-1, -3]]
    
        @cache
        def calculate(soup_a: int, soup_b: int) -> float:
            if soup_a <= 0 and soup_b <= 0:
                return 0.5
            if soup_a <= 0:
                return 1.0
            if soup_b <= 0:
                return 0.0
            if soup_a in states and soup_b in states[soup_a]:
                return states[soup_a][soup_b]
            
            state = sum(calculate(soup_a + move[0], soup_b + move[1]) for move in moves) / 4.0
            states[soup_a][soup_b] = state

            return state

        max_probability = 1 - 1e-5

        for serving in range(1, servings + 1):
            state = calculate(serving, serving)
            if state > max_probability:
                return 1.0
        
        return calculate(servings, servings)
       

1.684 - 2023-07-27 08:41:11 +0000 UTC

Fair Distribution of Cookies

Code

class Solution:
    def distributeCookies(self, cookies: List[int], k: int) -> int:
        cur = [0] * k
        n = len(cookies)

        def dfs(i, zero_count):
            # If there are not enough cookies remaining, return `float('inf')` 
            # as it leads to an invalid distribution.
            if n - i < zero_count:
                return float('inf')
            
            # After distributing all cookies, return the unfairness of this
            # distribution.
            if i == n:
                return max(cur)
            
            # Try to distribute the i-th cookie to each child, and update answer
            # as the minimum unfairness in these distributions.
            answer = float('inf')
            for j in range(k):
                zero_count -= int(cur[j] == 0)
                cur[j] += cookies[i]
                
                # Recursively distribute the next cookie.
                answer = min(answer, dfs(i + 1, zero_count))
                
                cur[j] -= cookies[i]
                zero_count += int(cur[j] == 0)
            
            return answer
        
        return dfs(0, k)

1.685 - 2023-07-27 08:39:36 +0000 UTC

Fair Distribution of Cookies

Code

class Solution:
    def distributeCookies(self, cookies: List[int], k: int) -> int:
        cur = [0] * k
        n = len(cookies)

        def dfs(i, zero_count):
            # If there are not enough cookies remaining, return `float('inf')` 
            # as it leads to an invalid distribution.
            if n - i < zero_count:
                return float('inf')
            
            # After distributing all cookies, return the unfairness of this
            # distribution.
            if i == n:
                return max(cur)
            
            # Try to distribute the i-th cookie to each child, and update answer
            # as the minimum unfairness in these distributions.
            answer = float('inf')
            for j in range(k):
                zero_count -= int(cur[j] == 0)
                cur[j] += cookies[i]
                
                # Recursively distribute the next cookie.
                answer = min(answer, dfs(i + 1, zero_count))
                
                cur[j] -= cookies[i]
                zero_count += int(cur[j] == 0)
            
            return answer
        
        return dfs(0, k)

1.686 - 2023-07-27 08:28:33 +0000 UTC

Maximum Running Time of N Computers

Code

class Solution:
    # n = 2, batteries = [3,3,3], Output: 4
    # n = 2, batteries = [1,1,1,1], Output: 2
    def maxRunTime(self, n: int, batteries: List[int]) -> int:
        length = len(batteries)

        if length < n:
            return 0
        
        if length == n:
            return min(batteries)

        batteries.sort()
        extra = sum(batteries[:-n])
        live = batteries[-n:]

        
        # We increase the total running time using 'extra' by increasing 
        # the running time of the computer with the smallest battery.
        for i in range(n - 1):
            # If the target running time is between live[i] and live[i + 1].
            if extra // (i + 1) < live[i + 1] - live[i]:
                return live[i] + extra // (i + 1)
            
            # Reduce 'extra' by the total power used.
            extra -= (i + 1) * (live[i + 1] - live[i])
        
        # If there is power left, we can increase the running time 
        # of all computers.
        return live[-1] + extra // n

1.687 - 2023-07-26 19:56:56 +0000 UTC

Minimum Speed to Arrive on Time

Code

class Solution:
    def minSpeedOnTime(self, dist: List[int], hour: float) -> int:
        length = len(dist)
        if hour >= sum(dist):
            return 1
        
        if hour <= length - 1:
            return -1
        
        time_remaining = hour - length + 1
        max_speed = int(max(
            max(dist), dist[-1] // time_remaining + 1
        ))
        min_speed = 1
        result = -1
        while min_speed < max_speed:
            speed = min_speed + (max_speed - min_speed) // 2
            time = dist[-1] / speed + sum(
                (distance + speed - 1) // speed 
                for distance in dist[:-1]
            )
            
            if time > hour:
                min_speed = speed + 1
            else:
                max_speed = speed
        
        return min_speed

1.688 - 2023-07-25 13:45:40 +0000 UTC

Peak Index in a Mountain Array

Code

class Solution:
    # [0,3,2,1,0]
    def peakIndexInMountainArray(self, arr: List[int]) -> int:
        length = len(arr)

        left, right = 0, length - 1
        while left < right:
            mid = left + (right - left) // 2

            if arr[mid] < arr[mid + 1]:
                left = mid + 1
            else:
                right = mid

        return left
        

1.689 - 2023-07-25 13:38:25 +0000 UTC

Peak Index in a Mountain Array

Code

class Solution:
    # [0,3,2,1,0]
    def peakIndexInMountainArray(self, arr: List[int]) -> int:
        length = len(arr)

        left, right = 0, length - 1
        while left <= right:
            peak = left + (right - left) // 2
            left_val, right_val = arr[peak-1], arr[peak+1]
            peak_val = arr[peak]

            if left_val < peak_val > right_val:
                return peak
            
            if right_val > peak_val:
                left = peak + 1
            else:
                right = peak - 1
        
        return left
        

1.690 - 2023-07-24 18:17:10 +0000 UTC

Longest Substring Without Repeating Characters

Code

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        length = len(s)
        if length < 2:
            return length
        
        max_length, left, charset = 1, 0, set([s[0]])
        for right in range(1, length):
            letter = s[right]
            if letter not in charset:
                charset.add(letter)
                continue

            this_length = right - left
            if this_length > max_length:
                max_length = this_length
            
            while letter in charset:
                charset.remove(s[left])
                left += 1
            
            charset.add(letter)

        return max(max_length, length - left)

1.691 - 2023-07-24 18:04:18 +0000 UTC

Longest Substring Without Repeating Characters

Code

class Solution:
    def lengthOfLongestSubstring(self, s: str) -> int:
        length = len(s)
        if length < 2:
            return length
        
        max_length = 0
        start = 0
        indexes = {s[0]: 0}
        for end in range(1, length):
            letter = s[end]
            if letter not in indexes:
                indexes[letter] = end
                continue

            this_length = end - start
            if this_length > max_length:
                max_length = this_length
            
            letter_index = indexes[letter]
            
            for remove_letter in s[start:letter_index]:
                indexes.pop(remove_letter)

            indexes[letter], start = end, letter_index + 1

        return max(max_length, length - start)

1.692 - 2023-07-24 17:07:58 +0000 UTC

Construct the Rectangle

Code

class Solution:
    def constructRectangle(self, area: int) -> List[int]:
        return next([area//width, width] 
                    for width in range(int(area**0.5), 0, -1) 
                    if area % width == 0)

1.693 - 2023-07-24 16:52:59 +0000 UTC

Max Consecutive Ones

Code

class Solution:
    def findMaxConsecutiveOnes(self, nums: List[int]) -> int:
        max_count, count = 0, 0
        for number in nums:
            if not number:
                max_count = max(max_count, count)
                count = 0
                continue
            
            count += 1
        
        return max(max_count, count)

1.694 - 2023-07-24 16:34:48 +0000 UTC

License Key Formatting

Code

class Solution:
    def licenseKeyFormatting(self, s: str, k: int) -> str:
        result = []
        count = 0
        for letter in reversed(s):
            if letter == "-":
                continue

            if count == k:
                result.append("-")
                count = 0
            
            count += 1
            result.append(letter.upper())

        return "".join(reversed(result))

1.695 - 2023-07-24 16:02:15 +0000 UTC

License Key Formatting

Code

class Solution:
    # "5F3Z-2e-9-w" -> "5F3Z2E9W" -> "5F3Z2E9W"
    def licenseKeyFormatting(self, s: str, k: int) -> str:
        letters = s.replace("-", "").upper()
        result = []
        end = len(letters)
        while end > 0:
            start = end - k
            if start < 0:
                start = 0
            result.append(letters[start:end])
            end -= k

        return "-".join(reversed(result))

1.696 - 2023-07-24 15:47:17 +0000 UTC

Island Perimeter

Code

class Solution:
    def islandPerimeter(self, grid: List[List[int]]) -> int:
        perimeter = 0
        last_row = len(grid) - 1        
        last_cell = len(grid[0]) - 1
        for i, row in enumerate(grid):
            for j, cell in enumerate(row):
                if cell == 0:
                    continue
                
                if j == 0 or row[j-1] == 0:
                    perimeter += 1
                
                if j == last_cell or row[j+1] == 0:
                    perimeter += 1
                
                if i == 0 or grid[i-1][j] == 0:
                    perimeter += 1

                if i == last_row or grid[i+1][j] == 0:
                    perimeter += 1
        
        return perimeter
                

1.697 - 2023-07-24 13:56:56 +0000 UTC

Intersection of Two Arrays

Code

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return set(nums1).intersection(nums2)

1.698 - 2023-07-24 13:56:13 +0000 UTC

Intersection of Two Arrays

Code

class Solution:
    def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:
        return set(nums1) & set(nums2)

1.699 - 2023-07-24 13:54:39 +0000 UTC

Find the Difference

Code

class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        letters = defaultdict(int)
        for letter in s:
            letters[letter] += 1

        for letter in t:
            if letters[letter] == 0:
                return letter
            
            letters[letter] -= 1
        
        return None

1.700 - 2023-07-24 13:51:33 +0000 UTC

First Unique Character in a String

Code

class Solution:
    def firstUniqChar(self, s: str) -> int:
        counts = defaultdict(int)
        repeated_index = len(s)
        for letter in s:
            counts[letter] += 1
        
        for i, letter in enumerate(s):
            if counts[letter] != 1:
                continue
            
            return i
        
        return -1

1.701 - 2023-07-24 13:49:38 +0000 UTC

First Unique Character in a String

Code

class Solution:
    def firstUniqChar(self, s: str) -> int:
        counts = {}
        repeated_index = len(s)
        for i, letter in enumerate(s):
            if letter in counts:
                counts[letter] = repeated_index
                continue
            
            counts[letter] = i
        
        result = repeated_index

        for letter, index in counts.items():
            if index == repeated_index:
                continue
            
            if index < result:
                result = index

        return result if result != repeated_index else -1

1.702 - 2023-07-24 13:32:14 +0000 UTC

Sum of Left Leaves

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def sumOfLeftLeaves(self, root: Optional[TreeNode]) -> int:
        nodes = set([root])
        result = 0

        while nodes:
            node = nodes.pop()
            
            if node.left and not node.left.left and not node.left.right:
                result += node.left.val
            elif node.left:
                nodes.add(node.left)
            
            if node.right:
                nodes.add(node.right)
            
        return result

1.703 - 2023-07-24 13:19:40 +0000 UTC

Longest Palindrome

Code

class Solution:
    def longestPalindrome(self, s: str) -> int:
        counts = defaultdict(int)

        for letter in s:
            counts[letter] += 1
        
        result = sum(count if count % 2 == 0 else count - 1
                     for symbol, count in counts.items())

        if result < len(s):
            result += 1

        return result

1.704 - 2023-07-24 13:17:10 +0000 UTC

Longest Palindrome

Code

class Solution:
    def longestPalindrome(self, s: str) -> int:
        counts = defaultdict(int)

        for letter in s:
            counts[letter] += 1
        
        result = 0
        used_odd_letter = False
        for letter, count in counts.items():
            is_odd = count % 2 != 0 
            if is_odd and used_odd_letter:
                result -= 1
            elif is_odd:
                used_odd_letter = True
            result += count

        return result

1.705 - 2023-07-24 10:04:29 +0000 UTC

Third Maximum Number

Code

class Solution:
    def thirdMax(self, nums: List[int]) -> int:
        nums.sort(reverse=True)
        number_max = nums[0]
        count = 1
        for i in range(1, len(nums)):
            number = nums[i]
            if number == nums[i-1]:
                continue
            
            count += 1

            if count == 3:
                return number 
        
        return number_max

1.706 - 2023-07-24 10:03:31 +0000 UTC

Third Maximum Number

Code

class Solution:
    def thirdMax(self, nums: List[int]) -> int:
        nums.sort(reverse=True)
        number_max = nums[0]
        count = 1
        for i in range(1, len(nums)):
            number = nums[i]
            if number == nums[i-1]:
                continue
            
            count += 1

            if count == 3:
                return number 

            if number > number_max:
                number_max = number
        
        return number_max

1.707 - 2023-07-24 09:58:41 +0000 UTC

Add Strings

Code

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        result = []
        index_1, index_2 = len(num1) - 1, len(num2) - 1


        carry = 0
        while index_1 >= 0 or index_2 >= 0 or carry:
            digit_1 = num1[index_1] if index_1 >= 0 else 0
            digit_2 = num2[index_2] if index_2 >= 0 else 0
            digit = int(digit_1) + int(digit_2) + carry
            if digit > 9:
                carry = 1
                digit %= 10
            else:
                carry = 0

            result.append(str(digit))
            index_1 -= 1
            index_2 -= 1 

        return "".join(reversed(result))

1.708 - 2023-07-24 09:56:22 +0000 UTC

Add Strings

Code

class Solution:
    def addStrings(self, num1: str, num2: str) -> str:
        result = []
        length_1, length_2 = len(num1), len(num2)
        index_1, index_2 = length_1 - 1, length_2 - 1


        carry = 0
        while index_1 >= 0 or index_2 >= 0 or carry:
            digit_1 = num1[index_1] if index_1 >= 0 else 0
            digit_2 = num2[index_2] if index_2 >= 0 else 0
            digit = int(digit_1) + int(digit_2) + carry
            if digit > 9:
                carry = 1
                digit %= 10
            else:
                carry = 0

            result.append(str(digit))
            index_1 -= 1
            index_2 -= 1 

        return "".join(reversed(result))

1.709 - 2023-07-24 09:44:43 +0000 UTC

Assign Cookies

Code

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        g.sort(reverse=True)
        s.sort(reverse=True)
        count = 0
        cookie_index = 0
        cookie_count = len(s)
        for greed in g:
            if cookie_index >= cookie_count or greed > s[cookie_index]:
                continue

            count += 1
            cookie_index += 1
            
        return count

1.710 - 2023-07-24 09:40:04 +0000 UTC

Assign Cookies

Code

class Solution:
    def findContentChildren(self, g: List[int], s: List[int]) -> int:
        greed = 0
        g.sort(reverse=True)
        s.sort(reverse=True)
        children_count = len(g)
        count = 0
        for cookie_size in s:
            while greed < children_count and g[greed] > cookie_size:
                greed += 1
            
            if greed >= children_count:
                break

            count += 1
            greed += 1
            
        return count

1.711 - 2023-07-24 08:13:00 +0000 UTC

Pow(x, n)

Code

class Solution:
    def myPow(self, x: float, n: int) -> float:
        if n == 0:
            return 1

        if n < 0:
            n *= -1
            x = 1 / x

        result = 1
        while n:
            if n % 2:
                result *= x
                n -= 1
            x *= x
            n //= 2
        
        return result

1.712 - 2023-07-23 18:12:51 +0000 UTC

Find All Numbers Disappeared in an Array

Code

class Solution:
    # [1,1,3,4], [1,2,3,4] -> [2]
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        for number in nums:
            index = abs(number) - 1
            nums[index] = -1 * abs(nums[index])
        
        return [number
                for number in range(1, len(nums) + 1) 
                if nums[number-1] > 0]
        

1.713 - 2023-07-23 18:01:06 +0000 UTC

Find All Numbers Disappeared in an Array

Code

class Solution:
    # [1,1,3,4], [1,2,3,4] -> [2]
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        result = {number: True for number in range(1, len(nums) + 1)}

        for number in nums:
            result[number] = False
        
        return [number for number, valid in result.items() if valid]

1.714 - 2023-07-23 17:55:57 +0000 UTC

Find All Numbers Disappeared in an Array

Code

class Solution:
    # [1,1,3,4], [1,2,3,4] -> [2]
    def findDisappearedNumbers(self, nums: List[int]) -> List[int]:
        nums.sort()
        result = []
        length = len(nums)
        j = 0
        for i in range(1, length + 1):
            while j < length and nums[j] < i:
                j += 1
            
            if j < length and nums[j] == i:
                continue

            result.append(i)

        return result

1.715 - 2023-07-23 17:18:00 +0000 UTC

Arranging Coins

Code

class Solution:
    def arrangeCoins(self, n: int) -> int:
        left, right = 0, n

        while left <= right:
            middle = left + (right - left) // 2
            coins = middle * (middle + 1) // 2

            if coins == n:
                return middle
            
            if coins > n:
                right = middle - 1
            else:
                left = middle + 1
        
        return right

1.716 - 2023-07-23 17:03:43 +0000 UTC

Arranging Coins

Code

class Solution:
    def arrangeCoins(self, n: int) -> int:
        count = 0
        row = 1
        while n >= row:
            n -= row
            row += 1
            count += 1

        return count

1.717 - 2023-07-23 16:57:13 +0000 UTC

Middle of the Linked List

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        slow = fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        
        return slow

1.718 - 2023-07-23 16:55:42 +0000 UTC

Middle of the Linked List

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
        middle = head.next if head else None 
        tail = middle.next if middle else None
        move = True
        while tail and tail.next:
            tail = tail.next
            if move:
                middle = middle.next
            
            move = not move

        return middle if middle else head

1.719 - 2023-07-23 13:50:34 +0000 UTC

All Possible Full Binary Trees

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def allPossibleFBT(self, n: int) -> List[TreeNode]:
        if n % 2 == 0:
            return []
        if n == 1:
            return [TreeNode()]

        res = []
        for i in range(1, n, 2):
            left = self.allPossibleFBT(i)
            right = self.allPossibleFBT(n - i - 1)

            for l in left:
                for r in right:
                    root = TreeNode(0, l, r)
                    res.append(root)

        return res

1.720 - 2023-07-22 16:09:00 +0000 UTC

Knight Probability in Chessboard

Code

class Solution:
    # y x x
    # x x x
    # x x x: (2 / 8) * (4 / 16) = 0.0625
    #        (1/8, 1/8), (2/8, 2/8)
    # 
    # x x x
    # x y x
    # x x x: 0
    def __init__(self):
        self.available_moves = (
            (2, 1), (1, 2), (-2, 1), (-1, 2), (2, -1), (1, -2), 
            (-2, -1), (-1, -2)
        )
    

    def knightProbability(self, n: int, k: int, row: int, column: int) -> float:
        if k < 1:
            return 1
        
        if n < 3:
            return 0

        return self.calculate(row, column, n, k)
    
    @cache
    def calculate(self, row: int, column: int, size: int, 
                       moves_left: int) -> float:
       
        if moves_left < 1:
            return 1

        probability = 0

        for row_add, column_add in self.available_moves:
            new_row = row_add + row
            new_column = column_add + column

            if new_row < 0 or new_row >= size or (
                new_column < 0 or new_column >= size
            ):
                continue

            probability += self.calculate(
                new_row, new_column, size, moves_left - 1
            ) / 8

        return probability

1.721 - 2023-07-22 14:36:35 +0000 UTC

Knight Probability in Chessboard

Code

class Solution:
    def knightProbability(self, n: int, k: int, row: int, column: int) -> float:
        # Define possible directions for the knight's moves
        directions = [(1, 2), (1, -2), (-1, 2), (-1, -2),
                      (2, 1), (2, -1), (-2, 1), (-2, -1)]

        # Initialize the dynamic programming table
        dp = [[[0] * n for _ in range(n)] for _ in range(k + 1)]
        dp[0][row][column] = 1

        # Iterate over the number of moves
        for moves in range(1, k + 1):
            # Iterate over the cells on the chessboard
            for i in range(n):
                for j in range(n):
                    # Iterate over possible directions
                    for direction in directions:
                        prev_i, prev_j = i - direction[0], j - direction[1]
                        # Check if the previous cell is within the chessboard
                        if 0 <= prev_i < n and 0 <= prev_j < n:
                            # Add the previous probability
                            dp[moves][i][j] += dp[moves - 1][prev_i][prev_j]
                    # Divide by 8
                    dp[moves][i][j] /= 8

        # Calculate total probability by summing probabilities for all cells
        total_probability = sum(
            dp[k][i][j]
            for i in range(n)
            for j in range(n)
        )
        return total_probability

1.722 - 2023-07-21 13:55:34 +0000 UTC

Repeated Substring Pattern

Code

class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        length = len(s)
        for i in range(1, length // 2 + 1):
            if length % i != 0:
                continue
            
            if s == s[:i] * (length // i):
                return True
        
        return False

1.723 - 2023-07-21 13:53:22 +0000 UTC

Repeated Substring Pattern

Code

class Solution:
    def repeatedSubstringPattern(self, s: str) -> bool:
        length = len(s)
        for i in range(length-1):
            if length % (i + 1) != 0:
                continue
            
            if s == s[:i+1] * (length // (i + 1)):
                return True
        
        return False

1.724 - 2023-07-21 13:40:56 +0000 UTC

Add Digits

Code

class Solution:
    def addDigits(self, num: int) -> int:
        sum = 0
        while num > 0:
            sum += num % 10
            num //= 10
        
            if num == 0 and sum > 9:
                num, sum = sum, 0
                
        return sum

1.725 - 2023-07-21 13:40:33 +0000 UTC

Add Digits

Code

class Solution:
    def addDigits(self, num: int) -> int:
        sum = 0
        while num > 0:
            sum += num % 10
            num //= 10
        
            if num == 0 and sum > 9:
                num, sum = sum, 0
                
        return sum

1.726 - 2023-07-21 13:40:14 +0000 UTC

Add Digits

Code

class Solution:
    def addDigits(self, num: int) -> int:
        sum = 0
        while num > 0:
            sum += num % 10
            num //= 10
        
            if num == 0 and sum > 9:
                num, sum = sum, 0
                
        return sum

1.727 - 2023-07-21 13:36:57 +0000 UTC

Add Digits

Code

class Solution:
    def addDigits(self, num: int) -> int:
        sum = num
        while sum > 9:
            current_number, current_sum = sum, 0
            while current_number:
                current_sum += current_number % 10
                current_number //= 10
            sum = current_sum
        return sum

1.728 - 2023-07-21 13:30:39 +0000 UTC

Implement Queue using Stacks

Code

class MyQueue:

    def __init__(self):
        self.stack_in = []
        self.stack_out = []

    def push(self, x: int) -> None:
        self.stack_in.append(x)

    def pop(self) -> int:
        self.peek()
        return self.stack_out.pop()

    def peek(self) -> int:
        if self.stack_out:
            return self.stack_out[-1]
        
        while self.stack_in:
            self.stack_out.append(self.stack_in.pop())

        return self.stack_out[-1]

    def empty(self) -> bool:
        return not self.stack_out and not self.stack_in


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

1.729 - 2023-07-21 13:20:49 +0000 UTC

Implement Queue using Stacks

Code

class MyQueue:

    def __init__(self):
        self.queue = []

    def push(self, x: int) -> None:
        self.queue.insert(0, x)

    def pop(self) -> int:
        return self.queue.pop()

    def peek(self) -> int:
        return self.queue[-1]

    def empty(self) -> bool:
        return len(self.queue) == 0


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

1.730 - 2023-07-21 13:09:40 +0000 UTC

Implement Queue using Stacks

Code

class MyQueue:

    def __init__(self):
        self.queue = deque()

    def push(self, x: int) -> None:
        self.queue.appendleft(x)

    def pop(self) -> int:
        return self.queue.pop()

    def peek(self) -> int:
        return self.queue[-1]

    def empty(self) -> bool:
        return len(self.queue) == 0


# Your MyQueue object will be instantiated and called as such:
# obj = MyQueue()
# obj.push(x)
# param_2 = obj.pop()
# param_3 = obj.peek()
# param_4 = obj.empty()

1.731 - 2023-07-21 13:06:08 +0000 UTC

Power of Two

Code

class Solution:
    def isPowerOfTwo(self, n: int) -> bool:
        if n == 1:
            return True

        while n > 2 and not n % 2:
            n //= 2
        return n == 2

1.732 - 2023-07-21 12:59:33 +0000 UTC

Remove Duplicates from Sorted List

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def deleteDuplicates(self, head: Optional[ListNode]) -> Optional[ListNode]:
        result = head
        
        while head and head.next:
            if head.next.val == head.val:
                head.next = head.next.next
                continue
            
            head = head.next
        
        return result

1.733 - 2023-07-21 12:52:55 +0000 UTC

Climbing Stairs

Code

class Solution:
    # 1: 1
    # 2: 2
    # 3: 3 [2(2), 1(1)]
    # 4: 5 [3(3), (2)]
    def climbStairs(self, n: int) -> int:
        if n < 3:
            return n

        count, count_prev = 2, 1
        for number in range(3, n + 1):
            count, count_prev = count + count_prev, count
        return count

1.734 - 2023-07-21 12:33:25 +0000 UTC

Plus One

Code

class Solution:
    def plusOne(self, digits: List[int]) -> List[int]:
        carry = 1
        for i in reversed(range(len(digits))):
            new_digit = digits[i] + carry
            if new_digit > 9:
                carry = 1
                new_digit %= 10
            else:
                carry = 0
            digits[i] = new_digit
        
        if carry:
            digits.insert(0, carry)
        
        return digits

1.735 - 2023-07-21 10:34:45 +0000 UTC

Number of Steps to Reduce a Number to Zero

Code

class Solution:
    def numberOfSteps(self, num: int) -> int:
        count = 0
        while num:
            count += 1
            if num % 2 == 0:
                num /= 2
            else:
                num -= 1
        
        return count
            

1.736 - 2023-07-21 10:33:01 +0000 UTC

Fizz Buzz

Code

class Solution:
    def fizzBuzz(self, n: int) -> List[str]:
        result = []

        for i in range(1, n + 1):
            div_by_3, div_by_5 = i % 3 == 0, i % 5 == 0
            value = None

            if div_by_3 and div_by_5:
                value = "FizzBuzz"
            elif div_by_3:
                value = "Fizz"
            elif div_by_5:
                value = "Buzz"
            else:
                value = str(i)
            
            result.append(value)
        
        return result

1.737 - 2023-07-21 10:26:34 +0000 UTC

Richest Customer Wealth

Code

class Solution:
    def maximumWealth(self, accounts: List[List[int]]) -> int:
        max_wealth = 0
        for i in range(len(accounts)):
            wealth = 0
            for j in range(len(accounts[i])):
                wealth += accounts[i][j]
            
            if wealth > max_wealth:
                max_wealth = wealth
        
        return max_wealth

1.738 - 2023-07-21 10:23:06 +0000 UTC

Running Sum of 1d Array

Code

class Solution:
    def runningSum(self, nums: List[int]) -> List[int]:
        for i in range(1, len(nums)):
            nums[i] += nums[i-1]
        return nums

1.739 - 2023-07-21 10:19:55 +0000 UTC

Root Equals Sum of Children

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def checkTree(self, root: Optional[TreeNode]) -> bool:
        return root.val == (root.left.val + root.right.val)

1.740 - 2023-07-21 10:18:37 +0000 UTC

Add Two Integers

Code

class Solution:
    def sum(self, num1: int, num2: int) -> int:
        return num1 + num2

1.741 - 2023-07-21 10:11:37 +0000 UTC

Number of Longest Increasing Subsequence

Code

class Solution:
    def findNumberOfLIS(self, nums: List[int]) -> int:
        n = len(nums)
        if n <= 1:
            return n

        lengths = [1] * n
        counts = [1] * n

        for i in range(1, n):
            for j in range(i):
                if nums[i] > nums[j]:
                    if lengths[j] + 1 > lengths[i]:
                        lengths[i] = lengths[j] + 1
                        counts[i] = counts[j]
                    elif lengths[j] + 1 == lengths[i]:
                        counts[i] += counts[j]

        max_length = max(lengths)
        return sum(count for length, count in zip(lengths, counts) if length == max_length)

1.742 - 2023-07-20 09:12:22 +0000 UTC

Asteroid Collision

Code

class Solution:
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
        stack = []
        for asteroid in asteroids:
            if asteroid > 0:
                stack.append(asteroid)
                continue
            
            asteroid_abs = abs(asteroid)
            while stack and stack[-1] > 0 and stack[-1] < asteroid_abs:
                stack.pop()
            
            if stack and stack[-1] == asteroid_abs:
                stack.pop()
            elif not stack or stack[-1] < 0:
                stack.append(asteroid)

        return stack

1.743 - 2023-07-20 08:41:51 +0000 UTC

Asteroid Collision

Code

class Solution:
    def asteroidCollision(self, asteroids: List[int]) -> List[int]:
        length = len(asteroids)

        if length < 2:
            return asteroids

        stack = [asteroids[0]]
        for i in range(1, length):
            asteroid = asteroids[i]
            asteroid_last = stack[-1] if stack else 0
            stack.append(asteroid)

            if asteroid > 0 or (
                asteroid < 0 and asteroid_last < 0
            ):
                continue

            while len(stack) >= 2 and stack[-1] < 0 and stack[-2] > 0:
                last, prev = abs(stack[-1]), abs(stack[-2])
                if last == prev:
                    stack.pop()
                elif last > prev:
                    stack[-1], stack[-2] = stack[-2], stack[-1]

                stack.pop()

        return stack

1.744 - 2023-07-19 11:35:52 +0000 UTC

Best Time to Buy and Sell Stock II

Code

class Solution:
    def maxProfit(self, prices: List[int]) -> int:
		# It is impossible to sell stock on first day, set -infinity as initial value for cur_hold
        cur_hold, cur_not_hold = -float('inf'), 0
        
        for stock_price in prices:
            prev_hold, prev_not_hold = cur_hold, cur_not_hold
			# either keep hold, or buy in stock today at stock price
            cur_hold = max(prev_hold, prev_not_hold - stock_price)
			
			# either keep not-hold, or sell out stock today at stock price
            cur_not_hold = max(prev_not_hold, 
                               prev_hold + stock_price)
            
        # maximum profit must be in not-hold state
        return cur_not_hold

1.745 - 2023-07-19 11:26:39 +0000 UTC

Gas Station

Code

class Solution:
    def canCompleteCircuit(self, gas: List[int], cost: List[int]) -> int:
        if sum(gas) < sum(cost): 
            return -1
        
        tank, idx = 0, 0
        for i in range(len(gas)):
            tank += gas[i] - cost[i] 
            if tank < 0: 
                tank, idx = 0, i+1
        return idx 

1.746 - 2023-07-19 11:19:51 +0000 UTC

Jump Game II

Code

class Solution:
    def jump(self, nums: List[int]) -> int:
        length = len(nums)
        result = 0
        end = 0
        farthest = 0

        for i in range(length - 1):
            number = nums[i]
            max_jump = i + number
            if max_jump > farthest:
                farthest = max_jump

            if farthest >= length - 1:
                result += 1
                break
            
            if i == end:
                result += 1
                end = farthest


        return result

1.747 - 2023-07-19 11:19:26 +0000 UTC

Minimum Size Subarray Sum

Code

class Solution:
    def minSubArrayLen(self, target: int, nums: List[int]) -> int:
        left = 0
        sum_of_subarray = 0
        min_length = float('inf')
        
        for right in range(len(nums)):
            sum_of_subarray += nums[right]
            
            while sum_of_subarray >= target:
                min_length = min(min_length, right - left + 1)
                sum_of_subarray -= nums[left]
                left += 1

        if min_length == float('inf'):
            return 0

        return min_length

1.748 - 2023-07-19 10:39:31 +0000 UTC

H-Index

Code

class Solution:
    # [3,0,6,1,5]
    # [0,1,3,5,6]
    def hIndex(self, citations: List[int]) -> int:
        citations = sorted(citations)
        length = len(citations)

        h = 0
        for i in reversed(range(length)):
            citations_count = citations[i]
            published_count = length - i

            if citations_count == 0 or published_count < h:
                break

            if published_count <= citations_count:
                h = published_count
            
        return h

1.749 - 2023-07-19 09:33:23 +0000 UTC

Zigzag Conversion

Code

class Solution:
    def convert(self, s: str, numRows: int) -> str:
        if numRows < 2:
            return s
        
        result: List[List[str]] = [[] for _ in range(numRows)]
    
        row, is_ascending, last = 0, True, numRows - 1
        for symbol in s:
            result[row].append(symbol)
            
            if is_ascending and row < last:
                row += 1
            elif is_ascending:
                is_ascending = False
            
            if is_ascending:
                continue

            if row > 0:
                row -= 1
            else:
                is_ascending = True
                row = 1
    
        
        return "".join("".join(row) for row in result)

1.750 - 2023-07-19 08:49:03 +0000 UTC

Insert Delete GetRandom O(1)

Code

class RandomizedSet:

    def __init__(self):
        self._set = set()
        self._items = []
        self._indexes = {}
        

    def insert(self, val: int) -> bool:
        is_in = val in self._set
        if not is_in:
            self._set.add(val)
            self._items.append(val)
            self._indexes[val] = len(self._items) - 1
        return not is_in

    def remove(self, val: int) -> bool:
        if val not in self._set:
            return False

        last = self._items[-1]
        val_index = self._indexes[val]
        self._items[val_index] = last
        self._indexes[last] = val_index
        
        self._set.remove(val)
        self._items.pop()
        self._indexes.pop(val)

        return True

    def getRandom(self) -> int:
        return random.choice(self._items)


# Your RandomizedSet object will be instantiated and called as such:
# obj = RandomizedSet()
# param_1 = obj.insert(val)
# param_2 = obj.remove(val)
# param_3 = obj.getRandom()

1.751 - 2023-07-19 08:34:17 +0000 UTC

Jump Game

Code

class Solution:
    def canJump(self, nums: List[int]) -> bool:
        length = len(nums)

        if length < 2:
            return True
        
        current = nums[0]

        for i in range(1, length):
            if current == 0:
                return False
            current -= 1
            current = max(current, nums[i])
        
        return True
            

1.752 - 2023-07-19 08:26:05 +0000 UTC

Letter Combinations of a Phone Number

Code

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        length = len(digits)
        if length == 0:
            return []
        
        digit_map: Dict[int, str] = {
            1: [],
            2: ["a", "b", "c"],
            3: ["d", "e", "f"],
            4: ["g", "h", "i"],
            5: ["j", "k", "l"],
            6: ["m", "n", "o"],
            7: ["p", "q", "r", "s"],
            8: ["t", "u", "v"],
            9: ["w", "x", "y", "z"],
            0: [" "]
        }
        result: List[List[str]] = [
            digit_map[int(digit)] for digit in digits
        ]
        return ["".join(i) for i in product(*result)]

1.753 - 2023-07-19 08:25:19 +0000 UTC

Letter Combinations of a Phone Number

Code

class Solution:
    def letterCombinations(self, digits: str) -> List[str]:
        length = len(digits)
        if length == 0:
            return []
        
        digit_map: Dict[int, str] = {
            1: [],
            2: ["a", "b", "c"],
            3: ["d", "e", "f"],
            4: ["g", "h", "i"],
            5: ["j", "k", "l"],
            6: ["m", "n", "o"],
            7: ["p", "q", "r", "s"],
            8: ["t", "u", "v"],
            9: ["w", "x", "y", "z"],
            0: [" "]
        }
        result: List[List[str]] = [
            digit_map[int(digit)] for digit in digits
        ]
        return ["".join(i) for i in product(*result)]

1.754 - 2023-07-19 08:14:44 +0000 UTC

Non-overlapping Intervals

Code

class Solution:
    def eraseOverlapIntervals(self, intervals: List[List[int]]) -> int:
        intervals = sorted(intervals, key=lambda element: element[1])
        length = len(intervals)
        prev, count = 0, 1

        for i in range(1, length):
            if intervals[i][0] < intervals[prev][1]:
                continue
            
            prev = i
            count += 1
        
        return length - count

1.755 - 2023-07-18 15:51:03 +0000 UTC

Add Two Numbers

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    # create the result pointer that points towards one of the lists
    # create the result root pointer that will point towards the root of the result list
    # 1. start infinite loop
    # 2. if result is false - break, we reached the end
    # 3. get values from non-empty pointers
    # 4. add values together, store the carry in a variable
    # 5. store the value in the result pointer
    # 6. move the result pointer to the next node, if there is no next node, use a node from
    #    another list
    # 7. move list pointers
    # 8. if we have a carry left, add a node to the result list
    def addTwoNumbers(self, l1: Optional[ListNode], 
                            l2: Optional[ListNode]) -> Optional[ListNode]:
        carry = 0
        result, result_root = l1, l1

        while True:
            if not l1 and not l2:
                break
            
            number_1 = l1.val if l1 else 0
            number_2 = l2.val if l2 else 0
            result_val = number_1 + number_2 + carry
            if result_val > 9:
                carry, result_val = 1, result_val - 10
            else:
                carry = 0
            
            result.val = result_val
            if not result.next and l2:
                l1 = None
                result.next = l2.next

            if result.next:
                result = result.next
            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next

        if carry:
            result.next = ListNode(carry)

        return result_root

1.756 - 2023-07-18 15:50:17 +0000 UTC

LRU Cache

Code

class LRUCache:
    class Node:
        def __init__(self, key: str, val: int) -> None:
            self.key = key
            self.val = val
            self.prev: Node = None
            self.next: Node = None

    def __init__(self, capacity: int) -> None:
        self.cap = capacity
        self.head = self.Node(-1, -1)
        self.tail = self.Node(-1, -1)
        self.head.next = self.tail
        self.tail.prev = self.head
        self.cache = {}

    def add_node(self, new_node: Node) -> None:
        old_first_node = self.head.next
        new_node.next = old_first_node
        new_node.prev = self.head
        self.head.next = new_node
        old_first_node.prev = new_node

    def delete_node(self, delete_node: Node) -> None:
        prev = delete_node.prev
        next = delete_node.next
        prev.next = next
        next.prev = prev

    def get(self, key: int) -> int:
        if key not in self.cache:
            return -1
        result_node = self.cache[key]
        result = result_node.val
        del self.cache[key]
        self.delete_node(result_node)
        self.add_node(result_node)
        self.cache[key] = self.head.next
        return result
    

    def put(self, key: int, value: int) -> None:
        if key in self.cache:
            current = self.cache[key]
            del self.cache[key]
            self.delete_node(current)

        if len(self.cache) == self.cap:
            del self.cache[self.tail.prev.key]
            self.delete_node(self.tail.prev)

        self.add_node(self.Node(key, value))
        self.cache[key] = self.head.next

# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)

1.757 - 2023-07-18 15:39:57 +0000 UTC

LRU Cache

Code

class LRUCache:
    class Node:
        def __init__(self, key: str, val: int) -> None:
            self.key = key
            self.val = val
            self.prev: Node = None
            self.next: Node = None

    def __init__(self, capacity: int) -> None:
        self.cap = capacity
        self.head = self.Node(-1, -1)
        self.tail = self.Node(-1, -1)
        self.head.next = self.tail
        self.tail.prev = self.head
        self.cache = {}

    def add_node(self, new_node: Node) -> None:
        old_first_node = self.head.next
        new_node.next = old_first_node
        new_node.prev = self.head
        self.head.next = new_node
        old_first_node.prev = new_node

    def delete_node(self, delete_node: Node) -> None:
        prev = delete_node.prev
        next = delete_node.next
        prev.next = next
        next.prev = prev

    def get(self, key: int) -> int:
        if key not in self.cache:
            return -1
        result_node = self.cache[key]
        result = result_node.val
        del self.cache[key]
        self.delete_node(result_node)
        self.add_node(result_node)
        self.cache[key] = self.head.next
        return result
    

    def put(self, key: int, value: int) -> None:
        if key in self.cache:
            current = self.cache[key]
            del self.cache[key]
            self.delete_node(current)

        if len(self.cache) == self.cap:
            del self.cache[self.tail.prev.key]
            self.delete_node(self.tail.prev)

        self.add_node(self.Node(key, value))
        self.cache[key] = self.head.next

# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)

1.758 - 2023-07-18 15:25:23 +0000 UTC

Search a 2D Matrix

Code

class Solution:
    def searchMatrix(self, matrix: List[List[int]], target: int) -> bool:
        length_vertical, length_horizontal = len(matrix), len(matrix[0])


        left, right = 0, length_vertical - 1
        while left <= right:
            mid = left + (right - left) // 2
            mid_number = matrix[mid][0]
            
            if mid_number == target:
                return True
            
            if mid_number > target:
                right = mid - 1
            else:
                left = mid + 1
        
        vertical_index = right
        left, right = 0, length_horizontal - 1
        while left <= right:
            mid = left + (right - left) // 2
            mid_number = matrix[vertical_index][mid]

            if mid_number == target:
                return True
            
            if mid_number > target:
                right = mid - 1
            else:
                left = mid + 1
            
        return False

1.759 - 2023-07-18 15:14:47 +0000 UTC

Search Insert Position

Code

class Solution:
    def searchInsert(self, nums: List[int], target: int) -> int:
        length = len(nums)
        left, right = 0, length - 1

        while left <= right:
            mid = left + (right - left) // 2
            mid_number = nums[mid]

            if mid_number == target:
                return mid

            if mid_number > target:
                right = mid - 1
            else:
                left = mid + 1

        return left

1.760 - 2023-07-18 15:10:20 +0000 UTC

Sqrt(x)

Code

class Solution:
    def mySqrt(self, x: int) -> int:
        if x == 0 or x == 1:
            return x

        left, right = 1, x

        while left <= right:
            mid = left + (right - left) // 2
            square = mid * mid

            if square == x:
                return mid
            
            if square > x:
                right = mid - 1 
            else:
                left = mid + 1
            
        return right

1.761 - 2023-07-18 15:02:32 +0000 UTC

Palindrome Number

Code

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False
        
        if x < 10:
            return True
        
        number = []

        while x:
            remainder = x % 10
            x = x // 10
            number.append(remainder)
            
        length = len(number)
        half_index = length // 2

        for i, digit in enumerate(number):
            last_digit = number[length - i - 1]

            if digit != last_digit:
                return False
            
            if i != half_index:
                continue
            
            return True

1.762 - 2023-07-18 15:01:12 +0000 UTC

Palindrome Number

Code

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False
        
        if x < 10:
            return True
        
        number = []

        while x:
            remainder = x % 10
            x = x // 10
            number.append(remainder)
            
        length = len(number)
        half_index = length // 2

        for i, digit in enumerate(number):
            last_digit = number[length - i - 1]

            if digit != last_digit:
                return False
            
            if i != half_index:
                continue
            
            return True

1.763 - 2023-07-18 14:58:35 +0000 UTC

Evaluate Reverse Polish Notation

Code

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        operations = {
            "+": lambda first, second: first + second,
            "-": lambda first, second: first - second,
            "*": lambda first, second: first * second,
            "/": lambda first, second: int(first / second)
        }
        for token in tokens:
            if token not in operations:
                stack.append(int(token))
                continue

            second, first = stack.pop(), stack.pop()
            result = operations[token](first, second)
            stack.append(result)
            
        return stack[-1]

1.764 - 2023-07-18 14:57:21 +0000 UTC

Add Two Numbers II

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverse(self, head: ListNode) -> ListNode:
        previous = None
        while head:
            next, head.next = head.next, previous
            previous, head = head, next
        return previous

    def addTwoNumbers(self, l1: Optional[ListNode], l2: Optional[ListNode]) -> Optional[ListNode]:
        l1, l2 = self.reverse(l1), self.reverse(l2)
        head, tail, carry = l1, l1, 0

        while l1 or l2 or carry:
            val_1 = l1.val if l1 else 0
            val_2 = l2.val if l2 else 0
            sum = val_1 + val_2 + carry
            if sum > 9:
                carry = 1
                sum %= 10
            else:
                carry = 0

            tail.val = sum
            l1, l2 = l1.next if l1 else None, l2.next if l2 else None
            if not tail.next and l2:
                tail.next = l2
                l1 = None

            if not tail.next and carry:
                tail.next = ListNode(carry)
                carry = 0
                l2 = None

            if tail.next:
                tail = tail.next
            
        return self.reverse(head)

1.765 - 2023-07-18 14:10:30 +0000 UTC

Reverse Linked List

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        previous = None
        while head:
            next, head.next = head.next, previous
            previous, head = head, next

        return previous

1.766 - 2023-07-18 13:55:29 +0000 UTC

Two Sum II - Input Array Is Sorted

Code

class Solution:
    def twoSum(self, numbers: List[int], target: int) -> List[int]:
        numbers_map: Dict[str, int] = {}

        for i, number in enumerate(numbers):
            diff = target - number
            if diff in numbers_map:
                return [numbers_map[diff] + 1, i + 1]
            numbers_map[number] = i
        
        return []

1.767 - 2023-07-18 13:41:40 +0000 UTC

Reverse Words in a String

Code

class Solution:
    def reverseWords(self, s: str) -> str:
        return " ".join(s.split()[::-1])

1.768 - 2023-07-18 13:37:43 +0000 UTC

Integer to Roman

Code

class Solution:
    def intToRoman(self, num: int) -> str:
        result: List[str] = []
        stack: List[int] = deque([
            1, 4, 5, 9, 10, 40, 50, 90, 100, 400, 500, 900, 1000
        ])
        values = {
            1000: "M",
            900: "CM",
            500: "D",
            400: "CD",
            100: "C",
            90: "XC",
            50: "L",
            40: "XL",
            10: "X",
            9: "IX",
            5: "V",
            4: "IV",  
            1: "I"
        }

        while num:
            roman = stack[-1]
            if num < roman:
                stack.pop()
                continue

            result.append(values[roman])
            num -= roman

        return "".join(result)

1.769 - 2023-07-18 13:15:43 +0000 UTC

Evaluate Reverse Polish Notation

Code

class Solution:
    def evalRPN(self, tokens: List[str]) -> int:
        stack = []
        operations = {
            "+": lambda first, second: first + second,
            "-": lambda first, second: first - second,
            "*": lambda first, second: first * second,
            "/": lambda first, second: int(first / second)
        }
        for token in tokens:
            if token not in operations:
                stack.append(int(token))
                continue

            second, first = stack.pop(), stack.pop()
            result = operations[token](first, second)
            stack.append(result)
            
        return stack[-1]

1.770 - 2023-07-18 12:49:17 +0000 UTC

Min Stack

Code

from sortedcontainers import sortedset

class MinStack:

    def __init__(self):
        self.stack: List[int] = []
        self.min_stack: List[int] = []

    def push(self, val: int) -> None:
        self.stack.append(val)
        if not self.min_stack or val <= self.min_stack[-1]:
            self.min_stack.append(val)

    def pop(self) -> None:
        if not self.stack:
            return
        pop = self.stack.pop()
        if pop == self.min_stack[-1]:
            self.min_stack.pop()

    def top(self) -> int:
        return self.stack[-1]

    def getMin(self) -> int:
        return self.min_stack[-1]


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

1.771 - 2023-07-18 12:46:05 +0000 UTC

Min Stack

Code

from sortedcontainers import sortedset

class MinStack:
    class Node:
        def __init__(self, val: int, prev: 'Node'):
            self.val = val
            self.prev = prev


    def __init__(self):
        self.stack: List[Node] = []
        self.min_node = None

    def push(self, val: int) -> None:
        new_node = self.Node(val, None)
        self.stack.append(new_node)
        if self.min_node is None or val <= self.min_node.val:
            new_node.prev = self.min_node
            self.min_node = new_node

    def pop(self) -> None:
        pop = self.stack.pop()
        if pop == self.min_node:
            self.min_node = self.min_node.prev

    def top(self) -> int:
        return self.stack[-1].val

    def getMin(self) -> int:
        return self.min_node.val


# Your MinStack object will be instantiated and called as such:
# obj = MinStack()
# obj.push(val)
# obj.pop()
# param_3 = obj.top()
# param_4 = obj.getMin()

1.772 - 2023-07-18 12:23:22 +0000 UTC

Simplify Path

Code

class Solution:
    def simplifyPath(self, path: str) -> str:
        canonical = []
        for directory in path.split("/"):
            if not directory or directory == ".":
                continue
            
            if directory != "..":
                canonical.append(directory)
                continue
            
            if len(canonical):
                canonical.pop()

        return "/" + "/".join(canonical)

1.773 - 2023-07-18 12:15:34 +0000 UTC

Longest Consecutive Sequence

Code

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        length = len(nums)
        if length < 2:
            return length
        
        nums = set(nums)
        longest = 1
        for number in nums:
            if number - 1 in nums:
                continue
            consequent = 1
            while number + consequent in nums:
                consequent += 1
            longest = max(longest, consequent)
        
        return longest

1.774 - 2023-07-18 12:08:44 +0000 UTC

Longest Consecutive Sequence

Code

from sortedcontainers import SortedSet

class Solution:
    def longestConsecutive(self, nums: List[int]) -> int:
        nums = SortedSet(nums)
        longest, current = 0, 0
        for number in nums:
            if number - 1 in nums:
                current += 1
                continue
            if current > longest:
                longest = current
            current = 1
        return max(current, longest)
            

1.775 - 2023-07-18 11:53:17 +0000 UTC

Group Anagrams

Code

class Solution:
    def groupAnagrams(self, strs: List[str]) -> List[List[str]]:
        anagrams: Dict[str, List[str]] = defaultdict(list)

        for string in strs:
            anagrams["".join(sorted(string))].append(string)
        
        return anagrams.values()

1.776 - 2023-07-18 11:46:38 +0000 UTC

LRU Cache

Code

class LRUCache:
    class Node:
        def __init__(self, key: str, val: int) -> None:
            self.key = key
            self.val = val
            self.prev: Node = None
            self.next: Node = None

    def __init__(self, capacity: int) -> None:
        self.cap = capacity
        self.head = self.Node(-1, -1)
        self.tail = self.Node(-1, -1)
        self.head.next = self.tail
        self.tail.prev = self.head
        self.cache = {}

    def add_node(self, new_node: Node) -> None:
        old_first_node = self.head.next
        new_node.next = old_first_node
        new_node.prev = self.head
        self.head.next = new_node
        old_first_node.prev = new_node

    def delete_node(self, delete_node: Node) -> None:
        prev = delete_node.prev
        next = delete_node.next
        prev.next = next
        next.prev = prev

    def get(self, key: int) -> int:
        if key not in self.cache:
            return -1
        result_node = self.cache[key]
        result = result_node.val
        del self.cache[key]
        self.delete_node(result_node)
        self.add_node(result_node)
        self.cache[key] = self.head.next
        return result
    

    def put(self, key: int, value: int) -> None:
        if key in self.cache:
            current = self.cache[key]
            del self.cache[key]
            self.delete_node(current)

        if len(self.cache) == self.cap:
            del self.cache[self.tail.prev.key]
            self.delete_node(self.tail.prev)

        self.add_node(self.Node(key, value))
        self.cache[key] = self.head.next

# Your LRUCache object will be instantiated and called as such:
# obj = LRUCache(capacity)
# param_1 = obj.get(key)
# obj.put(key,value)

1.777 - 2023-07-18 10:48:20 +0000 UTC

Rotate Array

Code

class Solution:
    def rotate(self, nums: List[int], k: int) -> None:
        """
        Do not return anything, modify nums in-place instead.
        """
        length = len(nums)
        k %= length
        nums[length - k:] = nums[length - k:][::-1]  
        nums[:length - k] = nums[:length - k][::-1]   
        nums[:] = nums[::-1] 

1.778 - 2023-07-16 16:26:31 +0000 UTC

Remove Duplicates from Sorted Array II

Code

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        length = len(nums)

        if length < 2:
            return length
        
        current_index = 2

        for number in nums[2:]:
            if number == nums[current_index-2]:
                continue
            
            nums[current_index] = number
            current_index += 1

        return current_index

1.779 - 2023-07-16 16:19:33 +0000 UTC

Remove Duplicates from Sorted Array II

Code

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        length = len(nums)

        if length < 2:
            return length
        
        current_number, unique, current_index = nums[0], True, 1
        for number in nums[1:]:
            if current_number != number:
                current_number = number
                unique = True
                nums[current_index] = number
                current_index += 1
                continue

            if unique:
                nums[current_index] = number
                current_index += 1
                unique = False

        return current_index

1.780 - 2023-07-16 15:35:46 +0000 UTC

Same Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        if p and not q or (q and not p):
            return False
        
        if not p and not q:
            return True
        
        if p.val != q.val:
            return False
        
        return self.isSameTree(p.left, q.left) and self.isSameTree(p.right, q.right)

1.781 - 2023-07-16 12:06:38 +0000 UTC

Maximum Depth of Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: Optional[TreeNode], depth: int = 0) -> int:
        if not root:
            return depth

        return max(self.maxDepth(root.left, depth + 1), self.maxDepth(root.right, depth + 1))
        

1.782 - 2023-07-16 12:04:36 +0000 UTC

Maximum Depth of Binary Tree

Code

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def maxDepth(self, root: Optional[TreeNode], count: int = 0) -> int:
        if not root:
            return 0
        
        if not root.left and not root.right:
            return count + 1

        return max(self.maxDepth(root.left, count + 1), self.maxDepth(root.right, count + 1))
        

1.783 - 2023-07-16 10:34:50 +0000 UTC

Merge Two Sorted Lists

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        if not list1:
            return list2
        
        if not list2:
            return list1
        
        head = None
        if list1.val < list2.val:
            head, list1 = list1, list1.next 
        else:
            head, list2 = list2, list2.next
        
        current = head
        while list1 and list2:
            if list1.val < list2.val:
                current.next, list1 = list1, list1.next
            else:
                current.next, list2 = list2, list2.next
            
            current = current.next

        if list1 or list2:
            current.next = list1 if list1 else list2

        return head

1.784 - 2023-07-16 09:53:42 +0000 UTC

Linked List Cycle

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow_p, fast_p = head, head.next if head else None
        while fast_p and fast_p.next:
            if slow_p == fast_p:
                return True
            slow_p, fast_p = slow_p.next, fast_p.next.next

        return False

1.785 - 2023-07-16 09:51:01 +0000 UTC

Linked List Cycle

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def hasCycle(self, head: Optional[ListNode]) -> bool:
        slow_p, fast_p = head, head.next if head else None
        while slow_p and fast_p:
            if slow_p == fast_p:
                return True
            slow_p = slow_p.next
            fast_p = fast_p.next if fast_p else None
            fast_p = fast_p.next if fast_p else None
        
        return False

1.786 - 2023-07-16 09:38:36 +0000 UTC

Valid Parentheses

Code

class Solution:
    def isValid(self, s: str) -> bool:
        length = len(s)
        if length < 2:
            return False

        brackets_open = {
            "{": "}",
            "(": ")",
            "[": "]"
        }
        brackets_close = brackets_open.values()
        stack = [s[0]]

        for bracket in s[1:]:
            if bracket not in brackets_close:
                stack.append(bracket)
                continue

            if len(stack) == 0 or brackets_open.get(stack[-1]) != bracket:
                return False
            
            stack.pop()

        return not len(stack) 

1.787 - 2023-07-16 09:17:02 +0000 UTC

Contains Duplicate II

Code

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        indexes = {}
        for i, number in enumerate(nums):
            if number in indexes and abs(i - indexes[number]) <= k:
                return True
            indexes[number] = i
        return False

            

1.788 - 2023-07-16 09:16:10 +0000 UTC

Contains Duplicate II

Code

class Solution:
    def containsNearbyDuplicate(self, nums: List[int], k: int) -> bool:
        indexes = defaultdict(set)
        for i, number in enumerate(nums):
            if number in indexes and any(abs(i - j) <= k for j in indexes[number]):
                return True
            indexes[number].add(i)
        return False

            

1.789 - 2023-07-16 07:47:21 +0000 UTC

Happy Number

Code

class Solution:
    def isHappy(self, n: int) -> bool:
        sums = set()
        while n != 1:
            if n in sums:
                return False
            sums.add(n)
            
            sum = 0
            while n > 0:
                sum += (n % 10 )**2
                n = n // 10
            n = sum

        return True

1.790 - 2023-07-16 07:41:43 +0000 UTC

Happy Number

Code

class Solution:
    def isHappy(self, n: int) -> bool:
        while True:
            sum = 0
            while n > 0:
                sum += (n % 10 )**2
                n = n // 10
            n = sum
            if sum < 10:
                break

        return n in [1, 7]

1.791 - 2023-07-16 07:41:26 +0000 UTC

Happy Number

Code

class Solution:
    def isHappy(self, n: int) -> bool:
        while True:
            sum = 0
            while n > 0:
                sum += (n % 10 )**2
                n = n // 10
            n = sum
            print(n)
            if sum < 10:
                break

        return n in [1, 7]

1.792 - 2023-07-15 18:24:48 +0000 UTC

Two Sum

Code

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        indexes = {}
        for i, number in enumerate(nums):
            diff = target - number
            if diff in indexes: 
                return [indexes[diff], i]
            indexes[number] = i

1.793 - 2023-07-15 18:22:16 +0000 UTC

Valid Anagram

Code

class Solution:
    def isAnagram(self, s: str, t: str) -> bool:
        s_length, t_length = len(s), len(t)

        if s_length != t_length:
            return False
        
        count = defaultdict(int)
        for i, s_symbol in enumerate(s):
            t_symbol = t[i]
            count[s_symbol] += 1
            count[t_symbol] -= 1

        return not any((i != 0 for i in count.values())) 

1.794 - 2023-07-15 18:11:36 +0000 UTC

Word Pattern

Code

class Solution:
    def wordPattern(self, pattern: str, s: str) -> bool:
        words = s.split()
        words_length, pattern_length = len(words), len(pattern)

        if words_length != pattern_length:
            return False
        
        symbol_to_word = {}
        word_to_symbol = {}

        for i, symbol in enumerate(pattern):
            word = words[i]
            symbol_in, word_in = symbol in symbol_to_word, word in word_to_symbol

            if symbol_in and word_in and symbol_to_word[symbol] == word:
                continue

            if not symbol_in and not word_in:
                symbol_to_word[symbol] = word
                word_to_symbol[word] = symbol
                continue

            return False
        
        return True
            

1.795 - 2023-07-15 17:53:31 +0000 UTC

Isomorphic Strings

Code

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        s_length, t_length = len(s), len(t)
        if s_length != t_length:
            return False
        
        s_to_t = {}
        t_to_s = {}
        for i, s_symbol in enumerate(s):
            t_symbol = t[i]

            if s_symbol not in s_to_t and t_symbol not in t_to_s:
                s_to_t[s_symbol] = t_symbol
                t_to_s[t_symbol] = s_symbol
            elif s_symbol in s_to_t and s_to_t[s_symbol] == t_symbol:
                continue
            else:
                return False
                
        return True

1.796 - 2023-07-15 17:49:31 +0000 UTC

Isomorphic Strings

Code

class Solution:
    def isIsomorphic(self, s: str, t: str) -> bool:
        return list(map(s.index, s)) == list(map(t.index, t))

1.797 - 2023-07-15 17:05:44 +0000 UTC

Ransom Note

Code

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        ransom_i, magazine_i = 0, 0
        ransom_length, magazine_length = len(ransomNote), len(magazine)

        if magazine_length < ransom_length:
            return False
        
        if ransom_length == 1:
            return ransomNote in magazine

        symbols = [0 for _ in range(26)]

        for symbol in magazine:
            symbols[ord(symbol)-97] += 1

        for symbol in ransomNote:
            symbols[ord(symbol)-97] -= 1
        
        
        return not any((count < 0 for count in symbols))

1.798 - 2023-07-15 16:55:32 +0000 UTC

Ransom Note

Code

class Solution:
    # two indexes: ransom_i, magazine_i
    # sort both ransomNote and magazine (ascending order)
    # while indexes have not reached the end:
    # - if ransom symbol is equal to the magazine_symbol: increase both indexes
    # - if it is not equal, increase only magazine index
    # return wheter the ranson index is equal to the length of the ransom
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        ransom_i, magazine_i = 0, 0
        ransom_length, magazine_length = len(ransomNote), len(magazine)

        if magazine_length < ransom_length:
            return False
        
        if ransom_length == 1:
            return ransomNote in magazine

        ransomNote = sorted(ransomNote)
        magazine = sorted(magazine)

        while ransom_i < ransom_length and magazine_i < magazine_length:
            ransom_symbol, magazine_symbol = ransomNote[ransom_i], magazine[magazine_i]
            
            if magazine_symbol > ransom_symbol:
                return False

            if ransom_symbol == magazine_symbol:
                ransom_i += 1
            
            magazine_i += 1

        return ransom_i == ransom_length

1.799 - 2023-07-15 16:35:16 +0000 UTC

Ransom Note

Code

class Solution:
    # two indexes: ransom_i, magazine_i
    # sort both ransomNote and magazine (ascending order)
    # while indexes have not reached the end:
    # - if ransom symbol is equal to the magazine_symbol: increase both indexes
    # - if it is not equal, increase only magazine index
    # return wheter the ranson index is equal to the length of the ransom
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        ransom_i, magazine_i = 0, 0
        ransom_length, magazine_length = len(ransomNote), len(magazine)
        ransomNote = sorted(ransomNote)
        magazine = sorted(magazine)

        if magazine_length < ransom_length:
            return False

        while ransom_i < ransom_length and magazine_i < magazine_length:
            ransom_symbol, magazine_symbol = ransomNote[ransom_i], magazine[magazine_i]
            
            if ransom_symbol == magazine_symbol:
                ransom_i += 1
                
            magazine_i += 1

        return ransom_i == ransom_length

1.800 - 2023-07-13 18:11:33 +0000 UTC

Is Subsequence

Code

class Solution:
    # create two pointers, original and sub, both are zero
    # while either of those pointers have not reached the end:
    # - if original symbol is equal to the sub, move both pointer to the right
    # - if not, move original pointer to the right
    # if sub pointer reached the end, return True, otherwise False
    def isSubsequence(self, s: str, t: str) -> bool:
        original, sub = 0, 0
        original_length, sub_length = len(t), len(s)

        while original < original_length and sub < sub_length:
            if s[sub] == t[original]:
                original += 1
                sub += 1
                continue
            
            original += 1

        return sub == sub_length

1.801 - 2023-07-13 17:57:51 +0000 UTC

Longest Common Prefix

Code

class Solution:
    
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if len(strs) == 1:
            return strs[0]

        min_length = min([len(string) for string in strs])
        prefix = strs[0][0:min_length]
        for string in strs:
            if not prefix:
                return ""
            
            while not string.startswith(prefix):
                prefix = prefix[0:-1]
            
        return prefix

1.802 - 2023-07-13 17:49:03 +0000 UTC

Longest Common Prefix

Code

class Solution:
    
    def longestCommonPrefix(self, strs: List[str]) -> str:
        if len(strs) == 1:
            return strs[0]

        min_length = min([len(string) for string in strs])
        for i in range(min_length, -1, -1):
            current = strs[0][0:i+1]
            for string in strs[1:]:
                if string[0:i+1] != current:
                    break
            else:
                return current

        return ""    

1.803 - 2023-07-13 17:34:54 +0000 UTC

Roman to Integer

Code

class Solution:
    def romanToInt(self, input_numbers: str) -> int:
        result = 0
        previous = None
        values = {
            "I": 1,
            "V": 5,
            "X": 10,
            "L": 50,
            "C": 100,
            "D": 500,
            "M": 1000,
        }
        subtractions = set(["IV", "IX", "XL", "XC", "CD", "CM"])

        for number in input_numbers:
            if f"{previous}{number}" in subtractions:
                result += values[number] - values[previous] * 2
            else:
                result += values[number]
            previous = number
        
        return result
            

1.804 - 2023-07-13 17:32:03 +0000 UTC

Majority Element

Code

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        return sorted(nums)[len(nums)//2]
                

1.805 - 2023-07-13 17:30:18 +0000 UTC

Best Time to Buy and Sell Stock

Code

class Solution:
    # Input: prices = [7,1,5,3,6,4]
    # Output: 5
    # Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
    # Note that buying on day 2 and selling on day 1 is not allowed because you must buy 
    # before you sell.
    def maxProfit(self, prices: List[int]) -> int:
        length = len(prices)
        if length < 2:
            return 0

        left, right, profit = 0, 1, 0
        while right < length:
            current_profit = prices[right] - prices[left]
            is_profitable = current_profit > 0
            if is_profitable and current_profit > profit:
                profit = current_profit
            elif not is_profitable:
                left = right
            
            right += 1

        return profit

1.806 - 2023-07-13 17:19:45 +0000 UTC

Best Time to Buy and Sell Stock

Code

class Solution:
    # Input: prices = [7,1,5,3,6,4]
    # Output: 5
    # Explanation: Buy on day 2 (price = 1) and sell on day 5 (price = 6), profit = 6-1 = 5.
    # Note that buying on day 2 and selling on day 1 is not allowed because you must buy 
    # before you sell.
    def maxProfit(self, prices: List[int]) -> int:
        length = len(prices)
        if length < 2:
            return 0

        left, right, profit = 0, 1, 0
        while right < length:
            current_profit = prices[right] - prices[left]
            if current_profit > 0:
                profit = max(current_profit, profit)
            else:
                left = right
            right += 1

        return profit

1.807 - 2023-07-13 16:37:36 +0000 UTC

Majority Element

Code

class Solution:
    def majorityElement(self, nums: List[int]) -> int:
        return sorted(nums)[len(nums)//2]
                

1.808 - 2023-07-13 16:13:31 +0000 UTC

Remove Duplicates from Sorted Array

Code

class Solution:
    # non-decreasing order, so to remove the duplicates we just need to remove all 
    #    consequent duplicates
    # create replace index, set it to 1 - the first element is always unique
    # check if length is more than 1 to avoid out-of-bounds - 
    #   if the length is one, just return 1
    # iterate over nums starting from the second element:
    # - if the current number is not equal to the previous, 
    #   set nums[replace] to it, move the replace index
    # - if the current number is equal to the previous one, continue 
    # return replace 
    def removeDuplicates(self, nums: List[int]) -> int:
        replace = 1
        for i, number in enumerate(nums[1:], 1): 
            if number == nums[i-1]:
                continue
            nums[replace] = number
            replace += 1
        
        return replace

1.809 - 2023-07-13 16:03:15 +0000 UTC

Remove Duplicates from Sorted Array

Code

class Solution:
    # non-decreasing order, so to remove the duplicates we just need to remove all 
    #    consequent duplicates
    # create replace index, set it to 0
    # create a set of duplicates
    # iterate over nums:
    # - if the number is in the set, continue
    # - if the number is not in the set, set nums[replace] to that number, add it to the set
    # return replace
    def removeDuplicates(self, nums: List[int]) -> int:
        replace, duplicates = 0, set()
        for i, number in enumerate(nums): 
            if number in duplicates:
                continue
            nums[replace] = number
            replace += 1
            duplicates.add(number)
        
        return replace

1.810 - 2023-07-13 15:52:44 +0000 UTC

Remove Element

Code

class Solution:
    # create replace index
    # iterate over nums:
    # - if the current number is equal to val, continue
    # - set nums[replace] to that number, increase the index

    def removeElement(self, nums: List[int], val: int) -> int:
        replace = 0
        for i, number in enumerate(nums):
            if number == val:
                continue
            nums[replace] = number
            replace += 1
        
        return replace

1.811 - 2023-07-13 15:46:43 +0000 UTC

Remove Element

Code

class Solution:
    # create two indexes, current and replace
    # create non_val_count
    # while to-be-replaced has not reached the end:
    # - if the current number is a regular number, move the current index, 
    #   increase non_val_count
    # - if the replace index is equal or less than the current, move it and continue
    # - if the replace number is a non-regular number, move the replace index and continue
    # - if the current number is a non-regular, replace it with the replace number, 
    #   replace the replace number with val, move both indexes
    # return the current index + 1

    def removeElement(self, nums: List[int], val: int) -> int:
        current, replace, val_count, length = 0, 0, 0, len(nums)
        non_val_count = 0
        
        while replace < length and current < length:
            current_number, replace_number = nums[current], nums[replace]
            
            if current_number != val:
                current += 1
                non_val_count += 1
                continue

            if replace <= current:
                replace = current + 1
                continue

            if replace_number == val:
                replace += 1
                continue

            nums[current], nums[replace] = replace_number, val
            replace += 1
            current += 1
            non_val_count += 1
            
        return non_val_count

1.812 - 2023-07-12 17:34:00 +0000 UTC

Merge Sorted Array

Code

class Solution:
    # have three indexes: nums1 (end of array 1), nums2 (from the end), 
    # and current (nums1 from the end) 
    # if nums2 number is bigger or equal than nums1 number, put the number at the current index,
    # move both indexes
    # if nums1 number is smaller than nums2 number, put the number at the current index, 
    # move both indexes  
    def merge(self, nums1: List[int], m: int, nums2: List[int], n: int) -> None:
        """
        Do not return anything, modify nums1 in-place instead.
        """

        nums1_i, nums2_i = m - 1, n - 1
        for i in range(m + n - 1, -1, -1):
            nums1_number  = nums1[nums1_i] if nums1_i >= 0 else nums2[0] - 1
            nums2_number = nums2[nums2_i] if nums2_i >= 0 else nums1[0] - 1
            if nums1_number >= nums2_number:
                nums1[i] = nums1_number
                nums1_i -= 1
                continue
            
            nums1[i] = nums2_number
            nums2_i -= 1

1.813 - 2023-07-11 14:42:28 +0000 UTC

Valid Palindrome

Code

class Solution:
    def isPalindrome(self, s: str) -> bool:
        length = len(s)

        # if the sring has only one symbol and it is alphanumeric, it is a palyndrom
        if s.isalnum() and length == 1:
            return True 
        
        i, j = 0, length - 1
        # iterate from the start and from the end using two indexes:
        # - if one the symbols is not alphanumeric, move the corresponding index
        # - if symbols are alphanumeric and not equal, return False
        # - move indexes
        while i < j:
            symbol_start, symbol_end = s[i].lower(), s[j].lower()
            if not symbol_start.isalnum():
                i += 1
                continue
            if not symbol_end.isalnum():
                j -= 1
                continue
            
            if symbol_start != symbol_end:
                return False
            
            i += 1
            j -= 1
        
        return True

1.814 - 2023-07-11 14:40:20 +0000 UTC

Valid Palindrome

Code

class Solution:
    def isPalindrome(self, s: str) -> bool:
        length = len(s)

        # if the sring has only one symbol and it is alphanumeric, it is a palyndrom
        if s.isalnum() and length == 1:
            return True 
        
        i, j = 0, length - 1
        # iterate from start and from end:
    # - if the symbol is not alphanumeric, skip
    # - if the symbol is alphanumeric, compare
    # - if indexes are equal or reversed, return
        while i < j:
            symbol_start, symbol_end = s[i].lower(), s[j].lower()
            if not symbol_start.isalnum():
                i += 1
                continue
            if not symbol_end.isalnum():
                j -= 1
                continue
            
            if symbol_start != symbol_end:
                return False
            
            i += 1
            j -= 1
        
        return True

1.815 - 2023-07-10 12:59:08 +0000 UTC

Find the Index of the First Occurrence in a String

Code

class Solution:
    # check edge cases:
    # - if length of the needle is less than the length of the haystack: -1
    # - if strings are equal: 0
    # - if length of the needle is equal to the length of the haystack, but 
    #   strings are not equal: -1
    # iterate over haystack and needle cheking if a substring starting with the current symbol
    # is equal to the needle
    def strStr(self, haystack: str, needle: str) -> int:
        length_needle, length_haystack = len(needle), len(haystack)
        last_needle_index = length_needle - 1

        if length_needle > length_haystack:
            return -1
        
        if haystack == needle:
            return 0

        if length_needle == length_haystack:
            return -1
        
        if needle == haystack:
            return 0

        for i, _ in enumerate(haystack):
            current_needle = haystack[i:i+length_needle]
            if current_needle == needle:
                return i
        return -1

1.816 - 2023-07-10 12:57:30 +0000 UTC

Find the Index of the First Occurrence in a String

Code

class Solution:
    # check edge cases:
    # - if length of the needle is less than the length of the haystack: -1
    # - if strings are equal: 0
    # - if length of the needle is equal to the length of the haystack, but 
    #   strings are not equal: -1
    # iterate over haystack and needle cheking if a symbol from haystack 
    #   corresponds to the symbol in needle
    def strStr(self, haystack: str, needle: str) -> int:
        length_needle, length_haystack = len(needle), len(haystack)
        last_needle_index = length_needle - 1

        if length_needle > length_haystack:
            return -1
        
        if haystack == needle:
            return 0

        if length_needle == length_haystack:
            return -1
        
        if needle == haystack:
            return 0

        j = length_needle
        for i, _ in enumerate(haystack):
            current_needle = haystack[i:j]
            if current_needle == needle:
                return i
            j += 1
        
        return -1

1.817 - 2023-07-10 12:49:18 +0000 UTC

Find the Index of the First Occurrence in a String

Code

class Solution:
    # check edge cases:
    # - if length of the needle is less than the length of the haystack: -1
    # - if strings are equal: 0
    # - if length of the needle is equal to the length of the haystack, but 
    #   strings are not equal: -1
    # iterate over haystack and needle cheking if a symbol from haystack 
    #   corresponds to the symbol in needle
    def strStr(self, haystack: str, needle: str) -> int:
        length_needle, length_haystack = len(needle), len(haystack)
        last_needle_index = length_needle - 1

        if length_needle > length_haystack:
            return -1
        
        if haystack == needle:
            return 0

        if length_needle == length_haystack:
            return -1
        
        if needle == haystack:
            return 0

        i, j = 0, length_needle
        while j <= len(haystack):
            current_needle = haystack[i:j]
            if current_needle == needle:
                return i

            i += 1
            j += 1
        
        return -1

1.818 - 2023-07-08 15:57:18 +0000 UTC

Length of Last Word

Code

class Solution:
    # we need to iterate over the string searching for words
    # add a whitespace to the end to avoid the situation when the last symbol is non-whitespace 
    # possible combinations:
    # 1. a whitespace after a symbol: end of the word
    # 2. a whitespace after a whitespace: ignore
    # 3. a symbol after a symbol: ignore
    def lengthOfLastWord(self, s: str) -> int:
        s += " "
        result, word_length = 0, 0

        for i, symbol in enumerate(s):
            if symbol != " ":
                word_length += 1
                continue
            
            if word_length > 0:
                result = word_length
                word_length = 0
        
        return result

1.819 - 2023-07-08 15:48:01 +0000 UTC

Length of Last Word

Code

class Solution:
    # we need to iterate over the string searching for words
    # possible combinations:
    # 1. a whitespace after a symbol: end of the word
    # 2. a whitespace after a whitespace: ignore
    # 3. a symbol after a symbol, but it's the last symbol: end of the last word
    # 4. a symbol after a symbol: ignore
    def lengthOfLastWord(self, s: str) -> int:
        length = len(s)
        if length == 1:
            return 1

        word_start, word_end, in_word = 0, 0, False

        for i, symbol in enumerate(s):
            is_whitespace = symbol == " "
            is_last = i == length - 1
            
            if is_whitespace and in_word:
                in_word = False
                word_end = i - 1
                continue
            
            if is_whitespace and not in_word:
                continue

            if not is_whitespace and in_word and is_last:
                word_end = i
                continue

            if not is_whitespace and not in_word and is_last:
                word_end = i
                word_start = i
                continue

            if not is_whitespace and in_word:
                continue

            if not is_whitespace and not in_word:
                word_start = i
                in_word = True
                continue
            
        return word_end - word_start + 1

1.820 - 2023-07-08 15:25:39 +0000 UTC

Length of Last Word

Code

class Solution:
    def lengthOfLastWord(self, s: str) -> int:
        return len(s.split()[-1])

1.821 - 2023-07-06 17:44:21 +0000 UTC

Add Two Numbers

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    # create the result pointer that points towards one of the lists
    # create the result root pointer that will point towards the root of the result list
    # 1. start infinite loop
    # 2. if result is false - break, we reached the end
    # 3. get values from non-empty pointers
    # 4. add values together, store the carry in a variable
    # 5. store the value in the result pointer
    # 6. move the result pointer to the next node, if there is no next node, use a node from
    #    another list
    # 7. move list pointers
    # 8. if we have a carry left, add a node to the result list
    def addTwoNumbers(self, l1: Optional[ListNode], 
                            l2: Optional[ListNode]) -> Optional[ListNode]:
        carry = 0
        result, result_root = l1, l1

        while True:
            if not l1 and not l2:
                break
            
            number_1 = l1.val if l1 else 0
            number_2 = l2.val if l2 else 0
            result_val = number_1 + number_2 + carry
            if result_val > 9:
                carry, result_val = 1, result_val - 10
            else:
                carry = 0
            
            result.val = result_val
            if not result.next and l2:
                l1 = None
                result.next = l2.next

            if result.next:
                result = result.next
            if l1:
                l1 = l1.next
            if l2:
                l2 = l2.next

        if carry:
            result.next = ListNode(carry)

        return result_root

1.822 - 2023-07-06 12:43:40 +0000 UTC

Roman to Integer

Code

class Solution:
    def romanToInt(self, input_numbers: str) -> int:
        result = 0
        previous = None
        values = {
            "I": 1,
            "V": 5,
            "X": 10,
            "L": 50,
            "C": 100,
            "D": 500,
            "M": 1000,
        }
        subtractions = set(["IV", "IX", "XL", "XC", "CD", "CM"])

        for number in input_numbers:
            if f"{previous}{number}" in subtractions:
                result = result - values[previous] * 2 + values[number]
            else:
                result += values[number]
            previous = number
        
        return result
            

1.823 - 2023-05-24 10:25:03 +0000 UTC

Remove Element

Code

class Solution:
    def removeElement(self, nums: List[int], val: int) -> int:
        length = len(nums)

        if not length: 
            return 0

        first = nums[0]
        if length == 1 and first == val:
            nums.pop()
            return 0
        if length == 1 and first != val:
            return 1
        
        not_equal_index = -1 if first == val else 0
        for i, number in enumerate(nums[1:], 1):
            if number == val:
                continue

            not_equal_index += 1
            nums[not_equal_index] = number

        return not_equal_index + 1
            

1.824 - 2023-05-24 10:11:40 +0000 UTC

Remove Duplicates from Sorted Array

Code

class Solution:
    def removeDuplicates(self, nums: List[int]) -> int:
        length = len(nums)
        if length == 1:
            return 1
        
        unique_count = 1
        last_unique_index = 0
        for i, number in enumerate(nums[1:], 1):
            last_unique = nums[last_unique_index]
            if number == last_unique:
                continue
            
            unique_count += 1
            last_unique_index += 1
            nums[last_unique_index] = number

        nums = nums[:last_unique_index+1]

        return unique_count

1.825 - 2023-05-24 09:54:30 +0000 UTC

Merge Two Sorted Lists

Code

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next

class Solution:
    def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:
        result = ListNode()
        current = result
        while list1 and list2:               
            if list1.val < list2.val:
                current.next = list1
                list1, current = list1.next, list1
                continue

            current.next = list2
            list2, current = list2.next, list2
                
        if list1 or list2:
            current.next = list1 if list1 else list2
            
        return result.next

1.826 - 2023-05-24 09:13:29 +0000 UTC

Valid Parentheses

Code

class Solution:
    def isValid(self, s: str) -> bool:
        brackets = []

        symbols = {
            "{": "}",
            "(": ")",
            "[": "]"
        }

        open = symbols.keys()
        closed = symbols.values()

        for bracket in s:
            if bracket in open:
                brackets.append(bracket)
                continue

            if not brackets:
                return False

            last_bracket = brackets[-1]
            if last_bracket in closed: 
                return False

            correct_closing_bracket = symbols[last_bracket]
            if bracket != correct_closing_bracket:
                return False
            
            brackets.pop()

        return not len(brackets)

1.827 - 2023-05-24 08:52:15 +0000 UTC

Palindrome Number

Code

class Solution:
    def isPalindrome(self, x: int) -> bool:
        if x < 0:
            return False
        
        if x < 10:
            return True
        
        number = []

        while True:
            remainder = x % 10
            x = int(x / 10)
            number.append(remainder)
            if not x:
                break
            
        
        number.reverse()
        print(number)
        length = len(number)
        half_index = int(length / 2)

        for i, digit in enumerate(number):
            last_digit = number[length - i - 1]

            if digit != last_digit:
                return False
            
            if i != half_index:
                continue
            
            return True

1.828 - 2023-05-24 08:37:01 +0000 UTC

Longest Common Prefix

Code

class Solution:
    def longestCommonPrefix(self, strs: List[str]) -> str:
        answer = []
        strings = sorted(strs)
        first = strings[0]
        last = strings[-1]
        min_length = min(len(first), len(last))
        for i in range(min_length):
            first_symbol = first[i]
            last_symbol = last[i]
            if first_symbol == last_symbol:
                answer.append(first_symbol)
                continue
            
            return "".join(answer)

        return "".join(answer)


        

1.829 - 2023-05-24 08:26:20 +0000 UTC

Roman to Integer

Code

class Solution:
    def romanToInt(self, s: str) -> int:
        result = 0
        skip = False

        values = {
            "I": 1,
            "V": 5,
            "X": 10,
            "L": 50,
            "C": 100,
            "D": 500,
            "M": 1000
        }
        special_cases = {
            "I": ["V", "X"],
            "X": ["L", "C"],
            "C": ["D", "M"]
        }

        for i, symbol in enumerate(s):
            if skip:
                skip = False
                continue

            next = None
            if i < (len(s) - 1):
                next = s[i+1]

            if next in special_cases.get(symbol, []):
                skip = True
                result += values[next] - values[symbol]
                continue
            
            result += values[symbol]

        return result
            

1.830 - 2023-05-24 08:15:01 +0000 UTC

Roman to Integer

Code

class Solution:
    def romanToInt(self, s: str) -> int:
        result = 0
        skip = False
        for i, symbol in enumerate(s):
            if skip:
                skip = False
                continue

            next = ""
            if i < len(s) - 1:
                next = s[i+1]
            
            if symbol == "I" and next == "V":
                result += 4
                skip = True
                continue

            if symbol == "I" and next == "X":
                result += 9
                skip = True
                continue
            
            if symbol == "I":
                result += 1
                continue

            if symbol == "X" and next == "L":
                result += 40
                skip = True
                continue

            if symbol == "X" and next == "C":
                result += 90
                skip = True
                continue
            
            if symbol == "X":
                result += 10
                continue

            if symbol == "C" and next == "D":
                result += 400
                skip = True
                continue
            
            if symbol == "C" and next == "M":
                result += 900
                skip = True
                continue
            
            if symbol == "C":
                result += 100
                continue
            
            if symbol == "V":
                result += 5
                continue
            
            if symbol == "D":
                result += 500
                continue
            
            if symbol == "M":
                result += 1000
                continue
            
            if symbol == "L":
                result += 50
                continue
            
            raise Exception(f"unexpected situation: {symbol}, {next}")

        return result
            

1.831 - 2023-05-23 09:36:30 +0000 UTC

Two Sum

Code

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        indexes = {}
        for i, number in enumerate(nums):
            diff = target - number
            if diff in indexes: 
                return [indexes[diff], i]
            indexes[number] = i

1.832 - 2023-05-23 09:30:44 +0000 UTC

Two Sum

Code

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        for i, number in enumerate(nums):
            for j, number_inner in enumerate(nums[i+1:]):
                if number + number_inner == target:
                    return [i, i+j+1]

2 - Autoscroll

CLI app for autoscroll

About The Project

This package implements platfrom-independent autoscroll

Features

  • Pretty useless
  • Has a config file with hot-reload
  • Python3, PyQt6
  • Some argparse tinkering

Usage

By default, the icon is disabled, to enable it pass --icon-enable

You can pass file contents as command line arguments using @path/to/the/file syntax. Arguments in that case can be placed wherever - on one line, on several lines

If you want to dynamically pass runtime arguments (without restarting the process), you can use --config options for it

Once you press --buttons-start, you can scroll vertically or horizontally just by moving your mouse untill you press --buttons-end

If --buttons-hold is set, the srolling ends once you release --buttons-start

Once --buttons-start is pressed, the scroll thread starts looping Every loop consists of sleeping for an interval, then scrolling for either 0, 1, or -1 pixels on both axis towards the starting point Starting point is the point where --buttons-start was pressed Sleep interval is recalculated on every mouse move as such:

    100 / (--scrolling-acceleration * max(distance) + --scrolling-speed)

If --scrolling-acceleration is not 0, the speed of scrolling will be faster the farther away you are from the starting point If --scrolling-acceleration is 0, the speed of scrolling will be constant

Examples

Use the package

python3 -m venv venv
. venv/bin/activate
pip install autoscroll
autoscroll

Command line options

autoscroll --buttons-start 1 --debug-click --icon-disable

Pass a configuration file once

autoscroll --icon-enable @config.txt

If config.txt is defined like this, its contents will be used as command line arguments - they will be loaded only once Arguments can be placed wherever - on one line, on several lines For example,

--buttons-start 1
--buttons-hold --debug-click

Listen for changes in the configuration file

autoscroll --config-enable --config-path config.txt

If config.txt is defined like this, the process will listen for changes in that file and update itself Arguments can be placed wherever - on one line, on several lines The file is checked for changess every --config-interval For example:

--buttons-start 1 --buttons-hold
--debug_click

--help output

usage: autoscroll [-h] [-ss SCROLLING_SPEED] [-sd SCROLLING_DEAD_AREA]
                  [-sa SCROLLING_ACCELERATION] [-bh] [-bs BUTTONS_START] [-be BUTTONS_END]
                  [-ce] [-cp CONFIG_PATH] [-ci CONFIG_INTERVAL] [-ie] [-ip ICON_PATH]
                  [-is ICON_SIZE] [-df] [-dc] [-ds] [-di]

...

options:
  -h, --help            show this help message and exit

scrolling:

  -ss, --scrolling-speed int
                        constant part of the scrolling speed
                        [default: 300]
  -sd, --scrolling-dead-area int
                        size of the square area aroung the starting point where scrolling will stop, in
                        pixels
                        [default: 50]
  -sa, --scrolling-acceleration int
                        dynamic part of the scrolling speed, depends on the distance from the point
                        where the scrolling started, can be set to 0
                        [default: 10]

buttons:

  -bh, --buttons-hold   if set, the scrolling will end once you release --buttons-start
  -bs, --buttons-start int
                        button that starts the scrolling
                        [default: 2]
  -be, --buttons-end int
                        button that ends the scrolling
                        [default: --buttons-start]

config:

  -ce, --config-enable  if set, arguments from the configuration file on --config-path will be loaded
                        every --config-interval
  -cp, --config-path str
                        path to the configuration file
                        [default: ~/.config/autoscroll/config.txt]
  -ci, --config-interval int
                        how often the config file should be checked for changes, in seconds
                        [default: 5]

icon:

  -ie, --icon-enable    if set, the icon will be enabled
  -ip, --icon-path str  path to the icon
                        [default: resources/img/icon.svg]
  -is, --icon-size int  size of the icon, in pixels
                        [default: 30]

debug:

  -df, --debug-file     if set, every time the config file is parsed, information will be printed to
                        stdout
  -dc, --debug-click    if set, click info will be printed to stdout
  -ds, --debug-scroll   if set, scroll info will be printed to stdout
  -di, --debug-initial  if set, startup configuration will be printed to stdout

2.1 - Bazel targets

NameInfo
autoscroll
locationpy/autoscroll/BUILD.bazel:23:9
name//py/autoscroll:autoscroll
ruleClasspy_wheel
visibility
  • //visibility:private
autoscroll.dist
locationpy/autoscroll/BUILD.bazel:23:9
name//py/autoscroll:autoscroll.dist
ruleClasspy_wheel_dist
visibility
  • //visibility:private
autoscroll.publish
locationpy/autoscroll/BUILD.bazel:23:9
name//py/autoscroll:autoscroll.publish
ruleClassnative_binary
visibility
  • //visibility:private
changelog
locationpy/autoscroll/BUILD.bazel:14:17
name//py/autoscroll:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //py/autoscroll:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationpy/autoscroll/BUILD.bazel:14:17
name//py/autoscroll:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //py/autoscroll:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationpy/autoscroll/BUILD.bazel:14:17
name//py/autoscroll:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //py/autoscroll:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationpy/autoscroll/BUILD.bazel:14:17
name//py/autoscroll:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //py/autoscroll:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationpy/autoscroll/BUILD.bazel:14:17
name//py/autoscroll:changelog-template
ruleClass_write_file
ruleOutput
  • //py/autoscroll:changelog-template.md
visibility
  • //visibility:private
readme
locationpy/autoscroll/BUILD.bazel:9:10
name//py/autoscroll:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationpy/autoscroll/BUILD.bazel:9:10
name//py/autoscroll:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //py/autoscroll:readme-children.tar
visibility
  • //visibility:public

2.2 - Changelog

2.3 - Src

2.3.1 - Autoscroll

2.3.1.1 - Bazel targets

NameInfo
_internal
locationpy/autoscroll/autoscroll/_internal/BUILD.bazel:11:11
name//py/autoscroll/autoscroll/_internal:_internal
ruleClasspy_library
visibility
  • //:__subpackages__
changelog
locationpy/autoscroll/autoscroll/_internal/BUILD.bazel:6:17
name//py/autoscroll/autoscroll/_internal:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //py/autoscroll/autoscroll/_internal:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationpy/autoscroll/autoscroll/_internal/BUILD.bazel:6:17
name//py/autoscroll/autoscroll/_internal:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //py/autoscroll/autoscroll/_internal:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationpy/autoscroll/autoscroll/_internal/BUILD.bazel:6:17
name//py/autoscroll/autoscroll/_internal:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //py/autoscroll/autoscroll/_internal:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationpy/autoscroll/autoscroll/_internal/BUILD.bazel:6:17
name//py/autoscroll/autoscroll/_internal:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //py/autoscroll/autoscroll/_internal:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationpy/autoscroll/autoscroll/_internal/BUILD.bazel:6:17
name//py/autoscroll/autoscroll/_internal:changelog-template
ruleClass_write_file
ruleOutput
  • //py/autoscroll/autoscroll/_internal:changelog-template.md
visibility
  • //visibility:private
readme
locationpy/autoscroll/autoscroll/_internal/BUILD.bazel:29:10
name//py/autoscroll/autoscroll/_internal:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationpy/autoscroll/autoscroll/_internal/BUILD.bazel:29:10
name//py/autoscroll/autoscroll/_internal:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //py/autoscroll/autoscroll/_internal:readme-children.tar
visibility
  • //visibility:public

2.3.1.2 - Changelog

2.3.2 - Bazel targets

NameInfo
autoscroll
locationpy/autoscroll/autoscroll/BUILD.bazel:17:11
name//py/autoscroll/autoscroll:autoscroll
ruleClasspy_library
visibility
  • //:__subpackages__
autoscroll-data
locationpy/autoscroll/autoscroll/BUILD.bazel:11:10
name//py/autoscroll/autoscroll:autoscroll-data
ruleClassfilegroup
visibility
  • //:__subpackages__
autoscroll_bin
locationpy/autoscroll/autoscroll/BUILD.bazel:27:10
name//py/autoscroll/autoscroll:autoscroll_bin
ruleClasspy_binary
visibility
  • //:__subpackages__
changelog
locationpy/autoscroll/autoscroll/BUILD.bazel:6:17
name//py/autoscroll/autoscroll:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //py/autoscroll/autoscroll:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationpy/autoscroll/autoscroll/BUILD.bazel:6:17
name//py/autoscroll/autoscroll:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //py/autoscroll/autoscroll:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationpy/autoscroll/autoscroll/BUILD.bazel:6:17
name//py/autoscroll/autoscroll:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //py/autoscroll/autoscroll:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationpy/autoscroll/autoscroll/BUILD.bazel:6:17
name//py/autoscroll/autoscroll:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //py/autoscroll/autoscroll:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationpy/autoscroll/autoscroll/BUILD.bazel:6:17
name//py/autoscroll/autoscroll:changelog-template
ruleClass_write_file
ruleOutput
  • //py/autoscroll/autoscroll:changelog-template.md
visibility
  • //visibility:private
readme
locationpy/autoscroll/autoscroll/BUILD.bazel:34:10
name//py/autoscroll/autoscroll:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationpy/autoscroll/autoscroll/BUILD.bazel:34:10
name//py/autoscroll/autoscroll:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //py/autoscroll/autoscroll:readme-children.tar
visibility
  • //visibility:public

2.3.3 - Changelog

3 - Bazel python shell

Python shell allowing you to run shell commands in python environment

3.1 - Bazel targets

NameInfo
binary
locationpy/bazel-python-shell/BUILD.bazel:33:10
name//py/bazel-python-shell:binary
ruleClasspy_binary
visibility
  • //visibility:public
black-fix
locationpy/bazel-python-shell/BUILD.bazel:23:15
name//py/bazel-python-shell:black-fix
ruleClassnative_binary
visibility
  • //visibility:private
black-test
locationpy/bazel-python-shell/BUILD.bazel:23:15
name//py/bazel-python-shell:black-test
ruleClassnative_test
visibility
  • //visibility:private
changelog
locationpy/bazel-python-shell/BUILD.bazel:13:17
name//py/bazel-python-shell:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //py/bazel-python-shell:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationpy/bazel-python-shell/BUILD.bazel:13:17
name//py/bazel-python-shell:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //py/bazel-python-shell:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationpy/bazel-python-shell/BUILD.bazel:13:17
name//py/bazel-python-shell:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //py/bazel-python-shell:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationpy/bazel-python-shell/BUILD.bazel:13:17
name//py/bazel-python-shell:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //py/bazel-python-shell:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationpy/bazel-python-shell/BUILD.bazel:13:17
name//py/bazel-python-shell:changelog-template
ruleClass_write_file
ruleOutput
  • //py/bazel-python-shell:changelog-template.md
visibility
  • //visibility:private
flake8-test
locationpy/bazel-python-shell/BUILD.bazel:23:15
name//py/bazel-python-shell:flake8-test
ruleClassnative_test
visibility
  • //visibility:private
isort-fix
locationpy/bazel-python-shell/BUILD.bazel:23:15
name//py/bazel-python-shell:isort-fix
ruleClassnative_binary
visibility
  • //visibility:private
isort-test
locationpy/bazel-python-shell/BUILD.bazel:23:15
name//py/bazel-python-shell:isort-test
ruleClassnative_test
visibility
  • //visibility:private
library
locationpy/bazel-python-shell/BUILD.bazel:27:11
name//py/bazel-python-shell:library
ruleClasspy_library
visibility
  • //visibility:public
mypy-test
locationpy/bazel-python-shell/BUILD.bazel:23:15
name//py/bazel-python-shell:mypy-test
ruleClassnative_test
visibility
  • //visibility:private
readme
locationpy/bazel-python-shell/BUILD.bazel:8:10
name//py/bazel-python-shell:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationpy/bazel-python-shell/BUILD.bazel:8:10
name//py/bazel-python-shell:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //py/bazel-python-shell:readme-children.tar
visibility
  • //visibility:public
src
locationpy/bazel-python-shell/BUILD.bazel:18:10
name//py/bazel-python-shell:src
ruleClassfilegroup
visibility
  • //visibility:private

3.2 - Changelog

4 - Bazel targets

NameInfo
_black_gen
locationpy/BUILD.bazel:27:29
name//py:_black_gen
ruleClasspy_console_script_gen
ruleOutput
  • //py:rules_python_entry_point_black.py
visibility
  • //visibility:private
_flake8_gen
locationpy/BUILD.bazel:27:29
name//py:_flake8_gen
ruleClasspy_console_script_gen
ruleOutput
  • //py:rules_python_entry_point_flake8.py
visibility
  • //visibility:private
_git-filter-repo_gen
locationpy/BUILD.bazel:27:29
name//py:_git-filter-repo_gen
ruleClasspy_console_script_gen
ruleOutput
  • //py:rules_python_entry_point_git-filter-repo.py
visibility
  • //visibility:private
_isort_gen
locationpy/BUILD.bazel:27:29
name//py:_isort_gen
ruleClasspy_console_script_gen
ruleOutput
  • //py:rules_python_entry_point_isort.py
visibility
  • //visibility:private
_mypy_gen
locationpy/BUILD.bazel:27:29
name//py:_mypy_gen
ruleClasspy_console_script_gen
ruleOutput
  • //py:rules_python_entry_point_mypy.py
visibility
  • //visibility:private
_twine_gen
locationpy/BUILD.bazel:27:29
name//py:_twine_gen
ruleClasspy_console_script_gen
ruleOutput
  • //py:rules_python_entry_point_twine.py
visibility
  • //visibility:private
black
locationpy/BUILD.bazel:27:29
name//py:black
ruleClasspy_binary
visibility
  • //visibility:public
changelog
locationpy/BUILD.bazel:19:17
name//py:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //py:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationpy/BUILD.bazel:19:17
name//py:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //py:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationpy/BUILD.bazel:19:17
name//py:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //py:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationpy/BUILD.bazel:19:17
name//py:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //py:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationpy/BUILD.bazel:19:17
name//py:changelog-template
ruleClass_write_file
ruleOutput
  • //py:changelog-template.md
visibility
  • //visibility:private
flake8
locationpy/BUILD.bazel:27:29
name//py:flake8
ruleClasspy_binary
visibility
  • //visibility:public
gazelle_python_manifest
locationpy/BUILD.bazel:48:24
name//py:gazelle_python_manifest
ruleClassfilegroup
visibility
  • //visibility:public
gazelle_python_manifest.genrule
locationpy/BUILD.bazel:48:24
name//py:gazelle_python_manifest.genrule
ruleClassgenrule
ruleOutput
  • //py:gazelle_python_manifest.generated_manifest
visibility
  • //visibility:private
gazelle_python_manifest.test
locationpy/BUILD.bazel:48:24
name//py:gazelle_python_manifest.test
ruleClassgo_test
visibility
  • //visibility:private
gazelle_python_manifest.update
locationpy/BUILD.bazel:48:24
name//py:gazelle_python_manifest.update
ruleClasspy_binary
visibility
  • //visibility:private
git-filter-repo
locationpy/BUILD.bazel:27:29
name//py:git-filter-repo
ruleClasspy_binary
visibility
  • //visibility:public
isort
locationpy/BUILD.bazel:27:29
name//py:isort
ruleClasspy_binary
visibility
  • //visibility:public
modules_map
locationpy/BUILD.bazel:55:16
name//py:modules_map
ruleClassmodules_mapping
visibility
  • //visibility:private
mypy
locationpy/BUILD.bazel:27:29
name//py:mypy
ruleClasspy_binary
visibility
  • //visibility:public
readme
locationpy/BUILD.bazel:43:10
name//py:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationpy/BUILD.bazel:43:10
name//py:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //py:readme-children.tar
visibility
  • //visibility:public
requirements
locationpy/BUILD.bazel:36:25
name//py:requirements
ruleClassfilegroup
visibility
  • //visibility:private
requirements.update
locationpy/BUILD.bazel:36:25
name//py:requirements.update
ruleClasspy_binary
visibility
  • //visibility:private
requirements_test
locationpy/BUILD.bazel:36:25
name//py:requirements_test
ruleClasspy_test
visibility
  • //visibility:private
twine
locationpy/BUILD.bazel:27:29
name//py:twine
ruleClasspy_binary
visibility
  • //visibility:public

5 - Changelog

6 - Python scripts

6.1 - Bazel targets

NameInfo
black-fix
locationpy/install-file/BUILD.bazel:23:15
name//py/install-file:black-fix
ruleClassnative_binary
visibility
  • //visibility:private
black-test
locationpy/install-file/BUILD.bazel:23:15
name//py/install-file:black-test
ruleClassnative_test
visibility
  • //visibility:private
changelog
locationpy/install-file/BUILD.bazel:13:17
name//py/install-file:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //py/install-file:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationpy/install-file/BUILD.bazel:13:17
name//py/install-file:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //py/install-file:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationpy/install-file/BUILD.bazel:13:17
name//py/install-file:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //py/install-file:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationpy/install-file/BUILD.bazel:13:17
name//py/install-file:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //py/install-file:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationpy/install-file/BUILD.bazel:13:17
name//py/install-file:changelog-template
ruleClass_write_file
ruleOutput
  • //py/install-file:changelog-template.md
visibility
  • //visibility:private
flake8-test
locationpy/install-file/BUILD.bazel:23:15
name//py/install-file:flake8-test
ruleClassnative_test
visibility
  • //visibility:private
isort-fix
locationpy/install-file/BUILD.bazel:23:15
name//py/install-file:isort-fix
ruleClassnative_binary
visibility
  • //visibility:private
isort-test
locationpy/install-file/BUILD.bazel:23:15
name//py/install-file:isort-test
ruleClassnative_test
visibility
  • //visibility:private
lib
locationpy/install-file/BUILD.bazel:27:11
name//py/install-file:lib
ruleClasspy_library
visibility
  • //visibility:public
mypy-test
locationpy/install-file/BUILD.bazel:23:15
name//py/install-file:mypy-test
ruleClassnative_test
visibility
  • //visibility:private
readme
locationpy/install-file/BUILD.bazel:8:10
name//py/install-file:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationpy/install-file/BUILD.bazel:8:10
name//py/install-file:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //py/install-file:readme-children.tar
visibility
  • //visibility:public
src
locationpy/install-file/BUILD.bazel:18:10
name//py/install-file:src
ruleClassfilegroup
visibility
  • //visibility:private

6.2 - Changelog

7 - Replace section

Replace sections of files

7.1 - Bazel targets

NameInfo
black-fix
locationpy/replace-section/BUILD.bazel:23:15
name//py/replace-section:black-fix
ruleClassnative_binary
visibility
  • //visibility:private
black-test
locationpy/replace-section/BUILD.bazel:23:15
name//py/replace-section:black-test
ruleClassnative_test
visibility
  • //visibility:private
changelog
locationpy/replace-section/BUILD.bazel:13:17
name//py/replace-section:changelog
ruleClasspkg_tar_impl
ruleOutput
  • //py/replace-section:changelog.tar
visibility
  • //visibility:public
changelog-changelog
locationpy/replace-section/BUILD.bazel:13:17
name//py/replace-section:changelog-changelog
ruleClassal_template_files
ruleOutput
  • //py/replace-section:changelog.md
visibility
  • //visibility:public
changelog-changelog-data
locationpy/replace-section/BUILD.bazel:13:17
name//py/replace-section:changelog-changelog-data
ruleClassgenrule
ruleOutput
  • //py/replace-section:changelog-changelog-data.yaml
visibility
  • //visibility:private
changelog-children
locationpy/replace-section/BUILD.bazel:13:17
name//py/replace-section:changelog-children
ruleClasspkg_tar_impl
ruleOutput
  • //py/replace-section:changelog-children.tar
visibility
  • //visibility:private
changelog-template
locationpy/replace-section/BUILD.bazel:13:17
name//py/replace-section:changelog-template
ruleClass_write_file
ruleOutput
  • //py/replace-section:changelog-template.md
visibility
  • //visibility:private
flake8-test
locationpy/replace-section/BUILD.bazel:23:15
name//py/replace-section:flake8-test
ruleClassnative_test
visibility
  • //visibility:private
isort-fix
locationpy/replace-section/BUILD.bazel:23:15
name//py/replace-section:isort-fix
ruleClassnative_binary
visibility
  • //visibility:private
isort-test
locationpy/replace-section/BUILD.bazel:23:15
name//py/replace-section:isort-test
ruleClassnative_test
visibility
  • //visibility:private
mypy-test
locationpy/replace-section/BUILD.bazel:23:15
name//py/replace-section:mypy-test
ruleClassnative_test
visibility
  • //visibility:private
readme
locationpy/replace-section/BUILD.bazel:8:10
name//py/replace-section:readme
ruleClassfilegroup
visibility
  • //visibility:public
readme-children
locationpy/replace-section/BUILD.bazel:8:10
name//py/replace-section:readme-children
ruleClasspkg_tar_impl
ruleOutput
  • //py/replace-section:readme-children.tar
visibility
  • //visibility:public
src
locationpy/replace-section/BUILD.bazel:18:10
name//py/replace-section:src
ruleClassfilegroup
visibility
  • //visibility:private

7.2 - Changelog