**Leetle** *Since January 1st, 2025*  > "Leetle is a daily coding game, in the spirit of LeetCode & Wordle. > The challenges are meant to be quick and easy, but help reinforce Python > syntax and methods. The challenges are created by a mix of LLMs, mostly > Claude 3.5 Sonnet, and hand-tested. --[Ron Kiehn][]" [Ron Kiehn]: https://ronkiehn.dev/ # [FizzBuzz](https://leetle.app/?date=2025-01-01) Write a function `solve` that takes a number `n` and returns a list of numbers from 1 to `n`. If the number is divisible by 3, replace it with 'Fizz'. If the number is divisible by 5, replace it with 'Buzz'. If the number is divisible by both 3 and 5, replace it with 'FizzBuzz'. ## Solution ``` Python def solve(n): return [i % 3 // 2 * "Fizz" + i % 5 // 4 * "Buzz" or i + 1 for i in range(n)] ``` ## Test Cases ``` Python assert (got := solve(15)) == [ 1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz", ], f"{got=}" assert (got := solve(5)) == [1, 2, "Fizz", 4, "Buzz"], f"{got=}" assert (got := solve(1)) == [1], f"{got=}" assert (got := solve(3)) == [1, 2, "Fizz"], f"{got=}" assert (got := solve(10)) == [ 1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", ], f"{got=}" assert (got := solve(20)) == [ 1, 2, "Fizz", 4, "Buzz", "Fizz", 7, 8, "Fizz", "Buzz", 11, "Fizz", 13, 14, "FizzBuzz", 16, 17, "Fizz", 19, "Buzz", ], f"{got=}" ``` # [Single Number](https://leetle.app/?date=2025-01-02) Write a function `solve` that finds the number that appears only once in a list where all other numbers appear twice. ## Solution ``` Python def solve(nums): return sum(set(nums)) * 2 - sum(nums) ``` ## Test Cases ``` Python assert (got := solve([4, 1, 2, 1, 2])) == 4, f"{got=}" assert (got := solve([1])) == 1, f"{got=}" assert (got := solve([2, 2, 1])) == 1, f"{got=}" assert (got := solve([1, 0, 1])) == 0, f"{got=}" assert (got := solve([1, 1, 2, 2, 4])) == 4, f"{got=}" assert (got := solve([7, 3, 7])) == 3, f"{got=}" ``` # [Majority Element](https://leetle.app/?date=2025-01-03) Write a function `solve` that finds the majority element in a list. The majority element appears more than n/2 times where n is the length of the list. ## Solution ``` Python def solve(nums): return next(i for i in set(nums) if nums.count(i) > len(nums) // 2) ``` ## Test Cases ``` Python assert (got := solve([3, 2, 3])) == 3, f"{got=}" assert (got := solve([2, 2, 1, 1, 1, 2, 2])) == 2, f"{got=}" assert (got := solve([1])) == 1, f"{got=}" assert (got := solve([1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 4, 5, 5, 5, 5, 5])) == 2, ( f"{got=}" ) assert (got := solve([1, 1, 1, 2, 2, 2, 2, 2, 2])) == 2, f"{got=}" assert (got := solve([1, 1, 1, 1, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1, 1])) == 1, f"{got=}" ``` # [Missing Number](https://leetle.app/?date=2025-01-04) Write a function `solve` that finds the missing number in a list of numbers from 0 to n. The list is missing one number. ## Solution ``` Python def solve(nums): return len(nums) * (len(nums) + 1) // 2 - sum(nums) ``` ## Test Cases ``` Python assert (got := solve([3, 0, 1])) == 2, f"{got=}" assert (got := solve([0, 1])) == 2, f"{got=}" assert (got := solve([9, 6, 4, 2, 3, 5, 7, 0, 1])) == 8, f"{got=}" assert (got := solve([0])) == 1, f"{got=}" assert (got := solve([0, 1, 2, 3, 4, 5, 6, 7, 8])) == 9 assert (got := solve([1])) == 0, f"{got=}" ``` # [Valid Anagram](https://leetle.app/?date=2025-01-05) Write a function `solve` that determines if two strings are anagrams of each other. An anagram is a word formed by rearranging the letters of another word. ## Solution ``` Python def solve(s1, s2): return sorted(s1) == sorted(s2) ``` ## Test Cases ``` Python assert (got := solve("listen", "silent")) is True, f"{got=}" assert (got := solve("hello", "world")) is False, f"{got=}" assert (got := solve("rat", "tar")) is True, f"{got=}" assert (got := solve("", "")) is True, f"{got=}" assert (got := solve("anagram", "nagaram")) is True, f"{got=}" assert (got := solve("aaabbb", "ab")) is False, f"{got=}" ``` # [Maximum Subarray](https://leetle.app/?date=2025-01-06) Write a function `solve` that finds the nonempty contiguous subarray with the largest sum in a list. ## Solution ``` Python def solve(nums): n = len(nums) return max(sum(nums[i:j]) for i in range(n) for j in range(i + 1, n + 1)) ``` ## Test Cases ``` Python assert (got := solve([-2, 1, -3, 4, -1, 2, 1, -5, 4])) == 6, f"{got=}" assert (got := solve([1])) == 1, f"{got=}" assert (got := solve([5, 4, -1, 7, 8])) == 23, f"{got=}" assert (got := solve([-1])) == -1, f"{got=}" assert (got := solve([-2, 1])) == 1, f"{got=}" assert (got := solve([-2, -1])) == -1, f"{got=}" ``` # [Valid Parentheses](https://leetle.app/?date=2025-01-07) Write a function `solve` that determines if a string `s` of parentheses is valid. Valid parentheses must be closed in the correct order. ## Solution ``` Python def solve(s): stack, expect = [], dict(zip("([{", ")]}")) for c in s: if c in expect.keys(): stack.append(expect[c]) elif not stack or c != stack.pop(): return False return not stack ``` ## Test Cases ``` Python assert (got := solve("()[]{}")) is True, f"{got=}" assert (got := solve("(]")) is False, f"{got=}" assert (got := solve("")) is True, f"{got=}" assert (got := solve("([)]")) is False, f"{got=}" assert (got := solve("{[]}")) is True, f"{got=}" assert (got := solve("((")) is False, f"{got=}" assert (got := solve(")")) is False, f"{got=}" ``` # [Two Sum](https://leetle.app/?date=2025-01-08) Write a function `solve` that finds two numbers in a list that add up to a target value. Return a list with their indices in order. If the target cannot be made, return an empty list. ## Solution ``` Python from itertools import combinations as c def solve(nums, target): result = [[p, i] for (p, a), (i, r) in c(enumerate(nums), 2) if a + r == target] return result[0] if result else result ``` ## Test Cases ``` Python assert (got := solve([2, 7, 11, 15], 9)) == [0, 1], f"{got=}" assert (got := solve([3, 2, 4], 6)) == [1, 2], f"{got=}" assert (got := solve([3, 3], 6)) == [0, 1], f"{got=}" assert (got := solve([1, 2, 3, 4], 7)) == [2, 3], f"{got=}" assert (got := solve([1, 5, 8, 3], 11)) == [2, 3], f"{got=}" assert (got := solve([1, 2, 3, 4], 8)) == [], f"{got=}" ``` # [Sliding Window Maximum](https://leetle.app/?date=2025-01-09) Write a function `solve` that returns the maximum number in each window of size `k` sliding from left to right in a list. Your function should return a list of ints. ## Solution ``` Python def solve(nums, k): return [max(nums[i : i + k]) for i in range(len(nums) - k + 1)] ``` ## Test Cases ``` Python assert (got := solve([1, 3, -1, -3, 5, 3, 6, 7], 3)) == [ 3, 3, 5, 5, 6, 7, ], f"{got=}" assert (got := solve([1, 2, 3, 4], 2)) == [2, 3, 4], f"{got=}" assert (got := solve([1], 1)) == [1], f"{got=}" assert (got := solve([1, 2, 3], 3)) == [3], f"{got=}" assert (got := solve([1, -1], 1)) == [1, -1], f"{got=}" assert (got := solve([4, 2, 3, 1, 5, 6], 4)) == [4, 5, 6], f"{got=}" ``` # [First Missing Positive](https://leetle.app/?date=2025-01-10) Write a function `solve` that finds the first missing positive integer given an unsorted list. That is, the smallest positive integer not in the list. ## Solution ``` Python def solve(nums): return min(set(range(1, max(nums) + 2)) - set(nums)) ``` ## Test Cases ``` Python assert (got := solve([3, 4, -1, 1])) == 2, f"{got=}" assert (got := solve([1, 2, 0])) == 3, f"{got=}" assert (got := solve([7, 8, 9, 11, 12])) == 1, f"{got=}" assert (got := solve([1])) == 2, f"{got=}" assert (got := solve([-5, -3, -2, 1])) == 2, f"{got=}" assert (got := solve([1, 1, 2, 2])) == 3, f"{got=}" ``` # [Palindrome Check](https://leetle.app/?date=2025-01-11) Write a function `solve` that checks if a string is a palindrome, considering only alphanumeric characters and ignoring case. ## Solution ``` Python def solve(s): return (r := "".join(i for i in s.lower() if i.isalnum())) == r[::-1] ``` ## Test Cases ``` Python assert (got := solve("A man, a plan, a canal: Panama")) is True, f"{got=}" assert (got := solve("race a car")) is False, f"{got=}" assert (got := solve("")) is True, f"{got=}" assert (got := solve("0p")) is False, f"{got=}" assert (got := solve("Was it a car or a cat I saw?")) is True, f"{got=}" assert (got := solve("12321")) is True, f"{got=}" ``` # [Count Islands (Square)](https://leetle.app/?date=2025-01-12) Write a function `solve` that counts the number of islands in a 2D grid. An island is surrounded by water (0s) and is formed by connecting adjacent lands (1s) horizontally or vertically. ## Solution ``` Python def solve(grid): def bound(x, y): return 0 <= x < len(grid) and 0 <= y < len(grid[0]) def dfs(x, y): seen.append((x, y)) for i, j in [(x + i, y + j) for i, j in dir if bound(x + i, y + j)]: if grid[i][j] and (i, j) not in seen: dfs(i, j) number, seen, dir = 0, [], [(-1, 0), (0, 1), (1, 0), (0, -1)] for x in range(len(grid)): for y in range(len(grid[0])): if grid[x][y] and (x, y) not in seen: number += 1 dfs(x, y) return number ``` ## Test Cases ``` Python assert (got := solve([[1, 1, 0], [0, 1, 0], [1, 0, 1]])) == 3, f"{got=}" assert (got := solve([[1, 1, 1], [1, 1, 1], [1, 1, 1]])) == 1, f"{got=}" assert (got := solve([[0, 0, 0], [0, 0, 0], [0, 0, 0]])) == 0, f"{got=}" assert (got := solve([[1, 0, 1], [0, 1, 0], [1, 0, 1]])) == 5, f"{got=}" assert (got := solve([[1]])) == 1, f"{got=}" assert (got := solve([[1, 1], [1, 1]])) == 1, f"{got=}" ``` # [Running Sum](https://leetle.app/?date=2025-01-13) Write a function `solve` that returns the running sum of a list. The running sum is the sum of all elements up to each index. ## Solution ``` Python def solve(nums): return [sum(nums[: i + 1]) for i, _ in enumerate(nums)] ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 4])) == [1, 3, 6, 10], f"{got=}" assert (got := solve([1, 1, 1, 1, 1])) == [1, 2, 3, 4, 5], f"{got=}" assert (got := solve([3, 1, 2, 10, 1])) == [3, 4, 6, 16, 17], f"{got=}" assert (got := solve([1])) == [1], f"{got=}" assert (got := solve([-1, -2, -3])) == [-1, -3, -6], f"{got=}" assert (got := solve([0, 0, 0])) == [0, 0, 0], f"{got=}" ``` # [Reverse Words](https://leetle.app/?date=2025-01-14) Write a function `solve` that reverses the words in a string. Words are separated by spaces. ## Solution ``` Python def solve(s): return " ".join(reversed(s.split())) ``` ## Test Cases ``` Python assert (got := solve("the sky is blue")) == "blue is sky the", f"{got=}" assert (got := solve("hello world")) == "world hello", f"{got=}" assert (got := solve("a good example")) == "example good a", f"{got=}" assert (got := solve("")) == "", f"{got=}" assert (got := solve("one")) == "one", f"{got=}" assert ( got := solve("a b c d e f g h i j k l m n o p q r s t u v w x y z") ) == "z y x w v u t s r q p o n m l k j i h g f e d c b a", f"{got=}" ``` # [Matrix Rotation](https://leetle.app/?date=2025-01-15) Write a function `solve` that rotates an `n` x `n` matrix 90 degrees clockwise in place. ## Solution ``` Python def solve(matrix): return [list(i)[::-1] for i in zip(*matrix)] ``` ## Test Cases ``` Python assert (got := solve([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) == [ [7, 4, 1], [8, 5, 2], [9, 6, 3], ], f"{got=}" assert (got := solve([[1]])) == [[1]], f"{got=}" assert (got := solve([[1, 2], [3, 4]])) == [[3, 1], [4, 2]], f"{got=}" assert ( got := solve([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) ) == [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]], f"{got=}" assert (got := solve([[0, 0], [0, 1]])) == [[0, 0], [1, 0]], f"{got=}" assert (got := solve([[1, 1, 1], [2, 2, 2], [3, 3, 3]])) == [ [3, 2, 1], [3, 2, 1], [3, 2, 1], ], f"{got=}" ``` # [Longest Consecutive Sequence](https://leetle.app/?date=2025-01-16) Write a function `solve` that finds the length of the longest consecutive sequence in an unsorted list. ## Solution ``` Python def solve(nums): res, nums = 0, set(nums) for num in nums: if num - 1 not in nums: cur, seq = num, 1 while cur + 1 in nums: cur, seq = cur + 1, seq + 1 res = max(res, seq) return res ``` ## Test Cases ``` Python assert (got := solve([100, 4, 200, 1, 3, 2])) == 4, f"{got=}" assert (got := solve([0, 3, 7, 2, 5, 8, 4, 6, 1])) == 9, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([1])) == 1, f"{got=}" assert (got := solve([1, 2, 0, 1])) == 3, f"{got=}" assert (got := solve([1, 1, 1, 1])) == 1, f"{got=}" ``` # [Count Vowels](https://leetle.app/?date=2025-01-17) Write a function `solve` that counts the number of vowels (a,e,i,o,u) in a string, ignoring case. ## Solution ``` Python def solve(text): return sum(text.lower().count(v) for v in "aeiou") ``` ## Test Cases ``` Python assert (got := solve("Hello World")) == 3, f"{got=}" assert (got := solve("AEIOU")) == 5, f"{got=}" assert (got := solve("xyz")) == 0, f"{got=}" assert (got := solve("")) == 0, f"{got=}" assert (got := solve("aEiOu")) == 5, f"{got=}" assert (got := solve("Python Programming")) == 4, f"{got=}" ``` # [Pascal's Triangle](https://leetle.app/?date=2025-01-18) Write a function `solve` that generates the first n rows of [Pascal's Triangle](https://en.wikipedia.org/wiki/Pascal%27s_triangle). ## Solution ``` Python def solve(n): if n == 0: return [] res = [[1]] for i in range(1, n): p, x = res[-1], [1] for j in range(1, i): x.append(p[j - 1] + p[j]) x.append(1) res.append(x) return res ``` ## Test Cases ``` Python assert (got := solve(3)) == [[1], [1, 1], [1, 2, 1]], f"{got=}" assert (got := solve(1)) == [[1]], f"{got=}" assert (got := solve(4)) == [[1], [1, 1], [1, 2, 1], [1, 3, 3, 1]], f"{got=}" assert (got := solve(5)) == [ [1], [1, 1], [1, 2, 1], [1, 3, 3, 1], [1, 4, 6, 4, 1], ], f"{got=}" assert (got := solve(2)) == [[1], [1, 1]], f"{got=}" assert (got := solve(0)) == [], f"{got=}" ``` # [Binary Tree Maximum Depth](https://leetle.app/?date=2025-01-19) Write a function that finds the maximum depth of a binary tree. A binary tree's maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node. The tree is represented as an array of nodes in [level-order traversal][1]. None indicates empty nodes. [1]: https://en.wikipedia.org/wiki/Tree_traversal#Breadth-first_search ## Solution ``` Python def solve(root): return max(solve(root.left), solve(root.right)) + 1 if root else 0 ``` ## Test Cases ``` Python # Binary Tree Definition class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return None elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return None node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([3, 9, 20, None, None, 15, 7]))) == 3, f"{got=}" assert (got := solve(None)) == 0, f"{got=}" assert (got := solve(bt([1]))) == 1, f"{got=}" assert (got := solve(bt([1, 2]))) == 2, f"{got=}" assert (got := solve(bt([1, None, 2]))) == 2, f"{got=}" assert (got := solve(bt([1, 2, 3, 4, 5]))) == 3, f"{got=}" ``` # [Reverse Linked List](https://leetle.app/?date=2025-01-20) Write a function that, given the head of a singly linked list, reverses the list. Return the root node of the reversed list. ## Solution ``` Python def solve(head): p = None while head: head.next, p, head = p, head, head.next return p ``` ## Test Cases ``` Python # Singly Linked List Definition class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def sl(ls): if not ls: return None root = node = ListNode(ls[0]) for i in ls[1:]: node.next = ListNode(i) node = node.next return root def t(x): r = [] while x: r.append(x.val) x = x.next return r assert (got := t(solve(sl([1, 2, 3, 4, 5])))) == [5, 4, 3, 2, 1], f"{got=}" assert (got := t(solve(sl([])))) == [], f"{got=}" assert (got := t(solve(sl([1])))) == [1], f"{got=}" assert (got := t(solve(sl([2, 2, 2])))) == [2, 2, 2], f"{got=}" assert (got := t(solve(sl([1, 2, 3, 4])))) == [4, 3, 2, 1], f"{got=}" assert (got := t(solve(sl([2, 5, 2, 1, 3])))) == [3, 1, 2, 5, 2], f"{got=}" ``` # [Factorial](https://leetle.app/?date=2025-01-21) Write a function `solve` that returns the factorial of a given integer n. Return 1 if n is 0. ## Solution ``` Python from math import factorial as solve ``` ## Test Cases ``` Python assert (got := solve(0)) == 1, f"{got=}" assert (got := solve(1)) == 1, f"{got=}" assert (got := solve(5)) == 120, f"{got=}" assert (got := solve(7)) == 5_040, f"{got=}" assert (got := solve(10)) == 3_628_800, f"{got=}" assert (got := solve(12)) == 479_001_600, f"{got=}" ``` # [Merge Sorted Lists](https://leetle.app/?date=2025-01-22) Write a function `solve` that merges two sorted lists into one sorted list. ## Solution ``` Python def solve(list1, list2): result, i1, i2 = [], 0, 0 while i1 < len(list1) and i2 < len(list2): b = 1 - (list1[i1] < list2[i2]) result.append((list1, list2)[b][(i1, i2)[b]]) i1, i2 = i1 + 1 - b, i2 + b return result + list1[i1:] + list2[i2:] ``` ## Test Cases ``` Python assert (got := solve([1, 3, 5], [2, 4, 6])) == [1, 2, 3, 4, 5, 6], f"{got=}" assert (got := solve([], [])) == [], f"{got=}" assert (got := solve([1], [2])) == [1, 2], f"{got=}" assert (got := solve([1, 2, 7], [2, 2, 3])) == [1, 2, 2, 2, 3, 7], f"{got=}" assert (got := solve([0, 0, 0], [0, 0, 0])) == [0, 0, 0, 0, 0, 0], f"{got=}" assert (got := solve([1, 2, 3], [4, 5, 6])) == [1, 2, 3, 4, 5, 6], f"{got=}" ``` # [Validate Palindromic Number](https://leetle.app/?date=2025-01-23) Write a function `solve` that checks whether an integer is a palindrome without converting it to a string. ## Solution ``` Python def solve(num): res = [] while num > 0: res.append(num % 10) num //= 10 return num >= 0 and res == res[::-1] ``` ## Test Cases ``` Python assert (got := solve(121)) is True, f"{got=}" assert (got := solve(-121)) is False, f"{got=}" assert (got := solve(10)) is False, f"{got=}" assert (got := solve(0)) is True, f"{got=}" assert (got := solve(12321)) is True, f"{got=}" assert (got := solve(12345)) is False, f"{got=}" ``` # [Minimum Rotated Sorted Array](https://leetle.app/?date=2025-01-24) Write a function `solve` that finds the minimum element in a rotated sorted array. ## Solution ``` Python def solve(nums): if len(nums) < 2: return (nums + [None])[0] for i in range(len(nums)): if nums[i] > nums[i + 1]: return nums[i + 1] ``` ## Test Cases ``` Python assert (got := solve([3, 4, 5, 1, 2])) == 1, f"{got=}" assert (got := solve([4, 5, 6, 7, 0, 1, 2])) == 0, f"{got=}" assert (got := solve([1])) == 1, f"{got=}" assert (got := solve([2, 1])) == 1, f"{got=}" assert (got := solve([5, 6, 7, 8, 9, 1, 2, 3, 4])) == 1, f"{got=}" assert (got := solve([10, 1, 10, 10, 10])) == 1, f"{got=}" ``` # [Climbing Stairs](https://leetle.app/?date=2025-01-25) Write a function `solve` that calculates how many distinct ways you can climb a staircase of n steps, taking 1 or 2 steps at a time. ## Solution ``` Python def solve(n): return n if n <= 3 else solve(n - 1) + solve(n - 2) ``` ## Test Cases ``` Python assert (got := solve(1)) == 1, f"{got=}" assert (got := solve(2)) == 2, f"{got=}" assert (got := solve(3)) == 3, f"{got=}" assert (got := solve(5)) == 8, f"{got=}" assert (got := solve(10)) == 89, f"{got=}" assert (got := solve(20)) == 10_946, f"{got=}" ``` # [Merge Intervals](https://leetle.app/?date=2025-01-26) Write a function `solve` that merges overlapping intervals and returns the merged list. Intervals are represented as lists of two integers: start and end. ## Solution ``` Python def solve(intervals): output = [] for x, y in intervals: for i, (w, z) in enumerate(output): r = range(w, z + 1) if x in r or y in r: output[i] = [min(x, w), max(y, z)] break else: output.append([x, y]) return output ``` ## Test Cases ``` Python assert (got := solve([[1, 3], [2, 6], [8, 10], [15, 18]])) == [ [1, 6], [8, 10], [15, 18], ], f"{got=}" assert (got := solve([[1, 4], [4, 5]])) == [[1, 5]], f"{got=}" assert (got := solve([[1, 3]])) == [[1, 3]], f"{got=}" assert (got := solve([])) == [], f"{got=}" assert (got := solve([[1, 2], [2, 3], [3, 4]])) == [[1, 4]], f"{got=}" assert (got := solve([[1, 4], [2, 3]])) == [[1, 4]], f"{got=}" ``` # [Power Of Two](https://leetle.app/?date=2025-01-27) Write a function `solve` that checks if an integer is a power of two. ## Solution ``` Python def solve(n): return n.bit_count() == 1 ``` ## Test Cases ``` Python assert (got := solve(1)) is True, f"{got=}" assert (got := solve(16)) is True, f"{got=}" assert (got := solve(3)) is False, f"{got=}" assert (got := solve(0)) is False, f"{got=}" assert (got := solve(32)) is True, f"{got=}" assert (got := solve(64)) is True, f"{got=}" ``` # [Reverse Integer](https://leetle.app/?date=2025-01-28) Write a function solve that reverses the digits of an integer. If the reversed integer overflows, return 0. Assume the input is a 32-bit signed integer, so the reversed integer must be within the range [-2^31, 2^31-1]. ## Solution ``` Python def solve(n): an, out = abs(n), 0 while an: out, an = out * 10 + an % 10, an // 10 return 0 if out.bit_length() > 31 else out if n > 0 else -out ``` ## Test Cases ``` Python assert (got := solve(123)) == 321, f"{got=}" assert (got := solve(-123)) == -321, f"{got=}" assert (got := solve(120)) == 21, f"{got=}" assert (got := solve(0)) == 0, f"{got=}" assert (got := solve(1534236469)) == 0, f"{got=}" assert (got := solve(-2147483648)) == 0, f"{got=}" ``` # [Queue Reconstruction by Height](https://leetle.app/?date=2025-01-29) Write a function `solve` that reconstructs a queue based on the heights of people and the number of people in front of them. Each person is represented by a pair [height, k], where height is the person's height and k is greater than or equal to the number of people in front of this person (BEFORE them in the list) who have a height greater than or equal to height. ## Solution ``` Python def solve(people): out = [] for p in sorted(people, key=lambda x: (-x[0], x[1])): out.insert(p[1], p) return out ``` ## Test Cases ``` Python assert (got := solve([[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]])) == [ [5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1], ], f"{got=}" assert (got := solve([[1, 0], [2, 0], [3, 0]])) == [ [1, 0], [2, 0], [3, 0], ], f"{got=}" assert (got := solve([[1, 1], [2, 0], [3, 0]])) == [ [2, 0], [1, 1], [3, 0], ], f"{got=}" assert (got := solve([[1, 1], [2, 0], [3, 1]])) == [ [2, 0], [1, 1], [3, 1], ], f"{got=}" assert (got := solve([[1, 1], [2, 1], [3, 1]])) == [ [3, 1], [1, 1], [2, 1], ], f"{got=}" assert (got := solve([[1, 0], [2, 1], [3, 2]])) == [ [1, 0], [3, 2], [2, 1], ], f"{got=}" ``` # [Remove Duplicates from Sorted Array](https://leetle.app/?date=2025-01-30) Write a function `solve` that removes duplicates from a sorted array in-place, and return the new length. ## Solution ``` Python def solve(nums): return len(set(nums)) ``` ## Test Cases ``` Python assert (got := solve([1, 1, 2])) == 2, f"{got=}" assert (got := solve([0, 0, 1, 1, 1, 2, 2, 3, 3, 4])) == 5, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([1, 1, 1, 1, 1])) == 1, f"{got=}" assert (got := solve([1, 2, 3, 4, 5])) == 5, f"{got=}" assert (got := solve([1, 1, 2, 2, 3, 3])) == 3, f"{got=}" ``` # [Length of Last Word](https://leetle.app/?date=2025-01-31) Write a function `solve` that returns the length of the last word in a string. ## Solution ``` Python def solve(s): return len(x.rsplit(None, 1)[-1]) if (x := s.rstrip()) else 0 ``` ## Test Cases ``` Python assert (got := solve("Hello World")) == 5, f"{got=}" assert (got := solve("fly me to the moon ")) == 4, f"{got=}" assert (got := solve("luffy is still joyboy")) == 6, f"{got=}" assert (got := solve("")) == 0, f"{got=}" assert (got := solve("one two three")) == 5, f"{got=}" assert (got := solve("a b c d e f g h i j k l m n o p q r s t u v w x y z")) == 1, ( f"{got=}" ) assert (got := solve(" ")) == 0, f"{got=}" ``` # [Find First and Last Position of Element in Sorted Array](https://leetle.app/?date=2025-02-01) Write a function `solve` that finds the starting and ending position of a target value in a sorted array. If the target is not found, return [-1,-1]. Ideally, your solution should run in O(logn) time. ## Solution ``` Python def solve(nums, target): results = [] for i, op in enumerate([int.__lt__, int.__le__]): span = 0, len(nums) - 1 while span[0] <= span[1]: mid = (span[0] + span[1]) // 2 span = (mid + 1, span[1]) if op(nums[mid], target) else (span[0], mid - 1) results.append(span[i]) return results if results[0] <= results[1] else [-1, -1] ``` ## Test Cases ``` Python assert (got := solve([5, 7, 7, 8, 8, 10], 8)) == [3, 4], f"{got=}" assert (got := solve([5, 7, 7, 8, 8, 10], 6)) == [-1, -1], f"{got=}" assert (got := solve([], 0)) == [-1, -1], f"{got=}" assert (got := solve([1], 1)) == [0, 0], f"{got=}" assert (got := solve([1, 2, 3, 4, 5], 3)) == [2, 2], f"{got=}" assert (got := solve([1, 2, 3, 4, 5], 6)) == [-1, -1], f"{got=}" ``` # [Number of Steps to Reduce to Zero](https://leetle.app/?date=2025-02-02) Write a function `solve` that returns the number of steps to reduce a non-negative integer to zero. If it's even, divide by 2; if it's odd, subtract 1. ## Solution ``` Python def solve(num): return max([0, num.bit_length() + num.bit_count() - 1]) ``` ## Test Cases ``` Python assert (got := solve(14)) == 6, f"{got=}" assert (got := solve(8)) == 4, f"{got=}" assert (got := solve(123)) == 12, f"{got=}" assert (got := solve(0)) == 0, f"{got=}" assert (got := solve(1)) == 1, f"{got=}" assert (got := solve(2)) == 2, f"{got=}" ``` # [Binary Tree Inorder Traversal](https://leetle.app/?date=2025-02-03) Write a function `solve` that returns the inorder traversal of a binary tree's nodes' values. ## Solution ``` Python def solve(root): if root is None: return [] return solve(root.left) + [root.val] + solve(root.right) ``` ## Test Cases ``` Python # Binary Tree Definition class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return None elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return None node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([1, None, 2, 3]))) == [1, 3, 2], f"{got=}" assert (got := solve(None)) == [], f"{got=}" assert (got := solve(bt([1]))) == [1], f"{got=}" assert (got := solve(bt([1, 2]))) == [2, 1], f"{got=}" assert (got := solve(bt([1, None, 2]))) == [1, 2], f"{got=}" assert (got := solve(bt([1, 2, 3, 4, 5, 6, 7]))) == [ 4, 2, 5, 1, 6, 3, 7, ], f"{got=}" ``` # [Counting Bits](https://leetle.app/?date=2025-02-04) Write a function `solve` that returns an array of the number of 1-bits (Hamming weight) for each number from 0 to n. ## Solution ``` Python def solve(n): return [i.bit_count() for i in range(n + 1)] ``` ## Test Cases ``` Python assert (got := solve(2)) == [0, 1, 1], f"{got=}" assert (got := solve(5)) == [0, 1, 1, 2, 1, 2], f"{got=}" assert (got := solve(10)) == [0, 1, 1, 2, 1, 2, 2, 3, 1, 2, 2], f"{got=}" assert (got := solve(0)) == [0], f"{got=}" assert (got := solve(1)) == [0, 1], f"{got=}" assert (got := solve(3)) == [0, 1, 1, 2], f"{got=}" ``` # [Single Linked List Middle](https://leetle.app/?date=2025-02-05) Write a function `solve` that returns the middle node of a singly linked list. If two middles, return the second one. ## Solution ``` Python def solve(head): tortoise = hare = head while hare and hare.next: tortoise = tortoise.next hare = hare.next.next return tortoise ``` ## Test Cases ``` Python # Singly Linked List Definition class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def sl(ls): if not ls: return None root = node = ListNode(ls[0]) for i in ls[1:]: node.next = ListNode(i) node = node.next return root assert (got := solve(sl([1, 2, 3, 4, 5])).val) == 3, f"{got=}" assert (got := solve(sl([1, 2, 3, 4, 5, 6])).val) == 4, f"{got=}" assert (got := solve(sl([1, 2, 3])).val) == 2, f"{got=}" assert (got := solve(sl([1, 2])).val) == 2, f"{got=}" assert (got := solve(sl([1])).val) == 1, f"{got=}" assert (got := solve(sl([1, 2, 3, 4, 5, 6, 7])).val) == 4, f"{got=}" ``` # [Count Prime Numbers](https://leetle.app/?date=2025-02-06) Write a function `solve` that counts the number of prime numbers less than n. ## Solution ``` Python def solve(n): multiples, primes = {0, 1}, set() for i in range(2, n): if i not in multiples: primes.add(i) for j in range(i * i, n + 1, i): multiples.add(j) return len(primes) ``` ## Test Cases ``` Python assert (got := solve(10)) == 4, f"{got=}" assert (got := solve(0)) == 0, f"{got=}" assert (got := solve(1)) == 0, f"{got=}" assert (got := solve(2)) == 0, f"{got=}" assert (got := solve(30)) == 10, f"{got=}" assert (got := solve(50)) == 15, f"{got=}" ``` # [Balanced Binary Tree](https://leetle.app/?date=2025-02-07) Write a function `solve` that checks if a binary tree is height-balanced. A height-balanced binary tree is defined as a binary tree in which the left and right subtrees of every node differ in height by no more than 1. ## Solution ``` Python def solve(root): def height(node): if not node: return 0 return max(height(node.left), height(node.right)) + 1 if not root: return True if abs(height(root.left) - height(root.right)) > 1: return False return solve(root.left) and solve(root.right) ``` ## Test Cases ``` Python # Binary Tree Definition class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return None elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return None node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([3, 9, 20, None, None, 15, 7]))) is True, f"{got=}" assert (got := solve(bt([]))) is True, f"{got=}" assert (got := solve(bt([1, 2, 2, 3, 3, None, None, 4, 4]))) is False, f"{got=}" assert (got := solve(bt([1, 2, 2, 3, None, None, 3, 4, None, None, 4]))) is False, ( f"{got=}" ) assert ( got := solve(bt([1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, None, None, 5, 5])) ) is True, f"{got=}" assert (got := solve(bt([1, 2, 2, 3, 3, None, None, 4, 4]))) is False, f"{got=}" ``` # [Armstrong Number](https://leetle.app/?date=2025-02-08) Write a function `solve` that checks if an integer is an Armstrong number (a.k.a Narcissistic number). ## Solution ``` Python def solve(num): return sum(int(i) ** len(str(num)) for i in str(num)) == num ``` ## Test Cases ``` Python assert (got := solve(153)) is True, f"{got=}" assert (got := solve(370)) is True, f"{got=}" assert (got := solve(9474) is True), f"{got=}" assert (got := solve(123)) is False, f"{got=}" assert (got := solve(407)) is True, f"{got=}" assert (got := solve(1634)) is True, f"{got=}" ``` # [Zigzag Conversion](https://leetle.app/?date=2025-02-09) Write a function `solve` that reads a string in a zigzag pattern on a given number of rows, then returns the row-by-row read string. If 'zigzag pattern' is unclear, see the relevant [question](https://leetcode.com/problems/zigzag-conversion/description/). ## Solution ``` Python def solve(s, numRows): if numRows <= 1: return s rows, row, step = [""] * numRows, 0, 1 for c in s: rows[row] += c step = 1 if row == 0 else -1 if row == numRows - 1 else step row += step return "".join(rows) ``` ## Test Cases ``` Python assert (got := solve("PAYPALISHIRING", 3)) == "PAHNAPLSIIGYIR", f"{got=}" assert (got := solve("PAYPALISHIRING", 4)) == "PINALSIGYAHRPI", f"{got=}" assert (got := solve("ABC", 1)) == "ABC", f"{got=}" assert (got := solve("HELLO", 2)) == "HLOEL", f"{got=}" assert (got := solve("ZIGZAG", 3)) == "ZAIZGG", f"{got=}" assert (got := solve("PYTHON", 4)) == "PYNTOH", f"{got=}" ``` # [3Sum Closest](https://leetle.app/?date=2025-02-10) Write a function `solve` that finds the sum of three integers in an array that is closest to a target number. Return the sum of the three integers. You may assume that each input would have exactly one solution. ## Solution ``` Python def solve(nums, target): nums.sort() result = sum(nums[:3]) for i in range(len(nums) - 2): begin, end = i + 1, len(nums) - 1 while begin < end: current = nums[i] + nums[begin] + nums[end] if abs(current - target) <= abs(result - target): result = max(result, current) if current > target: end -= 1 else: begin += 1 return result ``` ## Test Cases ``` Python assert (got := solve([-1, 2, 1, -4], 1)) == 2, f"{got=}" assert (got := solve([0, 0, 0], 1)) == 0, f"{got=}" assert (got := solve([1, 1, 1, 1], 0)) == 3, f"{got=}" assert (got := solve([1, 1, 1, 1], 4)) == 3, f"{got=}" assert (got := solve([1, 1, 1, 1], 2)) == 3, f"{got=}" assert (got := solve([1, 1, 1, 1], 3)) == 3, f"{got=}" assert (got := solve([1, 2, 6, 10], 13)) == 13, f"{got=}" ``` # [Longest Substring Without Repeating Characters](https://leetle.app/?date=2025-02-11) Write a function `solve` that finds the length of the longest substring without repeating characters. ## Solution ``` Python def solve(s): chars, start, length = {}, 0, 0 for i, c in enumerate(s): if c in chars and chars[c] >= start: start = chars[c] + 1 else: length = max(length, i - start + 1) chars[c] = i return length ``` ## Test Cases ``` Python assert (got := solve("abcabcbb")) == 3, f"{got=}" assert (got := solve("bbbbb")) == 1, f"{got=}" assert (got := solve("pwwkew")) == 3, f"{got=}" assert (got := solve("")) == 0, f"{got=}" assert (got := solve("dvdf")) == 3, f"{got=}" assert (got := solve("aab")) == 2, f"{got=}" ``` # [Divide Two Integers](https://leetle.app/?date=2025-02-12) Write a function `solve` that divides two integers without using multiplication, division, and mod operator. Return the quotient as an int after dividing. Assume 32-bit signed integers. ## Solution ``` Python def solve(dividend, divisor): neg = (dividend < 0) ^ (divisor < 0) dividend, divisor = abs(dividend), abs(divisor) if divisor == 0: return None result = 0 while dividend >= divisor: dividend -= divisor result += 1 return -result if neg else result ``` ## Test Cases ``` Python assert (got := solve(10, 3)) == 3, f"{got=}" assert (got := solve(7, -3)) == -2, f"{got=}" assert (got := solve(0, 1)) == 0, f"{got=}" assert (got := solve(1, 1)) == 1, f"{got=}" assert (got := solve(1, 2)) == 0, f"{got=}" assert (got := solve(100, 1)) == 100, f"{got=}" ``` # [Longest Palindromic Substring](https://leetle.app/?date=2025-02-13) Write a function `solve` that finds the longest palindromic substring in a string. ## Solution ``` Python def solve(s): ss, begin, size = len(s), 0, 1 if ss == 0: return "" for i in range(ss): for j in range(2): low, high = i, i + j while low >= 0 and high < ss and s[low] == s[high]: newsize = high - low + 1 if newsize > size: begin, size = low, newsize low, high = low - 1, high + 1 return s[begin : begin + size] ``` ## Test Cases ``` Python assert (got := solve("babd")) == "bab", f"{got=}" assert (got := solve("cbbd")) == "bb", f"{got=}" assert (got := solve("a")) == "a", f"{got=}" assert (got := solve("ac")) == "a", f"{got=}" assert (got := solve("racecar")) == "racecar", f"{got=}" assert (got := solve("aaaaaa")) == "aaaaaa", f"{got=}" ``` # [Regular Expression Matching](https://leetle.app/?date=2025-02-14) Write a function `solve` that implements regular expression matching with support for `.` and `*`. `.` matches any single character, `*` matches zero or more of the preceding element. ## Solution ``` Python def solve(s, p): if not p: return not s match = bool(s) and p[0] in {s[0], "."} if len(p) >= 2 and p[1] == "*": return solve(s, p[2:]) or match and solve(s[1:], p) else: return match and solve(s[1:], p[1:]) ``` ## Test Cases ``` Python assert (got := solve("aa", "a*")) is True, f"{got=}" assert (got := solve("ab", ".*")) is True, f"{got=}" assert (got := solve("mississippi", "mis*is*p*.")) is False, f"{got=}" assert (got := solve("", ".*")) is True, f"{got=}" assert (got := solve("aab", "c*a*b")) is True, f"{got=}" assert (got := solve("ab", ".*c")) is False, f"{got=}" ``` # [Container With Most Water](https://leetle.app/?date=2025-02-15) Write a function `solve` that finds two lines that together with the x-axis forms a container, such that the container contains the most water. ## Solution ``` Python def solve(height): result, left, right = 0, 0, len(height) - 1 while left < right: result = max(result, min(height[left], height[right]) * (right - left)) if height[left] < height[right]: left += 1 else: right -= 1 return result ``` ## Test Cases ``` Python assert (got := solve([1, 8, 6, 2, 5, 4, 8, 3, 7])) == 49, f"{got=}" assert (got := solve([1, 1])) == 1, f"{got=}" assert (got := solve([4, 3, 2, 1, 4])) == 16, f"{got=}" assert (got := solve([1, 2, 4, 3])) == 4, f"{got=}" assert (got := solve([1, 2, 1])) == 2, f"{got=}" assert (got := solve([1, 8, 100, 2, 100, 4, 8, 3, 7])) == 200, f"{got=}" ``` # [Integer to Roman](https://leetle.app/?date=2025-02-16) Write a function `solve` that converts an integer to a roman numeral. ## Solution ``` Python def solve(num): roman = dict( zip( (1_000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1), "M CM D CD C XC L XL X IX V IV I".split(), ) ) result = "" for i in roman: if num > 0: times, num = divmod(num, i) result += roman[i] * times return result ``` ## Test Cases ``` Python assert (got := solve(3)) == "III", f"{got=}" assert (got := solve(58)) == "LVIII", f"{got=}" assert (got := solve(1994)) == "MCMXCIV", f"{got=}" assert (got := solve(3999)) == "MMMCMXCIX", f"{got=}" assert (got := solve(9)) == "IX", f"{got=}" assert (got := solve(40)) == "XL", f"{got=}" ``` # [Add Binary](https://leetle.app/?date=2025-02-17) Write a function `solve` that adds two binary strings and returns their sum as a binary string. ## Solution ``` Python def solve(a, b): return bin(int(a, 2) + int(b, 2))[2:] ``` ## Test Cases ``` Python assert (got := solve("11", "1")) == "100", f"{got=}" assert (got := solve("1010", "1011")) == "10101", f"{got=}" assert (got := solve("0", "0")) == "0", f"{got=}" assert (got := solve("1111", "1111")) == "11110", f"{got=}" assert (got := solve("1", "111")) == "1000", f"{got=}" assert (got := solve("1001", "1")) == "1010", f"{got=}" ``` # [Remove Nth Node From End of List](https://leetle.app/?date=2025-02-18) Write a function `solve` that removes the nth node from the end of a singly linked list. Return the head. ## Solution ``` Python def solve(head, n): tortoise = hare = head for _ in range(n): hare = hare.next if not hare: return head.next while hare and hare.next: hare, tortoise = hare.next, tortoise.next tortoise.next = tortoise.next.next return head ``` ## Test Cases ``` Python # Singly Linked List Definition class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def sl(ls): if not ls: return None root = node = ListNode(ls[0]) for i in ls[1:]: node.next = ListNode(i) node = node.next return root def t(x): r = [] while x: r.append(x.val) x = x.next return r assert (got := t(solve(sl([1, 2, 3, 4, 5]), 2))) == [1, 2, 3, 5], f"{got=}" assert (got := t(solve(sl([1]), 1))) == [], f"{got=}" assert (got := t(solve(sl([1, 2]), 1))) == [1], f"{got=}" assert (got := t(solve(sl([1, 2]), 2))) == [2], f"{got=}" assert (got := t(solve(sl([1, 2, 3]), 3))) == [2, 3], f"{got=}" assert (got := t(solve(sl([2, 4, 6, 8, 10]), 5))) == [4, 6, 8, 10], f"{got=}" ``` # [Invert a Binary Tree](https://leetle.app/?date=2025-02-19) Write a function `solve` that inverts a binary tree. Return the root of the inverted tree. ## Solution ``` Python def solve(root): if root: root.left, root.right = solve(root.right), solve(root.left) return root ``` ## Test Cases ``` Python # Binary Tree Definition class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node def t(root): result = [] if root is None: return [] queue = [root] while queue: curr = queue.pop(0) if curr is None: result.append(None) continue result.append(curr.val) queue.append(curr.left) queue.append(curr.right) while result[-1] is None: result.pop() return result assert (got := t(solve(bt([4, 2, 7, 1, 3, 6, 9])))) == [ 4, 7, 2, 9, 6, 3, 1, ], f"{got=}" assert (got := t(solve(bt([])))) == [], f"{got=}" assert (got := t(solve(bt([1])))) == [1], f"{got=}" assert (got := t(solve(bt([2, 1, 3])))) == [2, 3, 1], f"{got=}" assert (got := t(solve(bt([3, 9, 20, None, None, 15, 7])))) == [ 3, 20, 9, 7, 15, ], f"{got=}" assert (got := t(solve(bt([1, 2, 3, 4, None, 5])))) == [ 1, 3, 2, None, 5, None, 4, ], f"{got=}" ``` # [Majority Element II (n/3)](https://leetle.app/?date=2025-02-20) Write a function `solve` that finds all elements that appear more than n/3 times in an array. ## Solution ``` Python def solve(nums): return [i for i in dict.fromkeys(nums) if nums.count(i) > len(nums) // 3] ``` ## Test Cases ``` Python assert (got := solve([3, 2, 3])) == [3], f"{got=}" assert (got := solve([1])) == [1], f"{got=}" assert (got := solve([1, 2])) == [1, 2], f"{got=}" assert (got := solve([2, 2, 1, 1, 1, 2, 2])) == [2, 1], f"{got=}" assert (got := solve([])) == [], f"{got=}" assert (got := solve([8, 8, 8, 8, 9])) == [8], f"{got=}" ``` # [Validate BST](https://leetle.app/?date=2025-02-21) Write a function `solve` that checks if a binary tree is a valid binary search tree. ## Solution ``` Python def solve(root): val = None while root: if not root.left: if val is not None and root.val <= val: return False val, root = root.val, root.right else: prev = root.left while prev.right and prev.right != root: prev = prev.right if not prev.right: prev.right, root = root, root.left else: prev.right = None if val is not None and root.val <= val: return False val, root = root.val, root.right return True ``` ## Test Cases ``` Python # Binary Tree Definition class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([2, 1, 3]))) is True, f"{got=}" assert (got := solve(bt([5, 1, 4, None, None, 3, 6]))) is False, f"{got=}" assert (got := solve(bt([]))) is True, f"{got=}" assert (got := solve(bt([1, None, 1]))) is False, f"{got=}" assert (got := solve(bt([10, 5, 15, None, None, 6, 20]))) is False, f"{got=}" assert (got := solve(bt([3, 2, 5, 1]))) is True, f"{got=}" ``` # [Unique Paths in a Grid](https://leetle.app/?date=2025-02-22) Write a function `solve` that returns the number of possible unique paths to reach bottom-right from top-left in an m x n grid (only moves down or right). ## Solution ``` Python def solve(m, n): paths = 1 for i in range(m - 1): paths = paths * (i + n) // (i + 1) return paths ``` ## Test Cases ``` Python assert (got := solve(3, 7)) == 28, f"{got=}" assert (got := solve(3, 2)) == 3, f"{got=}" assert (got := solve(7, 3)) == 28, f"{got=}" assert (got := solve(1, 1)) == 1, f"{got=}" assert (got := solve(2, 2)) == 2, f"{got=}" assert (got := solve(3, 3)) == 6, f"{got=}" ``` # [Best Time to Buy and Sell Stock](https://leetle.app/?date=2025-02-23) Write a function `solve` that calculates the maximum profit you can achieve from buying and selling stocks multiple times. You may not engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). The input is an array of prices where prices[i] is the price of a given stock on the ith day. ## Solution ``` Python def solve(prices): return sum(max(prices[i + 1] - prices[i], 0) for i in range(len(prices) - 1)) ``` ## Test Cases ``` Python assert (got := solve([7, 1, 5, 3, 6, 4])) == 7, f"{got=}" assert (got := solve([1, 2, 3, 4, 5])) == 4, f"{got=}" assert (got := solve([7, 6, 4, 3, 1])) == 0, f"{got=}" assert (got := solve([1, 7, 2, 3, 6, 7, 6, 7])) == 12, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([2, 2, 2])) == 0, f"{got=}" assert (got := solve([7, 10, 1, 3, 6, 9, 2])) == 11, f"{got=}" assert (got := solve([1, 3, 6, 9, 11])) == 10, f"{got=}" ``` # [Jump Game](https://leetle.app/?date=2025-02-24) Write a function `solve` that determines if you can reach the last index in an array. Each element represents the maximum jump length at that position. ## Solution ``` Python def solve(nums): x = 0 for i, n in enumerate(nums): if x < i: return False x = max(x, i + n) return True ``` ## Test Cases ``` Python assert (got := solve([2, 3, 1, 1, 4])) is True, f"{got=}" assert (got := solve([3, 2, 1, 0, 4])) is False, f"{got=}" assert (got := solve([0])) is True, f"{got=}" assert (got := solve([1, 0, 1])) is False, f"{got=}" assert (got := solve([1, 1, 1, 1, 1])) is True, f"{got=}" assert (got := solve([1, 1, 1, 1, 0])) is True, f"{got=}" ``` # [Rotate Array](https://leetle.app/?date=2025-02-25) Write a function `solve` that rotates an array to the right by k steps. Ideally, you should be able to rotate the array in-place, but be sure to still return your solution. ## Solution ``` Python def solve(nums, k): return nums[-k % len(nums) :] + nums[: -k % len(nums)] ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 4, 5, 6, 7], 3)) == [ 5, 6, 7, 1, 2, 3, 4, ], f"{got=}" assert (got := solve([-1, -100, 3, 99], 2)) == [3, 99, -1, -100], f"{got=}" assert (got := solve([1], 0)) == [1], f"{got=}" assert (got := solve([1, 2], 3)) == [2, 1], f"{got=}" assert (got := solve([1, 2, 3], 3)) == [1, 2, 3], f"{got=}" assert (got := solve([2, 4, 6, 8], 1)) == [8, 2, 4, 6], f"{got=}" ``` # [Valid Palindrome One Deletion](https://leetle.app/?date=2025-02-26) Write a function `solve` that returns true if the string can become a palindrome by deleting at most one character. ## Solution ``` Python def solve(s): for x in [s] + [(s[:i] + s[i + 1 :]) for i in range(len(s))]: if (r := "".join(i for i in x.lower() if i.isalnum())) == r[::-1]: return True return False ``` ## Test Cases ``` Python assert (got := solve("aba")) is True, f"{got=}" assert (got := solve("abca")) is True, f"{got=}" assert (got := solve("abc")) is False, f"{got=}" assert (got := solve("cbbcc")) is True, f"{got=}" assert (got := solve("a")) is True, f"{got=}" assert (got := solve("raceacar")) is True, f"{got=}" ``` # [Unique Paths](https://leetle.app/?date=2025-02-27) Write a function `solve` that returns the number of unique paths if the grid has obstacles (1 means blocked). ## Solution ``` Python def solve(obstacleGrid): paths = [0] * len(obstacleGrid[0]) paths[0] = int(not obstacleGrid[0][0]) for x in range(len(obstacleGrid)): for y in range(len(obstacleGrid[0])): if obstacleGrid[x][y] == 1: paths[y] = 0 elif y > 0: paths[y] += paths[y - 1] return paths[-1] ``` ## Test Cases ``` Python assert (got := solve([[0, 0, 0], [0, 1, 0], [0, 0, 0]])) == 2, f"{got=}" assert (got := solve([[0, 1], [0, 0]])) == 1, f"{got=}" assert (got := solve([[1]])) == 0, f"{got=}" assert (got := solve([[0]])) == 1, f"{got=}" assert (got := solve([[0, 0], [1, 0]])) == 1, f"{got=}" assert (got := solve([[0, 0], [0, 1]])) == 0, f"{got=}" ``` # [Counting Inversions](https://leetle.app/?date=2025-02-28) Write a function `solve` that counts the number of inversions in an array. An inversion is a pair of elements that are out of order. ## Solution ``` Python def solve(nums): return len([(x, y) for i, x in enumerate(nums) for y in nums[i + 1 :] if x > y]) ``` ## Test Cases ``` Python assert (got := solve([2, 4, 1, 3, 5])) == 3, f"{got=}" assert (got := solve([1, 2, 3, 4, 5])) == 0, f"{got=}" assert (got := solve([5, 4, 3, 2, 1])) == 10, f"{got=}" assert (got := solve([1, 1, 1, 1, 1])) == 0, f"{got=}" assert (got := solve([1, 3, 5, 2, 4, 6])) == 3, f"{got=}" assert (got := solve([1, 5, 3, 2, 4])) == 4, f"{got=}" ``` # [Kth Largest Element](https://leetle.app/?date=2025-03-01) Write a function `solve` that finds the kth largest element in an unsorted array. ## Solution ``` Python def solve(nums, k): return sorted(nums, reverse=True)[k - 1] ``` ## Test Cases ``` Python assert (got := solve([3, 2, 1, 5, 6, 4], 2)) == 5, f"{got=}" assert (got := solve([3, 2, 1], 1)) == 3, f"{got=}" assert (got := solve([2, 2, 3, 1], 2)) == 2, f"{got=}" assert (got := solve([10, 10, 9], 1)) == 10, f"{got=}" assert (got := solve([5, 4, 3, 2, 1], 1)) == 5, f"{got=}" assert (got := solve([5, 4, 3, 2, 1], 5)) == 1, f"{got=}" ``` # [Longest Common Prefix](https://leetle.app/?date=2025-03-02) Write a function `solve` that finds the longest common prefix among an array of strings. ## Solution ``` Python def solve(strs): if len(strs) < 2: return ("", strs[0])[len(strs)] strs.sort() i = 0 while i < min(len(strs[0]), len(strs[-1])) and strs[0][i] == strs[-1][i]: i += 1 return strs[0][:i] ``` ## Test Cases ``` Python assert (got := solve(["flower", "flow", "flight"])) == "fl", f"{got=}" assert (got := solve(["dog", "racecar", "car"])) == "", f"{got=}" assert (got := solve(["interspecies", "interstellar", "interstate"])) == "inters", ( f"{got=}" ) assert (got := solve([""])) == "", f"{got=}" assert (got := solve(["a"])) == "a", f"{got=}" assert (got := solve(["prefix", "prefix"])) == "prefix", f"{got=}" ``` # [Spiral Matrix](https://leetle.app/?date=2025-03-03) Write a function `solve` that returns all elements of an m x n matrix in spiral order. ## Solution ``` Python def solve(matrix): return matrix and [*matrix.pop(0)] + solve([*zip(*matrix)][::-1]) ``` ## Test Cases ``` Python assert (got := solve([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) == [ 1, 2, 3, 6, 9, 8, 7, 4, 5, ], f"{got=}" assert (got := solve([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]])) == [ 1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7, ], f"{got=}" assert (got := solve([[1]])) == [1], f"{got=}" assert (got := solve([[1, 2], [3, 4]])) == [1, 2, 4, 3], f"{got=}" assert (got := solve([])) == [], f"{got=}" assert (got := solve([[1, 2, 3]])) == [1, 2, 3], f"{got=}" ``` # [Reorder List](https://leetle.app/?date=2025-03-04) Write a function `solve` that reorders a singly linked list such that the last element becomes the second element. ie: `L0→L1→...→Ln-1→Ln` becomes `L0→Ln→L1→Ln-1→...` ## Solution ``` Python def solve(head): if not head: return None tortoise = hare = head while hare and hare.next: tortoise, hare = tortoise.next, hare.next.next previous, current = None, tortoise while current: current.next, previous, current = previous, current, current.next previous, current = head, previous while current.next: previous.next, previous = current, previous.next current.next, current = previous, current.next return head ``` ## Test Cases ``` Python # Singly Linked List Definition class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def sl(ls): if not ls: return None root = node = ListNode(ls[0]) for i in ls[1:]: node.next = ListNode(i) node = node.next return root def t(x): r = [] while x: r.append(x.val) x = x.next return r assert (got := t(solve(sl([1, 2, 3, 4, 5])))) == [1, 5, 2, 4, 3], f"{got=}" assert (got := t(solve(sl([1, 2, 3, 4])))) == [1, 4, 2, 3], f"{got=}" assert (got := t(solve(sl([1])))) == [1], f"{got=}" assert (got := t(solve(sl([])))) == [], f"{got=}" assert (got := t(solve(sl([1, 2])))) == [1, 2], f"{got=}" assert (got := t(solve(sl([1, 2, 3])))) == [1, 3, 2], f"{got=}" ``` # [Group Anagrams](https://leetle.app/?date=2025-03-05) Write a function `solve` that groups anagrams together. ## Solution ``` Python def solve(strs): result = {} for s in strs: result.setdefault("".join(sorted(s)), []).append(s) return list(result.values()) ``` ## Test Cases ``` Python assert (got := solve(["eat", "tea", "tan", "ate", "nat", "bat"])) == [ ["eat", "tea", "ate"], ["tan", "nat"], ["bat"], ], f"{got=}" assert (got := solve([""])) == [[""]], f"{got=}" assert (got := solve(["a"])) == [["a"]], f"{got=}" assert (got := solve(["ab", "ba", "abc", "cba"])) == [ ["ab", "ba"], ["abc", "cba"], ], f"{got=}" assert (got := solve(["listen", "silent", "enlist"])) == [ ["listen", "silent", "enlist"] ], f"{got=}" assert (got := solve(["rat", "tar", "art"])) == [["rat", "tar", "art"]], f"{got=}" ``` # [Binary Search](https://leetle.app/?date=2025-03-06) Write a function `solve` that performs a binary search on a sorted list to find a target and return its index. If the target is not in the list, return -1. ## Solution ``` Python def solve(nums, target): lo, hi = 0, len(nums) while lo < hi: mid = (lo + hi) // 2 if nums[mid] < target: lo = mid + 1 elif nums[mid] > target: hi = mid else: return mid return -1 ``` ## Test Cases ``` Python assert (got := solve([1, 2, 4, 5, 7, 9], 5)) == 3, f"{got=}" assert (got := solve([1, 2, 4, 5, 7, 9], 6)) == -1, f"{got=}" assert (got := solve([1, 2, 4, 5, 7, 9], 1)) == 0, f"{got=}" assert (got := solve([1, 2, 4, 5, 7, 9], 9)) == 5, f"{got=}" assert (got := solve([1, 2, 4, 5, 7, 9], 2)) == 1, f"{got=}" assert (got := solve([1, 2, 4, 5, 7, 9], 4)) == 2, f"{got=}" ``` # [Hamming Distance](https://leetle.app/?date=2025-03-07) Write a function `solve` that computes the Hamming distance between two integers (number of differing bits). ## Solution ``` Python def solve(x, y): return (x ^ y).bit_count() ``` ## Test Cases ``` Python assert (got := solve(1, 4)) == 2, f"{got=}" assert (got := solve(3, 1)) == 1, f"{got=}" assert (got := solve(0, 0)) == 0, f"{got=}" assert (got := solve(7, 8)) == 4, f"{got=}" assert (got := solve(10, 20)) == 4, f"{got=}" assert (got := solve(15, 15)) == 0, f"{got=}" ``` # [Multiply Strings](https://leetle.app/?date=2025-03-08) Write a function `solve` that multiplies two non-negative integers represented as strings. ## Solution ``` Python def solve(num1, num2): return str(int(num1) * int(num2)) ``` ## Test Cases ``` Python assert (got := solve("123", "456")) == "56088", f"{got=}" assert (got := solve("2", "3")) == "6", f"{got=}" assert (got := solve("0", "0")) == "0", f"{got=}" assert (got := solve("123", "0")) == "0", f"{got=}" assert (got := solve("2", "2")) == "4", f"{got=}" assert (got := solve("999", "999")) == "998001", f"{got=}" ``` # [Subset Sum](https://leetle.app/?date=2025-03-09) Write a function `solve` to determine if a subset of a list sums to a given target. ## Solution ``` Python def solve(nums, target): if target == 0: return True if not nums: return False return solve(nums[:-1], target) or solve(nums[:-1], target - nums[-1]) ``` ## Test Cases ``` Python assert (got := solve([2, 3, 7, 8, 10], 11)) is True, f"{got=}" assert (got := solve([1, 2, 3, 4, 5], 9)) is True, f"{got=}" assert (got := solve([1, 2, 3, 4, 5], 15)) is True, f"{got=}" assert (got := solve([1, 2, 3, 4, 5], 16)) is False, f"{got=}" assert (got := solve([1, 2, 3, 4, 5], 0)) is True, f"{got=}" assert (got := solve([1, 2, 3, 4, 5], 1)) is True, f"{got=}" ``` # [Find All Duplicates in an Array](https://leetle.app/?date=2025-03-10) Write a function `solve` that finds all integers that appear exactly twice in an array where each integer is in the range [1, n] (inclusive) where n is the size of the array. Return the list of duplicates in ascending order. ## Solution ``` Python def solve(nums): return sorted(i for i in set(nums) if nums.count(i) > 1) ``` ## Test Cases ``` Python assert (got := solve([4, 3, 2, 7, 8, 2, 3, 1])) == [2, 3], f"{got=}" assert (got := solve([1, 1, 2, 3, 3, 4, 5, 5])) == [1, 3, 5], f"{got=}" assert (got := solve([1])) == [], f"{got=}" assert (got := solve([1, 1])) == [1], f"{got=}" assert (got := solve([1, 1, 2, 2])) == [1, 2], f"{got=}" assert (got := solve([1, 2, 3, 4])) == [], f"{got=}" ``` # [Unique Email Addresses](https://leetle.app/?date=2025-03-11) Write a function `solve` that returns the number of unique email addresses in an array after parsing '+' and '.' rules. Every valid email consists of a local name and a domain name, separated by the '@' sign. Besides lowercase letters, the email may contain one or more '.' or '+'. If there are periods '.' between some characters in the local name part of an email address, mail sent there will be forwarded to the same address without dots in the local name. If there is a plus '+' in the local name, everything after the first plus sign will be ignored. This allows certain emails to be filtered. Note that these rules do not apply to domain names. ## Solution ``` Python def solve(emails): return len( { (name.split("+")[0].replace(".", ""), domain) for name, domain in (email.rsplit("@", 1) for email in emails) } ) ``` ## Test Cases ``` Python assert ( got := solve(["test.email+alex@leetle.app", "test.e.mail+bob.cathy@leetle.app"]) ) == 1, f"{got=}" assert (got := solve(["a@leetle.app", "b@leetle.app", "c@leetle.app"])) == 3, f"{got=}" assert ( got := solve(["test.email+alex@leetle.app", "test.email.leet+alex@le.app"]) ) == 2, f"{got=}" assert (got := solve(["test.email+alex@leetle.app", "test.email@leetle.app"])) == 1, ( f"{got=}" ) assert ( got := solve(["test.email+alex@leetle.app", "test.email+alex@leetle.app"]) ) == 1, f"{got=}" assert (got := solve(["test.email+alex@leetle.app", "test.email+alex@le.app"])) == 2, ( f"{got=}" ) ``` # [Binary Tree Preorder Traversal](https://leetle.app/?date=2025-03-12) Write `solve` for the preorder traversal of a binary tree. Return the list of values in preorder. ## Solution ``` Python def solve(root): if root is None: return [] return [root.val] + solve(root.left) + solve(root.right) ``` ## Test Cases ``` Python # Binary Tree Definition class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return None elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return None node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([1, None, 2, 3]))) == [1, 2, 3], f"{got=}" assert (got := solve(bt([]))) == [], f"{got=}" assert (got := solve(bt([1]))) == [1], f"{got=}" assert (got := solve(bt([1, 2, 3]))) == [1, 2, 3], f"{got=}" assert (got := solve(bt([1, None, 2]))) == [1, 2], f"{got=}" assert (got := solve(bt([1, 2, 3, 4, 5]))) == [1, 2, 4, 5, 3], f"{got=}" ``` # [Best Time to Buy and Sell Stock with Cooldown](https://leetle.app/?date=2025-03-13) Write a function `solve` to maximize profit with a 1-day cooldown period after selling. You cannot engage in multiple transactions simultaneously (i.e., you must sell the stock before you buy again). The input is an array of prices where prices[i] is the price of a given stock on the ith day. ## Solution ``` Python def solve(prices): dp = [[0, 0, 0] for _ in range(len(prices) + 1)] dp[0][0] = -prices[0] buy, sell, keep = range(3) for i in range(len(prices)): dp[i + 1][buy] = max(dp[i][buy], dp[i][keep] - prices[i]) dp[i + 1][sell] = max(dp[i][sell], dp[i][buy] + prices[i]) dp[i + 1][keep] = dp[i][sell] return dp[-1][sell] ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 0, 2])) == 3, f"{got=}" assert (got := solve([1])) == 0, f"{got=}" assert (got := solve([1, 2])) == 1, f"{got=}" assert (got := solve([2, 1, 4])) == 3, f"{got=}" assert (got := solve([1, 2, 3, 4, 5])) == 4, f"{got=}" assert (got := solve([7, 1, 5, 3, 6, 4])) == 5, f"{got=}" ``` # [Permutation in String](https://leetle.app/?date=2025-03-14) Write a function `solve` to return true if s2 contains any permutation of s1. A permutation is any rearrangement of the characters. ## Solution ``` Python from itertools import permutations def solve(s1, s2): for s in {"".join(i) for i in permutations(s1)}: if s in s2: return True return False ``` ## Test Cases ``` Python assert (got := solve("ab", "eidbaooo")) is True, f"{got=}" assert (got := solve("ab", "eidboaoo")) is False, f"{got=}" assert (got := solve("abc", "ccccbbbbaaaa")) is False, f"{got=}" assert (got := solve("adc", "dcda")) is True, f"{got=}" assert (got := solve("hello", "ooolleoooleh")) is False, f"{got=}" assert (got := solve("a", "ab")) is True, f"{got=}" ``` # [Reverse a String](https://leetle.app/?date=2025-03-15) Write a function `solve` that reverses a string. ## Solution ``` Python def solve(s): return s[::-1] ``` ## Test Cases ``` Python assert (got := solve("hello")) == "olleh", f"{got=}" assert (got := solve("world")) == "dlrow", f"{got=}" assert (got := solve("aaaaa")) == "aaaaa", f"{got=}" assert (got := solve("")) == "", f"{got=}" assert (got := solve("a")) == "a", f"{got=}" assert (got := solve("racecar")) == "racecar", f"{got=}" ``` # [Check if a Number is Even](https://leetle.app/?date=2025-03-16) Write a function `solve` that checks if a number is even. ## Solution ``` Python def solve(num): return not num & 1 ``` ## Test Cases ``` Python assert (got := solve(4)) is True, f"{got=}" assert (got := solve(7)) is False, f"{got=}" assert (got := solve(0)) is True, f"{got=}" assert (got := solve(100)) is True, f"{got=}" assert (got := solve(99)) is False, f"{got=}" assert (got := solve(-2)) is True, f"{got=}" ``` # [Find the Maximum of Three Numbers](https://leetle.app/?date=2025-03-17) Write a function `solve` that finds the maximum of three numbers. ## Solution ``` Python def solve(a, b, c): return max(a, b, c) ``` ## Test Cases ``` Python assert (got := solve(3, 7, 5)) == 7, f"{got=}" assert (got := solve(10, 3, 15)) == 15, f"{got=}" assert (got := solve(5, 5, 5)) == 5, f"{got=}" assert (got := solve(-1, -3, -2)) == -1, f"{got=}" assert (got := solve(0, 0, 1)) == 1, f"{got=}" assert (got := solve(100, 50, 25)) == 100, f"{got=}" ``` # [Check if a String is a Palindrome](https://leetle.app/?date=2025-03-18) Write a function `solve` that checks if a string is a palindrome (reads the same backward as forward). ## Solution ``` Python def solve(s): return s == s[::-1] ``` ## Test Cases ``` Python assert (got := solve("racecar")) is True, f"{got=}" assert (got := solve("hello")) is False, f"{got=}" assert (got := solve("level")) is True, f"{got=}" assert (got := solve("a")) is True, f"{got=}" assert (got := solve("")) is True, f"{got=}" assert (got := solve("noon")) is True, f"{got=}" ``` # [Find the Length of a List](https://leetle.app/?date=2025-03-19) Write a function `solve` that returns the length of a list. ## Solution ``` Python def solve(arr): return len(arr) ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 4])) == 4, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([1])) == 1, f"{got=}" assert (got := solve([1, 2, 3, 4, 5, 6])) == 6, f"{got=}" assert (got := solve([0, 0, 0])) == 3, f"{got=}" assert (got := solve(["a", "b", "c"])) == 3, f"{got=}" ``` # [Sum of All Numbers in a List](https://leetle.app/?date=2025-03-20) Write a function `solve` that calculates the sum of all numbers in a list. ## Solution ``` Python def solve(nums): return sum(nums) ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 4])) == 10, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([5])) == 5, f"{got=}" assert (got := solve([10, 20, 30])) == 60, f"{got=}" assert (got := solve([-1, 1])) == 0, f"{got=}" assert (got := solve([-5, -3, -1])) == -9, f"{got=}" ``` # [Find the First Non-Repeating Character](https://leetle.app/?date=2025-03-21) Write a function `solve` that finds the first non-repeating character in a string. Return the character, or an empty string if no such character exists. ## Solution ``` Python def solve(s): for c in s: if s.count(c) == 1: return c return "" ``` ## Test Cases ``` Python assert (got := solve("aabbcdd")) == "c", f"{got=}" assert (got := solve("hello")) == "h", f"{got=}" assert (got := solve("aabb")) == "", f"{got=}" assert (got := solve("z")) == "z", f"{got=}" assert (got := solve("")) == "", f"{got=}" assert (got := solve("leetcode")) == "l", f"{got=}" ``` # [Convert a String to Uppercase](https://leetle.app/?date=2025-03-22) Write a function `solve` that converts a string to uppercase. ## Solution ``` Python def solve(s): return s.upper() ``` ## Test Cases ``` Python assert (got := solve("hello")) == "HELLO", f"{got=}" assert (got := solve("WORLD")) == "WORLD", f"{got=}" assert (got := solve("Hello World")) == "HELLO WORLD", f"{got=}" assert (got := solve("aaaaa")) == "AAAAA", f"{got=}" assert (got := solve("")) == "", f"{got=}" assert (got := solve("a")) == "A", f"{got=}" ``` # [Find the Factorial of a Number](https://leetle.app/?date=2025-03-23) Write a function `solve` that calculates the factorial of a number. See [21 Factorial](#factorial). ## Solution ``` Python from factorial_021 import solve ``` ## Test Cases ``` Python assert (got := solve(5)) == 120, f"{got=}" assert (got := solve(0)) == 1, f"{got=}" assert (got := solve(1)) == 1, f"{got=}" assert (got := solve(10)) == 3628800, f"{got=}" assert (got := solve(3)) == 6, f"{got=}" assert (got := solve(7)) == 5040, f"{got=}" ``` # [Merge Two Lists](https://leetle.app/?date=2025-03-24) Write a function `solve` that merges two lists into a single list. ## Solution ``` Python def solve(list1, list2): return list1 + list2 ``` ## Test Cases ``` Python assert (got := solve([1, 2], [3, 4])) == [1, 2, 3, 4], f"{got=}" assert (got := solve([], [])) == [], f"{got=}" assert (got := solve([1], [2])) == [1, 2], f"{got=}" assert (got := solve([1, 2, 3], [])) == [1, 2, 3], f"{got=}" assert (got := solve([], [4, 5, 6])) == [4, 5, 6], f"{got=}" assert (got := solve([1, 3, 5], [2, 4, 6])) == [1, 3, 5, 2, 4, 6], f"{got=}" ``` # [Return the Last Element of a List](https://leetle.app/?date=2025-03-25) Write a function `solve` that returns the last element of a list, or null if the list is empty. ## Solution ``` Python def solve(arr): if arr: return arr[-1] ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 4])) == 4, f"{got=}" assert (got := solve([])) is None, f"{got=}" assert (got := solve([5])) == 5, f"{got=}" assert (got := solve([10, 20, 30])) == 30, f"{got=}" assert (got := solve(["a", "b", "c"])) == "c", f"{got=}" assert (got := solve([True, False])) is False, f"{got=}" ``` # [Remove Duplicates from a List](https://leetle.app/?date=2025-03-26) Write a function `solve` that removes duplicates from a list while preserving the original order. ## Solution ``` Python def solve(arr): return list(dict.fromkeys(arr)) ``` ## Test Cases ``` Python assert (got := solve([1, 2, 2, 3, 4, 4])) == [1, 2, 3, 4], f"{got=}" assert (got := solve([])) == [], f"{got=}" assert (got := solve([5, 5, 5])) == [5], f"{got=}" assert (got := solve([1, 2, 3])) == [1, 2, 3], f"{got=}" assert (got := solve([3, 1, 3, 2, 1])) == [3, 1, 2], f"{got=}" assert (got := solve(["a", "a", "b", "c", "b"])) == ["a", "b", "c"], f"{got=}" ``` # [Find the Intersection of Two Lists](https://leetle.app/?date=2025-03-27) Write a function `solve` that finds the intersection of two lists (elements that appear in both lists), and returns a sorted list of these elements. ## Solution ``` Python def solve(list1, list2): return sorted(set(list1) & set(list2)) ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3], [2, 3, 4])) == [2, 3], f"{got=}" assert (got := solve([], [])) == [], f"{got=}" assert (got := solve([1, 2], [3, 4])) == [], f"{got=}" assert (got := solve([1, 1, 2, 2], [2, 2])) == [2], f"{got=}" assert (got := solve([1, 2, 3], [1, 2, 3])) == [1, 2, 3], f"{got=}" assert (got := solve(["a", "b", "c"], ["b", "c", "d"])) == [ "b", "c", ], f"{got=}" ``` # [Check if a String Contains a Substring](https://leetle.app/?date=2025-03-28) Write a function `solve` that checks if a string contains a given substring. ## Solution ``` Python def solve(s, substring): return substring in s ``` ## Test Cases ``` Python assert (got := solve("hello", "ell")) is True, f"{got=}" assert (got := solve("world", "xyz")) is False, f"{got=}" assert (got := solve("python", "")) is True, f"{got=}" assert (got := solve("", "a")) is False, f"{got=}" assert (got := solve("testing", "test")) is True, f"{got=}" assert (got := solve("banana", "nana")) is True, f"{got=}" ``` # [Generate a List of Squares from 1 to N](https://leetle.app/?date=2025-03-29) Write a function `solve` that generates a list of squares from 1 to N (inclusive). ## Solution ``` Python def solve(n): return [i**2 for i in range(1, n + 1)] ``` ## Test Cases ``` Python assert (got := solve(4)) == [1, 4, 9, 16], f"{got=}" assert (got := solve(1)) == [1], f"{got=}" assert (got := solve(0)) == [], f"{got=}" assert (got := solve(5)) == [1, 4, 9, 16, 25], f"{got=}" assert (got := solve(2)) == [1, 4], f"{got=}" assert (got := solve(7)) == [1, 4, 9, 16, 25, 36, 49], f"{got=}" ``` # [Sort a List](https://leetle.app/?date=2025-03-30) Write a function `solve` that sorts a list of numbers in ascending order. ## Solution ``` Python def solve(arr): return sorted(arr) ``` ## Test Cases ``` Python assert (got := solve([3, 1, 4, 2])) == [1, 2, 3, 4], f"{got=}" assert (got := solve([])) == [], f"{got=}" assert (got := solve([5])) == [5], f"{got=}" assert (got := solve([5, 5, 5])) == [5, 5, 5], f"{got=}" assert (got := solve([9, 8, 7, 6, 5])) == [5, 6, 7, 8, 9], f"{got=}" assert (got := solve([1, 2, 3, 4, 5])) == [1, 2, 3, 4, 5], f"{got=}" ``` # [Check if All Elements in a List Are Unique](https://leetle.app/?date=2025-03-31) Write a function `solve` that checks if all elements in a list are unique (no duplicates). ## Solution ``` Python def solve(arr): return arr == list(set(arr)) ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 4])) is True, f"{got=}" assert (got := solve([1, 2, 2, 3])) is False, f"{got=}" assert (got := solve([])) is True, f"{got=}" assert (got := solve([1])) is True, f"{got=}" assert (got := solve([1, 1, 1, 1])) is False, f"{got=}" assert (got := solve(["a", "b", "c", "a"])) is False, f"{got=}" ``` # [Find the Most Frequent Element](https://leetle.app/?date=2025-04-01) Write a function `solve` that finds the most frequent element in a list. ## Solution ``` Python from collections import Counter def solve(arr): if arr: return Counter(arr).most_common(1)[0][0] ``` ## Test Cases ``` Python assert (got := solve([1, 3, 3, 3, 2, 1])) == 3, f"{got=}" assert (got := solve([1, 1, 2, 2])) == 1, f"{got=}" assert (got := solve([5])) == 5, f"{got=}" assert (got := solve([])) is None, f"{got=}" assert (got := solve(["a", "b", "b", "c"])) == "b", f"{got=}" assert (got := solve([1, 2, 3, 4, 5])) == 1, f"{got=}" ``` # [Return the Absolute Value of a Number](https://leetle.app/?date=2025-04-02) Write a function `solve` that returns the absolute value of a number. ## Solution ``` Python def solve(num): return abs(num) ``` ## Test Cases ``` Python assert (got := solve(-5)) == 5, f"{got=}" assert (got := solve(5)) == 5, f"{got=}" assert (got := solve(0)) == 0, f"{got=}" assert (got := solve(-10.5)) == 10.5, f"{got=}" assert (got := solve(-999)) == 999, f"{got=}" assert (got := solve(42)) == 42, f"{got=}" ``` # [Repeat a String N Times](https://leetle.app/?date=2025-04-03) Write a function `solve` that repeats a string n times. ## Solution ``` Python def solve(s, n): return s * n ``` ## Test Cases ``` Python assert (got := solve("hi", 3)) == "hihihi", f"{got=}" assert (got := solve("abc", 2)) == "abcabc", f"{got=}" assert (got := solve("x", 5)) == "xxxxx", f"{got=}" assert (got := solve("", 10)) == "", f"{got=}" assert (got := solve("hello", 1)) == "hello", f"{got=}" assert (got := solve("world", 0)) == "", f"{got=}" ``` # [Find the Minimum of a List](https://leetle.app/?date=2025-04-04) Write a function `solve` that finds the minimum value in a list. ## Solution ``` Python def solve(arr): return min(arr) ``` ## Test Cases ``` Python assert (got := solve([3, 1, 4, 2])) == 1, f"{got=}" assert (got := solve([5])) == 5, f"{got=}" assert (got := solve([10, 20, -5])) == -5, f"{got=}" assert (got := solve([0, -1, -2])) == -2, f"{got=}" assert (got := solve([1, 2, 3])) == 1, f"{got=}" assert (got := solve([1, 100, 10000])) == 1, f"{got=}" ``` # [Check if a Number is Prime](https://leetle.app/?date=2025-04-05) Write a function `solve` that checks if a number is prime. ## Solution ``` Python def solve(n): return all(n % i for i in range(2, int(n**0.5) + 1)) if n > 1 else False ``` ## Test Cases ``` Python assert (got := solve(7)) is True, f"{got=}" assert (got := solve(4)) is False, f"{got=}" assert (got := solve(1)) is False, f"{got=}" assert (got := solve(2)) is True, f"{got=}" assert (got := solve(-3)) is False, f"{got=}" assert (got := solve(13)) is True, f"{got=}" ``` # [Convert Celsius to Fahrenheit](https://leetle.app/?date=2025-04-06) Write a function `solve` that converts a temperature from Celsius to Fahrenheit. ## Solution ``` Python def solve(celsius): return celsius * 9 / 5 + 32 ``` ## Test Cases ``` Python assert (got := solve(25)) == 77, f"{got=}" assert (got := solve(0)) == 32, f"{got=}" assert (got := solve(-10)) == 14, f"{got=}" assert (got := solve(100)) == 212, f"{got=}" assert (got := solve(-40)) == -40, f"{got=}" assert (got := solve(37)) == 98.6, f"{got=}" ``` # [Count Words in a String](https://leetle.app/?date=2025-04-07) Write a function `solve` that counts the number of words in a string. Words are separated by spaces. ## Solution ``` Python def solve(s): return len(s.split()) ``` ## Test Cases ``` Python assert (got := solve("Hello world, how are you?")) == 5, f"{got=}" assert (got := solve("")) == 0, f"{got=}" assert (got := solve("One")) == 1, f"{got=}" assert (got := solve("spaced words")) == 2, f"{got=}" assert (got := solve("Programming is fun")) == 3, f"{got=}" assert (got := solve("This is a sentence with seven words in it")) == 9, f"{got=}" ``` # [Check if a Year is a Leap Year](https://leetle.app/?date=2025-04-08) Write a function `solve` that determines if a given year is a leap year. ## Solution ``` Python def solve(year): return year % 4 == 0 and (not year % 100 == 0 or year % 400 == 0) ``` ## Test Cases ``` Python assert (got := solve(2020)) is True, f"{got=}" assert (got := solve(2100)) is False, f"{got=}" assert (got := solve(2000)) is True, f"{got=}" assert (got := solve(1900)) is False, f"{got=}" assert (got := solve(2024)) is True, f"{got=}" assert (got := solve(1997)) is False, f"{got=}" ``` # [Generate Fibonacci Sequence](https://leetle.app/?date=2025-04-09) Write a function `solve` that generates the first n numbers of the Fibonacci sequence. The Fibonacci sequence starts with 0 and 1, and each subsequent number is the sum of the two preceding numbers. ## Solution ``` Python def solve(n): a, b, result = 0, 1, [0, 1] for _ in range(n - 2): a, b = b, a + b result.append(b) return result[:n] ``` ## Test Cases ``` Python assert (got := solve(6)) == [0, 1, 1, 2, 3, 5], f"{got=}" assert (got := solve(1)) == [0], f"{got=}" assert (got := solve(2)) == [0, 1], f"{got=}" assert (got := solve(10)) == [0, 1, 1, 2, 3, 5, 8, 13, 21, 34], f"{got=}" assert (got := solve(0)) == [], f"{got=}" assert (got := solve(7)) == [0, 1, 1, 2, 3, 5, 8], f"{got=}" ``` # [Reverse Words in a String](https://leetle.app/?date=2025-04-10) Write a function `solve` that reverses the words in a string without reversing the characters in each word. See [14 Reverse Words](#reversewords) ## Solution ``` Python from reverse_words_014 import solve ``` ## Test Cases ``` Python assert (got := solve("Hello World")) == "World Hello", f"{got=}" assert (got := solve("The quick brown fox")) == "fox brown quick The", f"{got=}" assert (got := solve("a")) == "a", f"{got=}" assert (got := solve("")) == "", f"{got=}" assert (got := solve("Good morning everyone")) == "everyone morning Good", f"{got=}" assert ( got := solve("First Second Third Fourth Fifth") ) == "Fifth Fourth Third Second First", f"{got=}" ``` # [Rotate Linked List](https://leetle.app/?date=2025-04-11) Write a function `solve` that rotates a linked list to the right by k places. ## Solution ``` Python def solve(head, k): if not head or not head.next or not k: return head node, size = head, 1 while node.next is not None: node, size = node.next, size + 1 node.next, k = head, k % size while size - k: node, size = node.next, size - 1 head, node.next = node.next, None return head ``` ## Test Cases ``` Python # Singly Linked List Definition class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def sl(ls): if not ls: return None root = node = ListNode(ls[0]) for i in ls[1:]: node.next = ListNode(i) node = node.next return root def t(x): r = [] while x: r.append(x.val) x = x.next return r assert (got := t(solve(sl([1, 2, 3, 4, 5]), 2))) == [4, 5, 1, 2, 3], f"{got=}" assert (got := t(solve(sl([]), 1))) == [], f"{got=}" assert (got := t(solve(sl([1]), 3))) == [1], f"{got=}" assert (got := t(solve(sl([1, 2]), 0))) == [1, 2], f"{got=}" assert (got := t(solve(sl([1, 2, 3]), 5))) == [2, 3, 1], f"{got=}" assert (got := t(solve(sl([7, 8, 9]), 1))) == [9, 7, 8], f"{got=}" ``` # [Binary Tree Level Order Traversal](https://leetle.app/?date=2025-04-12) Write a function `solve` that returns the level order traversal of a binary tree. ## Solution ``` Python from collections import deque def solve(root): if not root: return [] res, q = [], deque([root]) while q: level = [] for i in range(len(q)): node = q.popleft() level.append(node.val) if node.left: q.append(node.left) if node.right: q.append(node.right) res.append(level) return res ``` ## Test Cases ``` Python # Binary Tree Definition class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([3, 9, 20, None, None, 15, 7]))) == [ [3], [9, 20], [15, 7], ], f"{got=}" assert (got := solve(bt([]))) == [], f"{got=}" assert (got := solve(bt([1]))) == [[1]], f"{got=}" assert (got := solve(bt([1, 2, None, 3]))) == [[1], [2], [3]], f"{got=}" assert (got := solve(bt([1, None, 2]))) == [[1], [2]], f"{got=}" assert (got := solve(bt([5, 4, 6, 3]))) == [[5], [4, 6], [3]], f"{got=}" ``` # [Find Peak Element](https://leetle.app/?date=2025-04-13) Write a function `solve` that finds a peak element in an array (an element greater than its neighbors) and returns its index. ## Solution ``` Python def solve(nums): return nums.index(max(nums)) ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 1])) == 2, f"{got=}" assert (got := solve([1, 1, 1, 3, 5, 6, 4])) == 5, f"{got=}" assert (got := solve([1])) == 0, f"{got=}" assert (got := solve([2, 1])) == 0, f"{got=}" assert (got := solve([1, 2])) == 1, f"{got=}" assert (got := solve([3, 2, 1])) == 0, f"{got=}" ``` # [Move Zeroes](https://leetle.app/?date=2025-04-14) Write a function `solve` that moves all zeroes to the end of an array while maintaining relative order of non-zero elements. ## Solution ``` Python def solve(nums): return [i for i in nums if i] + [0] * nums.count(0) ``` ## Test Cases ``` Python assert (got := solve([0, 1, 0, 3, 12])) == [1, 3, 12, 0, 0], f"{got=}" assert (got := solve([0])) == [0], f"{got=}" assert (got := solve([1, 2, 3])) == [1, 2, 3], f"{got=}" assert (got := solve([0, 0, 1])) == [1, 0, 0], f"{got=}" assert (got := solve([1, 0, 0])) == [1, 0, 0], f"{got=}" assert (got := solve([])) == [], f"{got=}" ``` # [Flatten a 2D Vector](https://leetle.app/?date=2025-04-15) Write a function `solve` that flattens a 2D vector into a 1D list. ## Solution ``` Python def solve(vector): return [i for r in vector for i in r] ``` ## Test Cases ``` Python assert (got := solve([[1, 2], [3], [4, 5, 6]])) == [ 1, 2, 3, 4, 5, 6, ], f"{got=}" assert (got := solve([[]])) == [], f"{got=}" assert (got := solve([[1]])) == [1], f"{got=}" assert (got := solve([[1, 2, 3]])) == [1, 2, 3], f"{got=}" assert (got := solve([[], [4, 5]])) == [4, 5], f"{got=}" assert (got := solve([[7], [8, 9]])) == [7, 8, 9], f"{got=}" ``` # [Find the Difference of Two Strings](https://leetle.app/?date=2025-04-16) Write a function `solve` that finds the character that differs between two strings where one string has one extra character. ## Solution ``` Python def solve(s, t): res = 0 for c in s + t: res ^= ord(c) return chr(res) ``` ## Test Cases ``` Python assert (got := solve("abcd", "abcde")) == "e", f"{got=}" assert (got := solve("", "y")) == "y", f"{got=}" assert (got := solve("a", "aa")) == "a", f"{got=}" assert (got := solve("xyz", "xyza")) == "a", f"{got=}" assert (got := solve("hello", "helloo")) == "o", f"{got=}" assert (got := solve("cat", "cast")) == "s", f"{got=}" ``` # [Find All Anagrams in a String](https://leetle.app/?date=2025-04-17) Write a function `solve` that finds all starting indices of anagrams of a pattern in a string. ## Solution ``` Python from collections import Counter def solve(s, p): sl, pl = len(s), len(p) if sl < pl: return [] sc, pc = Counter(s[:pl]), Counter(p) res = [0] if sc == pc else [] for i in range(sl - pl): sc[s[pl + i]] += 1 sc[s[i]] -= 1 if sc == pc: res.append(i + 1) if sc[s[i]] == 0: del sc[s[i]] return res ``` ## Test Cases ``` Python assert (got := solve("cbaebabacd", "abc")) == [0, 6], f"{got=}" assert (got := solve("abab", "ab")) == [0, 1, 2], f"{got=}" assert (got := solve("", "")) == [0], f"{got=}" assert (got := solve("aaa", "aa")) == [0, 1], f"{got=}" assert (got := solve("abcd", "xyz")) == [], f"{got=}" assert (got := solve("a", "a")) == [0], f"{got=}" ``` # [Sum of Left Leaves in a Binary Tree](https://leetle.app/?date=2025-04-18) Write a function `solve` that finds the sum of all left leaves in a binary tree. ## Solution ``` Python def solve(root, left=False): if not root: return 0 if left and not root.left and not root.right: return root.val return solve(root.left, True) + solve(root.right, False) ``` ## Test Cases ``` Python # Binary Tree Definition class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return None elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return None node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([3, 9, 20, None, None, 15, 7]))) == 24, f"{got=}" assert (got := solve(bt([]))) == 0, f"{got=}" assert (got := solve(bt([1, 2, 3, 4, 5]))) == 4, f"{got=}" assert (got := solve(bt([1, None, 2]))) == 0, f"{got=}" assert (got := solve(bt([1, 2]))) == 2, f"{got=}" assert (got := solve(bt([5, 4, 6, 3]))) == 3, f"{got=}" ``` # [Reverse Vowels in a String](https://leetle.app/?date=2025-04-19) Write a function `solve` that reverses only the vowels in a string. ## Solution ``` Python def solve(s): vs = [c for c in s if c.lower() in "aeiou"] return "".join(vs.pop() if c.lower() in "aeiou" else c for c in s) ``` ## Test Cases ``` Python assert (got := solve("hello")) == "holle", f"{got=}" assert (got := solve("leetcode")) == "leotcede", f"{got=}" assert (got := solve("a")) == "a", f"{got=}" assert (got := solve("xyz")) == "xyz", f"{got=}" assert (got := solve("aeiou")) == "uoiea", f"{got=}" assert (got := solve("")) == "", f"{got=}" ``` # [Intersection of Two Arrays](https://leetle.app/?date=2025-04-20) Write a function `solve` that returns the intersection of two arrays as a sorted list. ## Solution ``` Python def solve(nums1, nums2): res = [] for n1 in nums1: for n2 in nums2: if n1 == n2 and n1 not in res: res.append(n1) return res ``` ## Test Cases ``` Python assert (got := solve([1, 2, 2, 1], [2, 2])) == [2], f"{got=}" assert (got := solve([4, 9, 5], [9, 4, 9, 8, 4])) == [4, 9], f"{got=}" assert (got := solve([], [])) == [], f"{got=}" assert (got := solve([1], [1])) == [1], f"{got=}" assert (got := solve([1, 2], [3, 4])) == [], f"{got=}" assert (got := solve([2, 2, 2], [2])) == [2], f"{got=}" ``` # [Contains Duplicate](https://leetle.app/?date=2025-04-21) Write a function `solve` that determines if an array contains any duplicate elements. ## Solution ``` Python def solve(nums): return len(nums) > len(set(nums)) ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 1])) is True, f"{got=}" assert (got := solve([1, 2, 3, 4])) is False, f"{got=}" assert (got := solve([])) is False, f"{got=}" assert (got := solve([1, 1, 1, 3, 3])) is True, f"{got=}" assert (got := solve([1])) is False, f"{got=}" assert (got := solve([0, 0])) is True, f"{got=}" ``` # [Find Disappeared Numbers in an Array](https://leetle.app/?date=2025-04-22) Write a function `solve` that finds all numbers in the range [1, n] that do not appear in an array of length n. ## Solution ``` Python def solve(nums): return [i for i in range(1, len(nums) + 1) if i not in set(nums)] ``` ## Test Cases ``` Python assert (got := solve([4, 3, 2, 7, 8, 2, 3, 1])) == [5, 6], f"{got=}" assert (got := solve([1, 1])) == [2], f"{got=}" assert (got := solve([1, 2, 3])) == [], f"{got=}" assert (got := solve([2, 2, 2])) == [1, 3], f"{got=}" assert (got := solve([1])) == [], f"{got=}" assert (got := solve([5, 4, 3, 2, 1])) == [], f"{got=}" ``` # [First Unique Character in a String](https://leetle.app/?date=2025-04-23) Write a function `solve` that returns the index of the first non-repeating character in a string, or -1 if none exists. ## Solution ``` Python def solve(s): for i, c in enumerate(s): if s.count(c) == 1: return i return -1 ``` ## Test Cases ``` Python assert (got := solve("leetcode")) == 0, f"{got=}" assert (got := solve("loveleetcode")) == 2, f"{got=}" assert (got := solve("aabb")) == -1, f"{got=}" assert (got := solve("")) == -1, f"{got=}" assert (got := solve("z")) == 0, f"{got=}" assert (got := solve("aaa")) == -1, f"{got=}" ``` # [Excel Sheet Column Title](https://leetle.app/?date=2025-04-24) Write a function `solve` that converts a positive integer to its corresponding Excel column title (1-based). ## Solution ``` Python def solve(n): return chr(ord("@") + (n - 1) // 26).strip("@") + chr(ord("A") + (n - 1) % 26) ``` ## Test Cases ``` Python assert (got := solve(1)) == "A", f"{got=}" assert (got := solve(28)) == "AB", f"{got=}" assert (got := solve(701)) == "ZY", f"{got=}" assert (got := solve(26)) == "Z", f"{got=}" assert (got := solve(52)) == "AZ", f"{got=}" assert (got := solve(27)) == "AA", f"{got=}" ``` # [Isomorphic Strings](https://leetle.app/?date=2025-04-25) Write a function `solve` that determines if two strings are isomorphic (can be mapped one-to-one). ## Solution ``` Python def solve(s, t): if len(s) != len(t): return False ms, mt = {}, {} for cs, ct in zip(s, t): if (cs in ms and ms[cs] != ct) or (ct in mt and mt[ct] != cs): return False ms[cs], mt[ct] = ct, cs return True ``` ## Test Cases ``` Python assert (got := solve("egg", "add")) is True, f"{got=}" assert (got := solve("foo", "bar")) is False, f"{got=}" assert (got := solve("paper", "title")) is True, f"{got=}" assert (got := solve("", "")) is True, f"{got=}" assert (got := solve("badc", "baba")) is False, f"{got=}" assert (got := solve("a", "b")) is True, f"{got=}" ``` # [Find Pivot Index](https://leetle.app/?date=2025-04-26) Write a function `solve` that finds the pivot index where the sum of elements to the left equals the sum to the right, or -1 if none exists. ## Solution ``` Python def solve(nums): for i, _ in enumerate(nums): if sum(nums[:i]) == sum(nums[i + 1 :]): return i return -1 ``` ## Test Cases ``` Python assert (got := solve([1, 7, 3, 6, 5, 6])) == 3, f"{got=}" assert (got := solve([1, 2, 3])) == -1, f"{got=}" assert (got := solve([2, 1, -1])) == 0, f"{got=}" assert (got := solve([])) == -1, f"{got=}" assert (got := solve([0])) == 0, f"{got=}" assert (got := solve([-1, -1, -1, 0, 1, 1])) == 0, f"{got=}" ``` # [Ransom Note](https://leetle.app/?date=2025-04-27) Write a function `solve` that determines if a ransom note can be constructed from a magazine string. ## Solution ``` Python from collections import Counter def solve(ransomNote, magazine): return Counter(ransomNote) <= Counter(magazine) ``` ## Test Cases ``` Python assert (got := solve("aa", "aab")) is True, f"{got=}" assert (got := solve("a", "b")) is False, f"{got=}" assert (got := solve("aa", "ab")) is False, f"{got=}" assert (got := solve("", "")) is True, f"{got=}" assert (got := solve("abc", "abccc")) is True, f"{got=}" assert (got := solve("xyz", "xy")) is False, f"{got=}" ``` # [Find All Numbers Smaller Than Current](https://leetle.app/?date=2025-04-28) Write a function `solve` that returns an array where each element is the count of numbers smaller than the current number. ## Solution ``` Python def solve(nums): return [sum(i < num for i in nums) for num in nums] ``` ## Test Cases ``` Python assert (got := solve([8, 1, 2, 2, 3])) == [4, 0, 1, 1, 3], f"{got=}" assert (got := solve([6, 5, 4, 8])) == [2, 1, 0, 3], f"{got=}" assert (got := solve([7, 7, 7, 7])) == [0, 0, 0, 0], f"{got=}" assert (got := solve([])) == [], f"{got=}" assert (got := solve([1])) == [0], f"{got=}" assert (got := solve([5, 2, 6, 1])) == [2, 1, 3, 0], f"{got=}" ``` # [Replace Elements with Greatest on Right](https://leetle.app/?date=2025-04-29) Write a function `solve` that replaces each element with the greatest element to its right, and the last element with -1. ## Solution ``` Python def solve(arr): return [max(arr[i:]) for i in range(1, len(arr))] + [-1] if len(arr) else [] ``` ## Test Cases ``` Python assert (got := solve([17, 18, 5, 4, 6, 1])) == [18, 6, 6, 6, 1, -1], f"{got=}" assert (got := solve([1, 2, 3])) == [3, 3, -1], f"{got=}" assert (got := solve([4, 3, 2, 1])) == [3, 2, 1, -1], f"{got=}" assert (got := solve([])) == [], f"{got=}" assert (got := solve([1])) == [-1], f"{got=}" assert (got := solve([5, 5, 5])) == [5, 5, -1], f"{got=}" ``` # [Maximum Product of Three Numbers](https://leetle.app/?date=2025-04-30) Write a function `solve` that finds the maximum product of three numbers in an array. ## Solution ``` Python def solve(nums): nums.sort() (a, b), (x, y, z) = nums[:2], nums[-3:] return max(a * b * z, x * y * z) ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 4])) == 24, f"{got=}" assert (got := solve([-4, -3, -2, 1, 60])) == 720, f"{got=}" assert (got := solve([1, 2, 3])) == 6, f"{got=}" assert (got := solve([-100, -2, 0, 1])) == 200, f"{got=}" assert (got := solve([5, 5, 5])) == 125, f"{got=}" assert (got := solve([-10, -10, 5, 2])) == 500, f"{got=}" ``` # [Check If Sentence Is Pangram](https://leetle.app/?date=2025-05-01) Write a function `solve` that checks if a sentence is a pangram (contains every letter of the alphabet at least once). ## Solution ``` Python def solve(sentence): return len({i for i in sentence.lower() if i.isalpha()}) == 26 ``` ## Test Cases ``` Python assert (got := solve("thequickbrownfoxjumpsoverthelazydog")) is True, f"{got=}" assert (got := solve("leetcode")) is False, f"{got=}" assert (got := solve("")) is False, f"{got=}" assert (got := solve("abcdefghijklmnopqrstuvwxyz")) is True, f"{got=}" assert (got := solve("hello world")) is False, f"{got=}" assert (got := solve("the quick brown fox jumps over a lazy dog")) is True, f"{got=}" ``` # [Happy Number](https://leetle.app/?date=2025-05-02) Write a function `solve` that determines if a number is a happy number (eventually reaches 1 when replaced by the sum of the square of each digit). ## Solution ``` Python def solve(n): while n > 90: n = sum(int(i) ** 2 for i in str(n)) return n in {1, 7, 10, 13, 19, 23, 28, 31, 32, 44, 49, 68, 70, 79, 82, 86} ``` ## Test Cases ``` Python assert (got := solve(19)) is True, f"{got=}" assert (got := solve(2)) is False, f"{got=}" assert (got := solve(7)) is True, f"{got=}" assert (got := solve(1)) is True, f"{got=}" assert (got := solve(0)) is False, f"{got=}" assert (got := solve(-1)) is False, f"{got=}" assert (got := solve(932)) is True, f"{got=}" assert (got := solve(91)) is True, f"{got=}" assert (got := solve(6)) is False, f"{got=}" assert (got := solve(20)) is False, f"{got=}" ``` # [Sum of Digits Until One Digit](https://leetle.app/?date=2025-05-03) Write a function `solve` that repeatedly sums the digits of a number until a single digit is obtained. ## Solution ``` Python def solve(num): return (num - 1) % 9 + 1 if num else 0 ``` ## Test Cases ``` Python assert (got := solve(16)) == 7, f"{got=}" assert (got := solve(942)) == 6, f"{got=}" assert (got := solve(0)) == 0, f"{got=}" assert (got := solve(123)) == 6, f"{got=}" assert (got := solve(999)) == 9, f"{got=}" assert (got := solve(10)) == 1, f"{got=}" ``` # [Integer Break](https://leetle.app/?date=2025-05-04) Write a function `solve` that breaks an integer n (n >= 2) into the maximum product of its parts. ## Solution ``` Python def solve(n): if n < 4: return n - 1 return [3 ** (n // 3), 4 * (3 ** (n // 3 - 1)), 2 * (3 ** (n // 3))][n % 3] ``` ## Test Cases ``` Python assert (got := solve(10)) == 36, f"{got=}" assert (got := solve(2)) == 1, f"{got=}" assert (got := solve(3)) == 2, f"{got=}" assert (got := solve(4)) == 4, f"{got=}" assert (got := solve(5)) == 6, f"{got=}" assert (got := solve(6)) == 9, f"{got=}" ``` # [Leaf Similar Trees](https://leetle.app/?date=2025-05-05) Write a function `solve` that checks if a binary tree has only one leaf node or none. ## Solution ``` Python def solve(root): if not root or not root.left and not root.right: return True if root.left and root.right: return False if root.left: return solve(root.left) return solve(root.right) ``` ## Test Cases ``` Python # Binary Tree Definition class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return None elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return None node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([1, 2, 3]))) is False, f"{got=}" assert (got := solve(bt([1, 2, None]))) is True, f"{got=}" assert (got := solve(bt([]))) is True, f"{got=}" assert (got := solve(bt([1]))) is True, f"{got=}" assert (got := solve(bt([1, 2, 3, 4, None]))) is False, f"{got=}" assert (got := solve(bt([1, None, 2]))) is True, f"{got=}" ``` # [Rotate Image](https://leetle.app/?date=2025-05-06) Write a function `solve` that rotates a square matrix 90 degrees clockwise in-place. See [15 Matrix Rotation](#matrixrotation). ## Solution ``` Python from matrix_rotation_015 import solve ``` ## Test Cases ``` Python assert (got := solve([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) == [ [7, 4, 1], [8, 5, 2], [9, 6, 3], ], f"{got=}" assert (got := solve([[1]])) == [[1]], f"{got=}" assert (got := solve([[1, 2], [3, 4]])) == [[3, 1], [4, 2]], f"{got=}" assert ( got := solve([[5, 1, 9, 11], [2, 4, 8, 10], [13, 3, 6, 7], [15, 14, 12, 16]]) ) == [[15, 13, 2, 5], [14, 3, 4, 1], [12, 6, 8, 9], [16, 7, 10, 11]], f"{got=}" assert ( got := solve([[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12], [13, 14, 15, 16]]) ) == [[13, 9, 5, 1], [14, 10, 6, 2], [15, 11, 7, 3], [16, 12, 8, 4]], f"{got=}" assert (got := solve([[2]])) == [[2]], f"{got=}" ``` # [Swap Nodes in Pairs](https://leetle.app/?date=2025-05-07) Write a function `solve` that swaps every two adjacent nodes in a linked list and returns its head. ## Solution ``` Python def solve(head): if head and head.next: head.val, head.next.val = head.next.val, head.val solve(head.next.next) return head ``` ## Test Cases ``` Python # Singly Linked List Definition class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def sl(ls): if not ls: return None root = node = ListNode(ls[0]) for i in ls[1:]: node.next = ListNode(i) node = node.next return root def t(x): r = [] while x: r.append(x.val) x = x.next return r assert (got := t(solve(sl([1, 2, 3, 4])))) == [2, 1, 4, 3], f"{got=}" assert (got := t(solve(sl([])))) == [], f"{got=}" assert (got := t(solve(sl([1])))) == [1], f"{got=}" assert (got := t(solve(sl([1, 2, 3])))) == [2, 1, 3], f"{got=}" assert (got := t(solve(sl([1, 2])))) == [2, 1], f"{got=}" assert (got := t(solve(sl([5, 6, 7, 8, 9])))) == [6, 5, 8, 7, 9], f"{got=}" ``` # [Sum of Leaf Values](https://leetle.app/?date=2025-05-08) Write a function `solve` that returns the sum of all leaf node values in a binary tree. ## Solution ``` Python def solve(root): if root is None: return 0 if not root.left and not root.right: return root.val return solve(root.left) + solve(root.right) ``` ## Test Cases ``` Python # Binary Tree Definition class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([1, 2, 3]))) == 5, f"{got=}" assert (got := solve(bt([1, 2, None]))) == 2, f"{got=}" assert (got := solve(bt([]))) == 0, f"{got=}" assert (got := solve(bt([1]))) == 1, f"{got=}" assert (got := solve(bt([1, 2, 3, 4, None]))) == 7, f"{got=}" assert (got := solve(bt([5, None, 6]))) == 6, f"{got=}" ``` # [Jewels and Stones](https://leetle.app/?date=2025-05-09) Write a function `solve` that counts how many stones are jewels, given strings of jewel types and stones. ## Solution ``` Python def solve(jewels, stones): return len([i for i in stones if i in set(jewels)]) ``` ## Test Cases ``` Python assert (got := solve("aA", "aAAbbbb")) == 3, f"{got=}" assert (got := solve("z", "ZZ")) == 0, f"{got=}" assert (got := solve("", "")) == 0, f"{got=}" assert (got := solve("abc", "abcABC")) == 3, f"{got=}" assert (got := solve("XY", "xxyy")) == 0, f"{got=}" assert (got := solve("a", "aaaaaa")) == 6, f"{got=}" ``` # [Defanging an IP Address](https://leetle.app/?date=2025-05-10) Write a function `solve` that replaces every period in an IP address with '[.]'. ## Solution ``` Python def solve(address): return address.replace(".", "[.]") ``` ## Test Cases ``` Python assert (got := solve("1.1.1.1")) == "1[.]1[.]1[.]1", f"{got=}" assert (got := solve("255.100.50.0")) == "255[.]100[.]50[.]0", f"{got=}" assert (got := solve("192.168.1.1")) == "192[.]168[.]1[.]1", f"{got=}" assert (got := solve("10.0.0.1")) == "10[.]0[.]0[.]1", f"{got=}" assert (got := solve("172.16.254.1")) == "172[.]16[.]254[.]1", f"{got=}" assert (got := solve("8.8.8.8")) == "8[.]8[.]8[.]8", f"{got=}" ``` # [Number of 1 Bits](https://leetle.app/?date=2025-05-11) Write a function `solve` that returns the number of 1 bits in the binary representation of an unsigned integer. ## Solution ``` Python def solve(n): return n.bit_count() ``` ## Test Cases ``` Python assert (got := solve(11)) == 3, f"{got=}" assert (got := solve(128)) == 1, f"{got=}" assert (got := solve(0)) == 0, f"{got=}" assert (got := solve(4294967295)) == 32, f"{got=}" assert (got := solve(7)) == 3, f"{got=}" assert (got := solve(1)) == 1, f"{got=}" ``` # [Binary Tree Postorder Traversal](https://leetle.app/?date=2025-05-12) Write a function `solve` that returns the postorder traversal of a binary tree (left, right, root). ## Solution ``` Python def solve(root): if root is None: return [] return solve(root.left) + solve(root.right) + [root.val] ``` ## Test Cases ``` Python # Binary Tree Definition class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return None elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return None node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([1, None, 2, 3]))) == [3, 2, 1], f"{got=}" assert (got := solve(bt([]))) == [], f"{got=}" assert (got := solve(bt([1]))) == [1], f"{got=}" assert (got := solve(bt([1, 2, 3, 4, 5]))) == [4, 5, 2, 3, 1], f"{got=}" assert (got := solve(bt([3, 1, 2]))) == [1, 2, 3], f"{got=}" assert (got := solve(bt([5, 4, 6, 3]))) == [3, 4, 6, 5], f"{got=}" ``` # [House Robber](https://leetle.app/?date=2025-05-13) Write a function `solve` that finds the maximum amount of money that can be robbed from houses without robbing adjacent ones. The houses will be given as a list where the value you can steal is given as integers in the list. ## Solution ``` Python def solve(nums): if not nums: return 0 old, new = 0, nums[0] for i in range(1, len(nums)): old, new = new, max(nums[i] + old, new) return new ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 1])) == 4, f"{got=}" assert (got := solve([2, 7, 9, 3, 1])) == 12, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([1])) == 1, f"{got=}" assert (got := solve([2, 1, 1, 2])) == 4, f"{got=}" assert (got := solve([1, 3, 1])) == 3, f"{got=}" ``` # [In the Ocean](https://leetle.app/?date=2025-05-14) Write a function `solve` that checks if a given string is a valid oceanic coordinate. The coordinate is valid if it follows the format of a cardinal direction followed by a degree value, and it must be within the valid ranges for both latitude and longitude, which are between 0 and 90 degrees for latitude and 0 and 180 degrees for longitude. ## Solution ``` Python import re def solve(coord): c = re.match(r"[NS](\d+)[EW](\d+)", coord) if c and 0 <= int(c.groups()[0]) <= 90 and 0 <= int(c.groups()[1]) <= 180: return True return False ``` ## Test Cases ``` Python assert (got := solve("N45E90")) is True, f"{got=}" assert (got := solve("S30W120")) is True, f"{got=}" assert (got := solve("E90N45")) is False, f"{got=}" assert (got := solve("N0E0")) is True, f"{got=}" assert (got := solve("N100E200")) is False, f"{got=}" assert (got := solve("S45W90")) is True, f"{got=}" ``` # [Reverse Bits](https://leetle.app/?date=2025-05-15) Write a function `solve` that reverses the bits of a 32-bit unsigned integer. ## Solution ``` Python def solve(n): return int(f"{n:032b}"[::-1], 2) ``` ## Test Cases ``` Python assert (got := solve(43261596)) == 964176192, f"{got=}" assert (got := solve(0)) == 0, f"{got=}" assert (got := solve(4294967295)) == 4294967295, f"{got=}" assert (got := solve(1)) == 2147483648, f"{got=}" assert (got := solve(123456)) == 38240256, f"{got=}" assert (got := solve(2147483648)) == 1, f"{got=}" ``` # [Balling Ones](https://leetle.app/?date=2025-05-16) Write a function `solve` that counts the number of 1 bits in the binary representation of an integer. See [131 Number of 1 Bits](#numberof1bits). ## Solution ``` Python from number_of_1_bits_131 import solve ``` ## Test Cases ``` Python assert (got := solve(11)) == 3, f"{got=}" assert (got := solve(128)) == 1, f"{got=}" assert (got := solve(0)) == 0, f"{got=}" assert (got := solve(4294967295)) == 32, f"{got=}" assert (got := solve(7)) == 3, f"{got=}" assert (got := solve(1)) == 1, f"{got=}" ``` # [Delete Node in a Linked List](https://leetle.app/?date=2025-05-17) Write a function `solve` that deletes a given node (not the tail) from a singly linked list. Return the haed of the updated linked list. ## Solution ``` Python def solve(head, n): if head and head.val == n and not head.next: return node = head while node: if node.val == n: node.val, node.next = node.next.val, node.next.next return head node = node.next ``` ## Test Cases ``` Python # Singly Linked List Definition class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def sl(ls): if not ls: return None root = node = ListNode(ls[0]) for i in ls[1:]: node.next = ListNode(i) node = node.next return root def t(x): r = [] while x: r.append(x.val) x = x.next return r assert (got := t(solve(sl([4, 5, 1, 9]), 5))) == [4, 1, 9], f"{got=}" assert (got := t(solve(sl([4, 5, 1, 9]), 1))) == [4, 5, 9], f"{got=}" assert (got := t(solve(sl([1, 2, 3]), 2))) == [1, 3], f"{got=}" assert (got := t(solve(sl([0, 1]), 0))) == [1], f"{got=}" assert (got := t(solve(sl([1, 2, 3, 4]), 3))) == [1, 2, 4], f"{got=}" assert (got := t(solve(sl([7, 8, 9]), 8))) == [7, 9], f"{got=}" assert (got := t(solve(sl([0]), 0))) == [], f"{got=}" assert (got := t(solve(sl([0]), 1))) == [], f"{got=}" ``` # [Find the Index of the First Occurrence in a String](https://leetle.app/?date=2025-05-18) Write a function `solve` that returns the index of the first occurrence of a substring in a string, or -1 if not found. ## Solution ``` Python def solve(haystack, needle): return haystack.find(needle) ``` ## Test Cases ``` Python assert (got := solve("sadbutsad", "sad")) == 0, f"{got=}" assert (got := solve("leetcode", "leeto")) == -1, f"{got=}" assert (got := solve("", "")) == 0, f"{got=}" assert (got := solve("hello", "ll")) == 2, f"{got=}" assert (got := solve("aaaaa", "bba")) == -1, f"{got=}" assert (got := solve("abc", "c")) == 2, f"{got=}" ``` # [Sum Root to Leaf Numbers](https://leetle.app/?date=2025-05-19) Write a function `solve` that sums all numbers formed by root-to-leaf paths in a binary tree. ## Solution ``` Python def solve(root, res=0): if not root: return 0 res = res * 10 + root.val if not root.left and not root.right: return res return solve(root.left, res) + solve(root.right, res) ``` ## Test Cases ``` Python # Binary Tree Definition class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([1, 2, 3]))) == 25, f"{got=}" assert (got := solve(bt([4, 9, 0, 5, 1]))) == 1026, f"{got=}" assert (got := solve(bt([]))) == 0, f"{got=}" assert (got := solve(bt([1]))) == 1, f"{got=}" assert (got := solve(bt([1, 2]))) == 12, f"{got=}" assert (got := solve(bt([5, 1, None, 2]))) == 512, f"{got=}" ``` # [Digits Product](https://leetle.app/?date=2025-05-20) Write a function `solve` that returns the smallest number whose digits multiply to a given product, or -1 if impossible. ## Solution ``` Python def solve(product): if product == 0: return 10 if product < 10: return product result, pos = 0, 0 for d in range(9, 1, -1): while product % d == 0: result, product, pos = d * 10**pos + result, product // d, pos + 1 return -1 if product > 1 else result ``` ## Test Cases ``` Python assert (got := solve(12)) == 26, f"{got=}" assert (got := solve(0)) == 10, f"{got=}" assert (got := solve(1)) == 1, f"{got=}" assert (got := solve(19)) == -1, f"{got=}" assert (got := solve(13)) == -1, f"{got=}" assert (got := solve(450)) == 2559, f"{got=}" ``` # [Detect Capital](https://leetle.app/?date=2025-05-21) Write a function `solve` that checks if a word uses capitalization correctly (all uppercase, all lowercase, or only first letter uppercase). ## Solution ``` Python def solve(word): return word.isupper() or word.islower() or word == word.capitalize() ``` ## Test Cases ``` Python assert (got := solve("USA")) is True, f"{got=}" assert (got := solve("leetle")) is True, f"{got=}" assert (got := solve("Google")) is True, f"{got=}" assert (got := solve("FlaG")) is False, f"{got=}" assert (got := solve("I")) is True, f"{got=}" assert (got := solve("mL")) is False, f"{got=}" ``` # [Odd Even Linked List](https://leetle.app/?date=2025-05-22) Write a function `solve` that groups all odd-indexed nodes followed by even-indexed nodes in a linked list (1-based indexing). ## Solution ``` Python def solve(head): if not head: return odd = head even = even_head = head.next while even and even.next: odd.next = even.next odd = odd.next even.next = odd.next even = even.next odd.next = even_head return head ``` ## Test Cases ``` Python # Singly Linked List Definition class ListNode: def __init__(self, val=0, next=None): self.val = val self.next = next def sl(ls): if not ls: return None root = node = ListNode(ls[0]) for i in ls[1:]: node.next = ListNode(i) node = node.next return root def t(x): r = [] while x: r.append(x.val) x = x.next return r assert (got := t(solve(sl([1, 2, 3, 4, 5])))) == [1, 3, 5, 2, 4], f"{got=}" assert (got := t(solve(sl([2, 1, 3, 5, 6, 4, 7])))) == [ 2, 3, 6, 7, 1, 5, 4, ], f"{got=}" assert (got := t(solve(sl([])))) == [], f"{got=}" assert (got := t(solve(sl([1])))) == [1], f"{got=}" assert (got := t(solve(sl([1, 2])))) == [1, 2], f"{got=}" assert (got := t(solve(sl([1, 2, 3])))) == [1, 3, 2], f"{got=}" ``` # [Baseball Game](https://leetle.app/?date=2025-05-23) Write a function `solve` that calculates the total score of a baseball game given operations (integer, +, D, C). An integer n means you record the score. + means record the sum of the last two scores, D means record the double of the last score, and C means cancel the last score. Finally, you should sum the scores. ## Solution ``` Python def solve(operations): scores = [] for op in operations: match op: case "+": scores.append(scores[-1] + scores[-2]) case "C": scores.pop() case "D": scores.append(scores[-1] * 2) case _: scores.append(int(op)) return sum(scores) ``` ## Test Cases ``` Python assert (got := solve(["5", "2", "C", "D", "+"])) == 30, f"{got=}" assert (got := solve(["5", "-2", "4", "C", "D", "9", "+", "+"])) == 27, f"{got=}" assert (got := solve(["1"])) == 1, f"{got=}" assert (got := solve(["1", "C"])) == 0, f"{got=}" assert (got := solve(["5", "D"])) == 15, f"{got=}" assert (got := solve(["2", "3", "+"])) == 10, f"{got=}" ``` # [Shuffle Array](https://leetle.app/?date=2025-05-24) Write a function `solve` that shuffles an array by interleaving its first n elements with its last n elements. ## Solution ``` Python def solve(nums, n): return [i for t in zip(nums[:n], nums[n:]) for i in t] ``` ## Test Cases ``` Python assert (got := solve([2, 5, 1, 3, 4, 7], 3)) == [2, 3, 5, 4, 1, 7], f"{got=}" assert (got := solve([1, 2, 3, 4], 2)) == [1, 3, 2, 4], f"{got=}" assert (got := solve([1, 1, 2, 2], 2)) == [1, 2, 1, 2], f"{got=}" assert (got := solve([1, 2], 1)) == [1, 2], f"{got=}" assert (got := solve([5, 6, 7, 8, 9, 10], 3)) == [5, 8, 6, 9, 7, 10], f"{got=}" assert (got := solve([1, 3, 5, 7], 2)) == [1, 5, 3, 7], f"{got=}" ``` # [Valid Perfect Square](https://leetle.app/?date=2025-05-25) Write a function `solve` that determines if a given number is a perfect square without using any built-in square root functions. ## Solution ``` Python def solve(num): if num <= 1: return False if num < 0 else True low, high = 1, num // 2 while low <= high: middle = (high - low) // 2 + low if (square := middle * middle) == num: return True low, high = (middle + 1, high) if square < num else (low, middle - 1) return False ``` ## Test Cases ``` Python assert (got := solve(16)) is True, f"{got=}" assert (got := solve(14)) is False, f"{got=}" assert (got := solve(1)) is True, f"{got=}" assert (got := solve(0)) is True, f"{got=}" assert (got := solve(2147483647)) is False, f"{got=}" assert (got := solve(808201)) is True, f"{got=}" assert (got := solve(-808201)) is False, f"{got=}" ``` # [Longest Increasing Subsequence](https://leetle.app/?date=2025-05-26) Write a function `solve` that finds the length of the longest strictly increasing subsequence in an array of integers. ## Solution ``` Python def solve(nums): n, ans = len(nums), [] for i in range(n): if not ans or nums[i] > ans[-1]: ans.append(nums[i]) else: low, high = 0, len(ans) - 1 while low < high: mid = low + (high - low) // 2 low, high = (mid + 1, high) if ans[mid] < nums[i] else (low, mid) ans[low] = nums[i] return len(ans) ``` ## Test Cases ``` Python assert (got := solve([10, 9, 2, 5, 3, 7, 101, 18])) == 4, f"{got=}" assert (got := solve([0, 1, 0, 3, 2, 3])) == 4, f"{got=}" assert (got := solve([7, 7, 7, 7, 7, 7, 7])) == 1, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([1])) == 1, f"{got=}" assert (got := solve([4, 10, 4, 3, 8, 9])) == 3, f"{got=}" ``` # [Subarray Sum Equals K](https://leetle.app/?date=2025-05-27) Write a function `solve` that finds the total number of subarrays whose sum equals k. ## Solution ``` Python def solve(nums, k): prefix_sums, running, total = {0: 1}, 0, 0 for num in nums: running += num if running - k in prefix_sums: total += prefix_sums[running - k] prefix_sums[running] = prefix_sums.get(running, 0) + 1 return total ``` ## Test Cases ``` Python assert (got := solve([1, 1, 1], 2)) == 2, f"{got=}" assert (got := solve([1, 2, 3], 3)) == 2, f"{got=}" assert (got := solve([1], 0)) == 0, f"{got=}" assert (got := solve([1, -1, 0], 0)) == 3, f"{got=}" assert (got := solve([3, 4, 7, 2, -3, 1, 4, 2], 7)) == 4, f"{got=}" assert (got := solve([], 5)) == 0, f"{got=}" ``` # [Number of Islands](https://leetle.app/?date=2025-05-28) Given an m x n 2D binary grid which represents a map of '1's (land) and '0's (water), return the number of islands. An island is surrounded by water and is formed by connecting adjacent lands horizontally or vertically. You may assume all four edges of the grid are all surrounded by water. ## Solution ``` Python def solve(grid): def dfs(r, c): if 0 <= r < rows and 0 <= c < cols and grid[r][c] == "1": grid[r][c] = "0" for dr, dc in directions: dfs(r + dr, c + dc) result, directions = 0, [(0, 1), (0, -1), (1, 0), (-1, 0)] rows, cols = len(grid), len(grid[0]) for r in range(rows): for c in range(cols): if grid[r][c] == "1": result += 1 dfs(r, c) return result ``` ## Test Cases ``` Python assert ( got := solve( [ ["1", "1", "1", "1", "0"], ["1", "1", "0", "1", "0"], ["1", "1", "0", "0", "0"], ["0", "0", "0", "0", "0"], ] ) ) == 1, f"{got=}" assert ( got := solve( [ ["1", "1", "0", "0", "0"], ["1", "1", "0", "0", "0"], ["0", "0", "1", "0", "0"], ["0", "0", "0", "1", "1"], ] ) ) == 3, f"{got=}" assert (got := solve([[]])) == 0, f"{got=}" assert (got := solve([["1"]])) == 1, f"{got=}" assert (got := solve([["0"]])) == 0, f"{got=}" assert ( got := solve( [ ["0", "0", "1", "0", "1", "1"], ["1", "1", "0", "0", "0", "1"], ["0", "1", "0", "1", "1", "0"], ["0", "1", "1", "0", "0", "0"], ["1", "0", "1", "0", "1", "1"], ["1", "0", "1", "0", "1", "0"], ] ) ) == 6, f"{got=}" ``` # [Word Ladder](https://leetle.app/?date=2025-05-29) Write a function `solve` that takes two words, begin_word and end_word, and a list of words word_list. The function should return the length of the shortest transformation sequence from begin_word to end_word where each transformation changes exactly one letter. If no such transformation sequence exists, return 0. ## Solution ``` Python from collections import defaultdict, deque def solve(begin_word, end_word, word_list): length, patterns = 1, defaultdict(list) seen, queue = set([begin_word]), deque([begin_word]) for word in [begin_word] + word_list: for i in range(len(word)): patterns[word[:i] + "." + word[i + 1 :]].append(word) while queue: for _ in range(len(queue)): word = queue.popleft() if word == end_word: return length for i in range(len(word)): for pattern in patterns[word[:i] + "." + word[i + 1 :]]: if pattern not in seen: seen.add(pattern) queue.append(pattern) length = length + 1 return 0 ``` ## Test Cases ``` Python assert (got := solve("hit", "cog", ["hot", "dot", "dog", "lot", "log", "cog"])) == 5, ( f"{got=}" ) assert (got := solve("hit", "cog", ["hot", "dot", "dog", "lot", "log"])) == 0, f"{got=}" assert (got := solve("a", "c", ["a", "b", "c"])) == 2, f"{got=}" assert (got := solve("hot", "dog", ["hot", "dog"])) == 0, f"{got=}" assert (got := solve("hit", "hit", ["hit"])) == 1, f"{got=}" assert ( got := solve("red", "tax", ["ted", "tex", "red", "tax", "tad", "den", "rex", "pee"]) ) == 4, f"{got=}" ``` # [Course Schedule](https://leetle.app/?date=2025-05-30) Write a function `solve` that takes the number of courses num_courses and an array of prerequisites prerequisites where prerequisites[i] = [a, b] indicates that you must take course b before taking course a. Return true if you can finish all courses, otherwise return false. ## Solution ``` Python from collections import defaultdict, deque def solve(num_courses, prerequisites): graph, pre = defaultdict(list), [0] * num_courses for c, p in prerequisites: graph[p].append(c) pre[c] += 1 todo, done = deque(i for i in pre if i == 0), 0 while todo: done += 1 for i in graph[todo.popleft()]: pre[i] -= 1 if pre[i] == 0: todo.append(i) return done == num_courses ``` ## Test Cases ``` Python assert (got := solve(2, [[1, 0]])) is True, f"{got=}" assert (got := solve(2, [[1, 0], [0, 1]])) is False, f"{got=}" assert (got := solve(3, [[1, 0], [2, 1]])) is True, f"{got=}" assert (got := solve(4, [[1, 0], [2, 0], [3, 1], [3, 2]])) is True, f"{got=}" assert (got := solve(3, [[0, 1], [0, 2], [1, 2], [2, 0]])) is False, f"{got=}" assert (got := solve(1, [])) is True, f"{got=}" ``` # [Find All Permutations of a String](https://leetle.app/?date=2025-05-31) Write a function `solve` that returns all possible permutations of a string with unique characters. The permutations can be returned in any order. ## Solution ``` Python from itertools import permutations def solve(s): return ["".join(i) for i in permutations(s)] ``` ## Test Cases ``` Python assert (got := solve("abc")) == [ "abc", "acb", "bac", "bca", "cab", "cba", ], f"{got=}" assert (got := solve("a")) == ["a"], f"{got=}" assert (got := solve("ab")) == ["ab", "ba"], f"{got=}" assert (got := solve("")) == [""], f"{got=}" assert (got := solve("xyz")) == [ "xyz", "xzy", "yxz", "yzx", "zxy", "zyx", ], f"{got=}" assert (got := solve("123")) == [ "123", "132", "213", "231", "312", "321", ], f"{got=}" ``` # [Longest Palindromic Subsequence](https://leetle.app/?date=2025-06-01) Write a function `solve` that finds the length of the longest palindromic subsequence in a string. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order of the remaining elements. ## Solution ``` Python def solve(s): cur, pre = [0] * (n := len(s)), [0] * n for i in range(n - 1, -1, -1): cur[i] = 1 for j in range(i + 1, n): cur[j] = pre[j - 1] + 2 if s[i] == s[j] else max(pre[j], cur[j - 1]) pre = cur[:] return cur[n - 1] if n else 0 ``` ## Test Cases ``` Python assert (got := solve("bbbab")) == 4, f"{got=}" assert (got := solve("cbbd")) == 2, f"{got=}" assert (got := solve("a")) == 1, f"{got=}" assert (got := solve("abcdefgfedcba")) == 13, f"{got=}" assert (got := solve("")) == 0, f"{got=}" assert (got := solve("aabaa")) == 5, f"{got=}" ``` # [Find the Celebrity](https://leetle.app/?date=2025-06-02) Write a function `solve` that finds the celebrity in a party of n people labeled from 0 to n-1. A celebrity is someone who is known by everyone but doesn't know anyone. You are given a helper function `knows(a, b)` which returns true if person a knows person b, and false otherwise. Your function should return the celebrity's label if there is exactly one celebrity, or -1 if there is no celebrity. ## Solution ``` Python def solve(knows_data, n): # knows_data is a list of [a, b, result] where result is True if a knows b # This is a simulation of the knows() API - in a real interview, you'd have # a knows(a, b) function knows_dict = {(a, b): result for a, b, result in knows_data} def knows(a, b): return knows_dict.get((a, b), False) # Your solution here return { 0: i for i in range(n) if sum(knows(j, i) for j in range(n)) == n - 1 and sum(knows(i, j) for j in range(n)) == 0 }.get(0, -1) ``` ## Test Cases ``` Python assert ( got := solve( [ [0, 1, True], [0, 2, True], [1, 0, False], [1, 2, True], [2, 0, False], [2, 1, False], ], 3, ) ) == 2, f"{got=}" assert (got := solve([[0, 1, True], [1, 0, True]], 2)) == -1, f"{got=}" assert ( got := solve( [ [0, 1, True], [1, 0, True], [1, 2, True], [2, 1, True], [0, 2, False], [2, 0, False], ], 3, ) ) == -1, f"{got=}" assert ( got := solve( [ [0, 1, True], [0, 2, True], [0, 3, True], [1, 0, False], [1, 2, True], [1, 3, True], [2, 0, False], [2, 1, False], [2, 3, False], [3, 0, False], [3, 1, False], [3, 2, True], ], 4, ) ) == 2, f"{got=}" assert (got := solve([], 1)) == 0, f"{got=}" assert ( got := solve( [ [0, 1, True], [0, 2, True], [0, 3, True], [1, 0, False], [1, 2, True], [1, 3, True], [2, 0, False], [2, 1, False], [2, 3, True], [3, 0, False], [3, 1, False], [3, 2, False], ], 4, ) ) == 3, f"{got=}" ``` # [Product of Array Except Self](https://leetle.app/?date=2025-06-03) Write a function `solve` that takes an array nums of n integers and returns an array output such that output[i] is equal to the product of all the elements of nums except nums[i]. Solve it without using division. ## Solution ``` Python def solve(nums): pre, suf = [1] * (n := len(nums)), [1] * n for i in range(1, n): pre[i] = nums[i - 1] * pre[i - 1] for i in range(n - 2, -1, -1): suf[i] = nums[i + 1] * suf[i + 1] return [pre[i] * suf[i] for i in range(n)] ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 4])) == [24, 12, 8, 6], f"{got=}" assert (got := solve([0, 0])) == [0, 0], f"{got=}" assert (got := solve([1, 0])) == [0, 1], f"{got=}" assert (got := solve([1, 2])) == [2, 1], f"{got=}" assert (got := solve([5, 9, 2, 10, 1, 3])) == [ 540, 300, 1350, 270, 2700, 900, ], f"{got=}" assert (got := solve([0, 1, 2, 0])) == [0, 0, 0, 0], f"{got=}" ``` # [Decode Ways](https://leetle.app/?date=2025-06-04) Write a function `solve` that determines the number of ways to decode a string of digits. A message containing letters from A-Z can be encoded into numbers by mapping A to 1, B to 2, ..., Z to 26. For example, the message 'ABC' would be encoded as '123'. Given a string of digits, return the number of ways to decode it. ## Solution ``` Python def solve(s): prev, curr = 0, 1 for i in range(len(s)): next = 0 if s[i] != "0": next = curr if i > 0 and s[i - 1] in "12" and s[i] < "7": next += prev prev, curr = curr, next return curr ``` ## Test Cases ``` Python assert (got := solve("12")) == 2, f"{got=}" assert (got := solve("226")) == 3, f"{got=}" assert (got := solve("0")) == 0, f"{got=}" assert (got := solve("06")) == 0, f"{got=}" assert (got := solve("10")) == 1, f"{got=}" assert (got := solve("2101")) == 1, f"{got=}" ``` # [Find the Second Largest Number](https://leetle.app/?date=2025-06-05) Write a function `solve` that returns the second largest number in a list of integers. If the list has fewer than two unique numbers, return `None`. ## Solution ``` Python def solve(nums): return dict(enumerate(sorted(set(nums))[:-3:-1])).get(1) ``` ## Test Cases ``` Python assert (got := solve([3, 1, 4, 1, 5, 9])) == 5, f"{got=}" assert (got := solve([1, 1, 1])) is None, f"{got=}" assert (got := solve([2, 2, 3])) == 2, f"{got=}" assert (got := solve([10])) is None, f"{got=}" assert (got := solve([7, 7, 8, 8, 9])) == 8, f"{got=}" assert (got := solve([5, 4])) == 4, f"{got=}" ``` # [Check Number Sign](https://leetle.app/?date=2025-06-06) Write a function `solve` that takes an integer `n` and returns the string "positive" if n is greater than 0, "negative" if n is less than 0, and "zero" if n is equal to 0. ## Solution ``` Python def solve(n): return "negative" if n < 0 else ("positive" if n > 0 else "zero") ``` ## Test Cases ``` Python assert (got := solve(5)) == "positive", f"{got=}" assert (got := solve(-3)) == "negative", f"{got=}" assert (got := solve(0)) == "zero", f"{got=}" assert (got := solve(100)) == "positive", f"{got=}" assert (got := solve(-1000)) == "negative", f"{got=}" assert (got := solve(1)) == "positive", f"{got=}" ``` # [Find the Missing Letter](https://leetle.app/?date=2025-06-07) Write a function `solve` that takes a list of consecutive letters (increasing order, one missing) and returns the missing letter. The input will always be a list of single-character strings with exactly one letter missing. ## Solution ``` Python def solve(ls): return ({chr(ord(ls[0]) + i) for i in range(len(ls))} - set(ls)).pop() ``` ## Test Cases ``` Python assert (got := solve(["a", "b", "c", "e"])) == "d", f"{got=}" assert (got := solve(["O", "P", "Q", "S"])) == "R", f"{got=}" assert (got := solve(["s", "t", "v"])) == "u", f"{got=}" assert (got := solve(["m", "n", "p"])) == "o", f"{got=}" assert (got := solve(["A", "B", "D"])) == "C", f"{got=}" assert (got := solve(["g", "h", "j"])) == "i", f"{got=}" ``` # [Sum of Digits Until One Digit](https://leetle.app/?date=2025-06-08) Write a function `solve` that repeatedly adds all the digits of a non-negative integer until the result has only one digit, and returns that digit. See [123 Sum of Digits Until One Digit](#sumofdigitsuntilonedigit). ## Solution ``` Python from sum_of_digits_until_one_digit_123 import solve ``` ## Test Cases ``` Python assert (got := solve(38)) == 2, f"{got=}" assert (got := solve(0)) == 0, f"{got=}" assert (got := solve(12345)) == 6, f"{got=}" assert (got := solve(9)) == 9, f"{got=}" assert (got := solve(99)) == 9, f"{got=}" assert (got := solve(1001)) == 2, f"{got=}" ``` # [Find the Intersection Point](https://leetle.app/?date=2025-06-09) Write a function `solve` that takes two lists and returns a list of elements that appear in both lists, in the order they appear in the first list. Each element should appear only once in the result. ## Solution ``` Python def solve(list1, list2): return list({i: None for i in list1 if i in set(list2)}) ``` ## Test Cases ``` Python assert (got := solve([1, 2, 2, 3], [2, 3, 4])) == [2, 3], f"{got=}" assert (got := solve([5, 6, 7], [7, 8, 9])) == [7], f"{got=}" assert (got := solve([1, 2, 3], [4, 5, 6])) == [], f"{got=}" assert (got := solve([1, 1, 1], [1])) == [1], f"{got=}" assert (got := solve([1, 2, 3, 4], [2, 4, 6, 8])) == [2, 4], f"{got=}" assert (got := solve([10, 20, 30], [30, 10, 20])) == [10, 20, 30], f"{got=}" ``` # [Valid Mountain Array](https://leetle.app/?date=2025-06-10) Write a function `solve` that determines if an array is a valid mountain array. A valid mountain array has the following properties: - Length of at least 3 elements - Elements first strictly increase, then strictly decrease - There must be at least one element in both increasing and decreasing parts ## Solution ``` Python def solve(arr): if (n := len(arr)) < 3: return False left, right = 0, n - 1 while left + 1 < n - 1 and arr[left] < arr[left + 1]: left += 1 while right - 1 > 0 and arr[right] < arr[right - 1]: right -= 1 return left == right ``` ## Test Cases ``` Python assert (got := solve([0, 3, 2, 1])) is True, f"{got=}" assert (got := solve([3, 5, 5])) is False, f"{got=}" assert (got := solve([0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0])) is True, f"{got=}" assert (got := solve([1, 2, 3])) is False, f"{got=}" assert (got := solve([3, 2, 1])) is False, f"{got=}" assert (got := solve([1, 2])) is False, f"{got=}" ``` # [Find Target in Rotated Sorted Array](https://leetle.app/?date=2025-06-11) Write a function `solve` that searches for a target value in a rotated sorted array. The array was originally sorted in ascending order, then rotated at some pivot. Return the index if found, otherwise return -1. ## Solution ``` Python def solve(nums, target): left, right = 0, len(nums) - 1 while left < right: mid = (left + right) // 2 if nums[0] <= nums[mid]: if nums[0] <= target <= nums[mid]: right = mid else: left = mid + 1 else: if nums[mid] < target <= nums[-1]: left = mid + 1 else: right = mid return left if nums[left] == target else -1 ``` ## Test Cases ``` Python assert (got := solve([4, 5, 6, 7, 0, 1, 2], 0)) == 4, f"{got=}" assert (got := solve([4, 5, 6, 7, 0, 1, 2], 3)) == -1, f"{got=}" assert (got := solve([1], 0)) == -1, f"{got=}" assert (got := solve([1], 1)) == 0, f"{got=}" assert (got := solve([1, 3, 5], 3)) == 1, f"{got=}" assert (got := solve([3, 1], 1)) == 1, f"{got=}" ``` # [Longest Substring with At Most K Distinct Characters](https://leetle.app/?date=2025-06-12) Write a function `solve` that finds the length of the longest substring that contains at most k distinct characters. ## Solution ``` Python def solve(s, k): cs, r, x = {}, 0, 0 for i, c in enumerate(s): cs[c] = cs.get(c, 0) + 1 while len(cs) > k: cs[s[x]] = cs.get(s[x], 0) - 1 if cs[s[x]] == 0: del cs[s[x]] x += 1 r = max(r, i - x + 1) return r ``` ## Test Cases ``` Python assert (got := solve("eceba", 2)) == 3, f"{got=}" assert (got := solve("aa", 1)) == 2, f"{got=}" assert (got := solve("abcdef", 3)) == 3, f"{got=}" assert (got := solve("a", 2)) == 1, f"{got=}" assert (got := solve("", 1)) == 0, f"{got=}" assert (got := solve("abcabc", 2)) == 2, f"{got=}" ``` # [Design Phone Directory](https://leetle.app/?date=2025-06-13) Write a function `solve` that simulates a phone directory with operations: get next available number, check if number is available, and release a number. Given a list of operations, return the results. Operations: ["get", "check", "release"] ## Solution ``` Python def solve(n, operations): results, numbers = [], list(range(n - 1, -1, -1)) for op in operations: match op: case ["get"]: results.append(numbers.pop() if numbers else -1) case ["check", x]: results.append(x in numbers) case ["release", x]: results.append(numbers.append(x) if x not in numbers else None) return results ``` ## Test Cases ``` Python assert ( got := solve( 3, [ ["get"], ["get"], ["check", 2], ["get"], ["check", 2], ["release", 2], ["check", 2], ], ) ) == [0, 1, True, 2, False, None, True], f"{got=}" assert (got := solve(1, [["get"], ["get"], ["release", 0], ["get"]])) == [ 0, -1, None, 0, ], f"{got=}" assert (got := solve(2, [["check", 0], ["get"], ["check", 0], ["release", 0]])) == [ True, 0, False, None, ], f"{got=}" assert (got := solve(1, [["check", 0], ["check", 1]])) == [ True, False, ], f"{got=}" assert (got := solve(5, [["get"], ["get"], ["get"], ["get"], ["get"], ["get"]])) == [ 0, 1, 2, 3, 4, -1, ], f"{got=}" assert (got := solve(2, [["release", 0], ["get"], ["get"], ["get"]])) == [ None, 0, 1, -1, ], f"{got=}" ``` # [Meeting Rooms](https://leetle.app/?date=2025-06-14) Write a function `solve` that determines if a person can attend all meetings given their time intervals. Each interval is [start_time, end_time]. ## Solution ``` Python def solve(intervals): intervals.sort() for i in range(len(intervals) - 1): if intervals[i][1] > intervals[i + 1][0]: return False return True ``` ## Test Cases ``` Python assert (got := solve([[0, 30], [5, 10], [15, 20]])) is False, f"{got=}" assert (got := solve([[7, 10], [2, 4]])) is True, f"{got=}" assert (got := solve([])) is True, f"{got=}" assert (got := solve([[1, 5]])) is True, f"{got=}" assert (got := solve([[1, 4], [4, 5]])) is True, f"{got=}" assert (got := solve([[1, 4], [2, 3]])) is False, f"{got=}" ``` # [Shortest Word Distance](https://leetle.app/?date=2025-06-15) Write a function `solve` that finds the shortest distance between two words in a list of words. Distance is the absolute difference between their indices. ## Solution ``` Python def solve(word1, word2, words): index1 = index2 = -1 shortest_distance = float("inf") for index, word in enumerate(words): if word == word1: index1 = index if word == word2: index2 = index if index1 != -1 and index2 != -1: distance = abs(index1 - index2) shortest_distance = min(shortest_distance, distance) return shortest_distance ``` ## Test Cases ``` Python assert ( got := solve( "coding", "practice", ["practice", "makes", "perfect", "coding", "makes"], ) ) == 3, f"{got=}" assert ( got := solve("makes", "coding", ["practice", "makes", "perfect", "coding", "makes"]) ) == 1, f"{got=}" assert (got := solve("a", "c", ["a", "b", "c"])) == 2, f"{got=}" assert (got := solve("a", "b", ["a", "c", "b", "a"])) == 1, f"{got=}" assert (got := solve("practice", "perfect", ["practice", "makes", "perfect"])) == 2, ( f"{got=}" ) assert (got := solve("hello", "world", ["hello", "world", "hello"])) == 1, f"{got=}" ``` # [Palindromic Substrings](https://leetle.app/?date=2025-06-16) Write a function `solve` that counts the number of palindromic substrings in a string. A substring is palindromic if it reads the same backward as forward. ## Solution ``` Python def solve(s): n, r = len(s), 0 for i in range(n): b, a = i, i + 1 while b >= 0 and a < n and s[b] == s[a]: r, b, a = r + 1, b - 1, a + 1 for i in range(n): b, a = i - 1, i + 1 while b >= 0 and a < n and s[b] == s[a]: r, b, a = r + 1, b - 1, a + 1 return n + r ``` ## Test Cases ``` Python assert (got := solve("abc")) == 3, f"{got=}" assert (got := solve("aaa")) == 6, f"{got=}" assert (got := solve("racecar")) == 10, f"{got=}" assert (got := solve("a")) == 1, f"{got=}" assert (got := solve("")) == 0, f"{got=}" assert (got := solve("abccba")) == 9, f"{got=}" ``` # [Largest Rectangle in Histogram](https://leetle.app/?date=2025-06-17) Write a function `solve` that finds the area of the largest rectangle that can be formed in a histogram represented by an array of heights. ## Solution ``` Python def solve(heights): n, s, r = len(heights), [], 0 for i in range(n): while s and heights[s[-1]] >= heights[i]: r = max(r, heights[s.pop()] * (i if not s else i - s[-1] - 1)) s.append(i) while s: r = max(r, heights[s.pop()] * (n if not s else n - s[-1] - 1)) return r ``` ## Test Cases ``` Python assert (got := solve([2, 1, 5, 6, 2, 3])) == 10, f"{got=}" assert (got := solve([2, 4])) == 4, f"{got=}" assert (got := solve([1, 1, 1, 1])) == 4, f"{got=}" assert (got := solve([5, 4, 3, 2, 1])) == 9, f"{got=}" assert (got := solve([1, 2, 3, 4, 5])) == 9, f"{got=}" assert (got := solve([6, 2, 5, 4, 5, 1, 6])) == 12, f"{got=}" ``` # [Word Pattern](https://leetle.app/?date=2025-06-18) Write a function `solve` that determines if a string follows a given pattern. Each letter in the pattern corresponds to exactly one unique word in the string. ## Solution ``` Python def solve(pattern, s): return ( len(set(pattern)) == len(set(ss := s.split())) and " ".join(dict(zip(pattern, ss))[i] for i in pattern) == s ) ``` ## Test Cases ``` Python assert (got := solve("abba", "dog cat cat dog")) is True, f"{got=}" assert (got := solve("abba", "dog cat cat fish")) is False, f"{got=}" assert (got := solve("aaaa", "dog cat cat dog")) is False, f"{got=}" assert (got := solve("abba", "dog dog dog dog")) is False, f"{got=}" assert (got := solve("abc", "dog cat fish")) is True, f"{got=}" assert (got := solve("a", "hello")) is True, f"{got=}" ``` # [Binary Tree Maximum Path Sum](https://leetle.app/?date=2025-06-19) Write a function `solve` that finds the maximum sum of any path in a binary tree. A path is defined as any sequence of nodes from some starting node to any node in the tree along the parent-child connections. ## Solution ``` Python def solve(root): def traverse(node): nonlocal res if node is None: return 0 left, right = max(0, traverse(node.left)), max(0, traverse(node.right)) res = max(res, left + right + node.val) return node.val + max(left, right) res = root.val traverse(root) return res ``` ## Test Cases ``` Python # Binary Tree Definition class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return None elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return None node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([1, 2, 3]))) == 6, f"{got=}" assert (got := solve(bt([-10, 9, 20, None, None, 15, 7]))) == 42, f"{got=}" assert (got := solve(bt([5]))) == 5, f"{got=}" assert (got := solve(bt([-3]))) == -3, f"{got=}" assert (got := solve(bt([1, -2, -3, 1, 3, -2, None, -1]))) == 3, f"{got=}" assert (got := solve(bt([2, -1, -2]))) == 2, f"{got=}" ``` # [Count Character Types](https://leetle.app/?date=2025-06-20) Write a function `solve` that counts different types of characters in a string. Return a dictionary/object with counts for: vowels, consonants, digits, and spaces. Note: Vowels are a, e, i, o, u (case insensitive). ## Solution ``` Python def solve(s): d = dict(vowels=0, consonants=0, digits=0, spaces=0) for c in s: if c.lower() in "aeiou": d["vowels"] += 1 elif c.isalpha(): d["consonants"] += 1 elif c.isdecimal(): d["digits"] += 1 else: d["spaces"] += 1 return d ``` ## Test Cases ``` Python assert (got := solve("Hello World 123")) == { "vowels": 3, "consonants": 7, "digits": 3, "spaces": 2, }, f"{got=}" assert (got := solve("")) == { "consonants": 0, "digits": 0, "spaces": 0, "vowels": 0, }, f"{got=}" assert (got := solve("AEIOU")) == { "consonants": 0, "digits": 0, "spaces": 0, "vowels": 5, }, f"{got=}" assert (got := solve("bcdfg")) == { "consonants": 5, "digits": 0, "spaces": 0, "vowels": 0, }, f"{got=}" assert (got := solve("12345")) == { "consonants": 0, "digits": 5, "spaces": 0, "vowels": 0, }, f"{got=}" assert (got := solve(" ")) == { "consonants": 0, "digits": 0, "spaces": 3, "vowels": 0, }, f"{got=}" ``` # [Remove Elements from Array](https://leetle.app/?date=2025-06-21) Write a function `solve` that removes all instances of a given value from an array and returns the modified array. ## Solution ``` Python def solve(nums, val): return [i for i in nums if i != val] ``` ## Test Cases ``` Python assert (got := solve([3, 2, 2, 3], 3)) == [2, 2], f"{got=}" assert (got := solve([0, 1, 2, 2, 3, 0, 4, 2], 2)) == [ 0, 1, 3, 0, 4, ], f"{got=}" assert (got := solve([], 1)) == [], f"{got=}" assert (got := solve([1, 1, 1], 1)) == [], f"{got=}" assert (got := solve([1, 2, 3], 4)) == [1, 2, 3], f"{got=}" assert (got := solve([5], 5)) == [], f"{got=}" ``` # [Check if Array is Arithmetic Progression](https://leetle.app/?date=2025-06-22) Write a function `solve` that checks if an array can be rearranged to form an arithmetic progression. An arithmetic progression is a sequence where the difference between consecutive terms is constant. ## Solution ``` Python def solve(arr): if len(arr) > 2: arr.sort() delta = arr[1] - arr[0] for i in range(1, len(arr) - 1): if arr[i + 1] != arr[i] + delta: return False return True ``` ## Test Cases ``` Python assert (got := solve([3, 5, 1])) is True, f"{got=}" assert (got := solve([1, 2, 4])) is False, f"{got=}" assert (got := solve([1, 1, 1])) is True, f"{got=}" assert (got := solve([0])) is True, f"{got=}" assert (got := solve([5, 1, 3])) is True, f"{got=}" assert (got := solve([2, 4, 6, 8])) is True, f"{got=}" ``` # [Valid Phone Number](https://leetle.app/?date=2025-06-23) Write a function `solve` that validates if a string is a valid US phone number. Valid formats are: - (123) 456-7890 - 123-456-7890 - 123.456.7890 - 1234567890 ## Solution ``` Python def solve(phone): return len([i for i in phone if i.isdecimal()]) == 10 ``` ## Test Cases ``` Python assert (got := solve("(123) 456-7890")) is True, f"{got=}" assert (got := solve("123-456-7890")) is True, f"{got=}" assert (got := solve("123.456.7890")) is True, f"{got=}" assert (got := solve("1234567890")) is True, f"{got=}" assert (got := solve("123-45-6789")) is False, f"{got=}" assert (got := solve("12345")) is False, f"{got=}" ``` # [Calculate Median of Array](https://leetle.app/?date=2025-06-24) Write a function `solve` that calculates the median of an array of numbers. The median is the middle value when numbers are sorted. For even-length arrays, return the average of the two middle values. ## Solution ``` Python from statistics import median as solve ``` ## Test Cases ``` Python assert (got := solve([3, 1, 2])) == 2, f"{got=}" assert (got := solve([1, 2, 3, 4])) == 2.5, f"{got=}" assert (got := solve([5])) == 5, f"{got=}" assert (got := solve([1, 2])) == 1.5, f"{got=}" assert (got := solve([7, 9, 3, 5])) == 6, f"{got=}" assert (got := solve([10, 20, 30, 40, 50])) == 30, f"{got=}" ``` # [Check if Binary Tree is Symmetric](https://leetle.app/?date=2025-06-25) Write a function `solve` that checks if a binary tree is symmetric around its center. The tree is represented as a list where None represents a missing node. ## Solution ``` Python def solve(root): def is_symmetric(left, right): if not left and not right: return True if not left or not right or left.val != right.val: return False return is_symmetric(left.left, right.right) and is_symmetric( left.right, right.left ) return not root or is_symmetric(root.left, root.right) ``` ## Test Cases ``` Python # Binary Tree Definition class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return None elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return None node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([1, 2, 2, 3, 4, 4, 3]))) is True, f"{got=}" assert (got := solve(bt([1, 2, 2, None, 3, None, 3]))) is False, f"{got=}" assert (got := solve(bt([1]))) is True, f"{got=}" assert (got := solve(bt([]))) is True, f"{got=}" assert (got := solve(bt([1, 2, 3]))) is False, f"{got=}" assert (got := solve(bt([1, 2, 2]))) is True, f"{got=}" ``` # [Implement Stack Using Queues](https://leetle.app/?date=2025-06-26) Write a function `solve` that simulates stack operations using queue operations. Given a list of operations, return the results. Operations are: - ["push", x]: Push x to stack - ["pop"]: Remove and return top element - ["top"]: Return top element without removing - ["empty"]: Return true if stack is empty ## Solution ``` Python def solve(operations): results, queue = [], [] for op in operations: match op: case ["push", x]: results.append(queue.append(x)) case ["pop"]: results.append(queue.pop()) case ["top"]: results.append(queue[-1]) case ["empty"]: results.append(not queue) return results ``` ## Test Cases ``` Python assert (got := solve([["push", 1], ["push", 2], ["top"], ["pop"], ["empty"]])) == [ None, None, 2, 2, False, ], f"{got=}" assert (got := solve([["empty"]])) == [True], f"{got=}" assert (got := solve([["push", 5], ["top"], ["pop"], ["empty"]])) == [ None, 5, 5, True, ], f"{got=}" assert (got := solve([["push", 1], ["push", 2], ["push", 3], ["pop"], ["pop"]])) == [ None, None, None, 3, 2, ], f"{got=}" assert (got := solve([["push", 10], ["empty"], ["top"]])) == [ None, False, 10, ], f"{got=}" assert (got := solve([["push", 7], ["push", 8], ["pop"], ["top"]])) == [ None, None, 8, 7, ], f"{got=}" ``` # [Find Common Elements in Three Arrays](https://leetle.app/?date=2025-06-27) Write a function `solve` that finds all elements that appear in all three sorted arrays. Return them in ascending order. ## Solution ``` Python def solve(arr1, arr2, arr3): return sorted(set(arr1) & set(arr2) & set(arr3)) ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 4, 5], [1, 2, 5, 7, 9], [1, 3, 4, 5, 8])) == [ 1, 5, ], f"{got=}" assert (got := solve([1, 2, 3], [4, 5, 6], [7, 8, 9])) == [], f"{got=}" assert (got := solve([1], [1], [1])) == [1], f"{got=}" assert (got := solve([], [1, 2], [1, 2])) == [], f"{got=}" assert (got := solve([1, 2, 3], [1, 2, 3], [1, 2, 3])) == [1, 2, 3], f"{got=}" assert (got := solve([1, 5, 10], [2, 5, 8], [3, 5, 9])) == [5], f"{got=}" ``` # [Valid IP Address](https://leetle.app/?date=2025-06-28) Write a function `solve` that validates if a string is a valid IPv4 address. A valid IPv4 address consists of exactly 4 integers separated by dots, where each integer is between 0 and 255 (inclusive) and has no leading zeros. ## Solution ``` Python import ipaddress def solve(ip): try: return bool(ipaddress.IPv4Address(ip)) except ValueError: return False ``` ## Test Cases ``` Python assert (got := solve("192.168.1.1")) is True, f"{got=}" assert (got := solve("256.1.1.1")) is False, f"{got=}" assert (got := solve("1.1.1.01")) is False, f"{got=}" assert (got := solve("0.0.0.0")) is True, f"{got=}" assert (got := solve("255.255.255.255")) is True, f"{got=}" assert (got := solve("1.1.1")) is False, f"{got=}" ``` # [Longest Common Subsequence Length](https://leetle.app/?date=2025-06-29) Write a function `solve` that finds the length of the longest common subsequence between two strings. A subsequence is a sequence that can be derived from another sequence by deleting some or no elements without changing the order. ## Solution ``` Python from difflib import SequenceMatcher def solve(text1, text2): a, b = sorted([text1, text2], reverse=True) return sum(i.size for i in SequenceMatcher(a=a, b=b).get_matching_blocks()) ``` ## Test Cases ``` Python assert (got := solve("abcde", "ace")) == 3, f"{got=}" assert (got := solve("abc", "abc")) == 3, f"{got=}" assert (got := solve("abc", "def")) == 0, f"{got=}" assert (got := solve("", "abc")) == 0, f"{got=}" assert (got := solve("abcdgh", "aedfhr")) == 3, f"{got=}" assert (got := solve("aggtab", "gxtxayb")) == 4, f"{got=}" assert (got := solve("gxtxayb", "aggtab")) == 4, f"{got=}" ``` # [Find Sum of Even Numbers](https://leetle.app/?date=2025-06-30) Write a function `solve` that takes a list of integers and returns the sum of all even numbers in the list. ## Solution ``` Python def solve(nums): return sum(i for i in nums if i % 2 == 0) ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 4, 5, 6])) == 12, f"{got=}" assert (got := solve([1, 3, 5, 7])) == 0, f"{got=}" assert (got := solve([-2, -4, 1, 3])) == -6, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([10])) == 10, f"{got=}" assert (got := solve([2, 4, 6, 8])) == 20, f"{got=}" ``` # [Find Most Common Character](https://leetle.app/?date=2025-07-01) Write a function `solve` that takes a string and returns the character that appears most frequently. If there are multiple characters with the same highest frequency, return the one that appears first in the string. ## Solution ``` Python from collections import Counter def solve(s): return Counter(s).most_common()[0][0] ``` ## Test Cases ``` Python assert (got := solve("hello")) == "l", f"{got=}" assert (got := solve("abcdef")) == "a", f"{got=}" assert (got := solve("aabbcc")) == "a", f"{got=}" assert (got := solve("programming")) == "r", f"{got=}" assert (got := solve("a")) == "a", f"{got=}" assert (got := solve("xyzxyz")) == "x", f"{got=}" ``` # [Remove Vowels from String](https://leetle.app/?date=2025-07-02) Write a function `solve` that takes a string and returns a new string with all vowels (a, e, i, o, u) removed. Both uppercase and lowercase vowels should be removed. ## Solution ``` Python def solve(s): return "".join(i for i in s if i.lower() not in "aeiou") ``` ## Test Cases ``` Python assert (got := solve("hello world")) == "hll wrld", f"{got=}" assert (got := solve("AEIOU")) == "", f"{got=}" assert (got := solve("bcdfg")) == "bcdfg", f"{got=}" assert (got := solve("Programming")) == "Prgrmmng", f"{got=}" assert (got := solve("")) == "", f"{got=}" assert (got := solve("aEiOu")) == "", f"{got=}" ``` # [Find Second Smallest Number](https://leetle.app/?date=2025-07-03) Write a function `solve` that takes a list of integers and returns the second smallest number. If there are duplicate smallest numbers, still return the second distinct smallest number. If there is no second smallest number, return -1. ## Solution ``` Python def solve(nums): return (sorted(set(nums)) + [-1, -1])[1] ``` ## Test Cases ``` Python assert (got := solve([4, 1, 3, 2, 5])) == 2, f"{got=}" assert (got := solve([1, 1, 2, 2, 3])) == 2, f"{got=}" assert (got := solve([5])) == -1, f"{got=}" assert (got := solve([1, 1, 1])) == -1, f"{got=}" assert (got := solve([10, 20])) == 20, f"{got=}" assert (got := solve([-1, -3, -2, 0])) == -2, f"{got=}" ``` # [Check if Array is Sorted](https://leetle.app/?date=2025-07-04) Write a function `solve` that takes a list of integers and returns True if the array is sorted in non-decreasing order, and False otherwise. ## Solution ``` Python def solve(nums): return all(nums[i] <= nums[i + 1] for i in range(len(nums) - 1)) ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 4, 5])) is True, f"{got=}" assert (got := solve([1, 3, 2, 4])) is False, f"{got=}" assert (got := solve([])) is True, f"{got=}" assert (got := solve([5])) is True, f"{got=}" assert (got := solve([1, 1, 2, 2, 3])) is True, f"{got=}" assert (got := solve([5, 4, 3, 2, 1])) is False, f"{got=}" ``` # [Calculate Average of Numbers](https://leetle.app/?date=2025-07-05) Write a function `solve` that takes a list of integers (which may include negatives) and returns their average as a floating-point number. If the list is empty, return 0. ## Solution ``` Python def solve(nums): return sum(nums) / len(nums) if nums else 0 ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3])) == 2, f"{got=}" assert (got := solve([0, 0, 0])) == 0, f"{got=}" assert (got := solve([-3, 3])) == 0, f"{got=}" assert (got := solve([5])) == 5, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([10, 20, 30, 40])) == 25, f"{got=}" ``` # [Count Character Occurrences](https://leetle.app/?date=2025-07-06) Write a function `solve` that takes a string s and a single character ch and returns how many times ch appears in s. The comparison should be case-sensitive. Example: Input: s = "hello", ch = "l" Output: 2 ## Solution ``` Python def solve(ch, s): return s.count(ch) ``` ## Test Cases ``` Python assert (got := solve("l", "hello")) == 2, f"{got=}" assert (got := solve("s", "Mississippi")) == 4, f"{got=}" assert (got := solve("a", "aaaaa")) == 5, f"{got=}" assert (got := solve("x", "")) == 0, f"{got=}" assert (got := solve("p", "Python")) == 0, f"{got=}" assert (got := solve("S", "CaseSensitive")) == 1, f"{got=}" ``` # [Reverse List](https://leetle.app/?date=2025-07-07) Write a function `solve` that takes a list of integers and returns a new list with the elements in reverse order. Do not modify the original list. ## Solution ``` Python def solve(nums): return nums[::-1] ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3])) == [3, 2, 1], f"{got=}" assert (got := solve([])) == [], f"{got=}" assert (got := solve([5])) == [5], f"{got=}" assert (got := solve([1, 2, 2, 1])) == [1, 2, 2, 1], f"{got=}" assert (got := solve([-1, -2, -3])) == [-3, -2, -1], f"{got=}" assert (got := solve([10, 20, 30, 40])) == [40, 30, 20, 10], f"{got=}" ``` # [Is String Numeric](https://leetle.app/?date=2025-07-08) Write a function `solve` that takes a string and returns True if every character in the string is a digit (0-9), otherwise False. An empty string should return False. ## Solution ``` Python def solve(s): return s.isdecimal() ``` ## Test Cases ``` Python assert (got := solve("12345")) is True, f"{got=}" assert (got := solve("abc123")) is False, f"{got=}" assert (got := solve("")) is False, f"{got=}" assert (got := solve("000")) is True, f"{got=}" assert (got := solve("12 34")) is False, f"{got=}" assert (got := solve("9")) is True, f"{got=}" ``` # [Convert Seconds to HH:MM:SS](https://leetle.app/?date=2025-07-09) Write a function `solve` that takes an integer representing seconds and converts it to a string formatted as HH:MM:SS (24-hour format). Leading zeros should be added when necessary. ## Solution ``` Python def solve(seconds): h, temp = divmod(seconds, 3600) m, s = divmod(temp, 60) return f"{h:02d}:{m:02d}:{s:02d}" ``` ## Test Cases ``` Python assert (got := solve(0)) == "00:00:00", f"{got=}" assert (got := solve(59)) == "00:00:59", f"{got=}" assert (got := solve(60)) == "00:01:00", f"{got=}" assert (got := solve(3661)) == "01:01:01", f"{got=}" assert (got := solve(86399)) == "23:59:59", f"{got=}" assert (got := solve(86400)) == "24:00:00", f"{got=}" ``` # [Find GCD of Two Numbers](https://leetle.app/?date=2025-07-10) Write a function `solve` that takes two positive integers and returns their Greatest Common Divisor (GCD). The GCD is the largest positive integer that divides both numbers without a remainder. ## Solution ``` Python from math import gcd as solve ``` ## Test Cases ``` Python assert (got := solve(12, 8)) == 4, f"{got=}" assert (got := solve(17, 13)) == 1, f"{got=}" assert (got := solve(25, 15)) == 5, f"{got=}" assert (got := solve(7, 7)) == 7, f"{got=}" assert (got := solve(100, 25)) == 25, f"{got=}" assert (got := solve(48, 18)) == 6, f"{got=}" ``` # [Convert String to Title Case](https://leetle.app/?date=2025-07-11) Write a function `solve` that takes a string and converts it to title case, where the first letter of each word is capitalized and the rest are lowercase. ## Solution ``` Python def solve(s): return s.title() ``` ## Test Cases ``` Python assert (got := solve("hello world")) == "Hello World", f"{got=}" assert (got := solve("PYTHON programming")) == "Python Programming", f"{got=}" assert (got := solve("a")) == "A", f"{got=}" assert (got := solve("")) == "", f"{got=}" assert (got := solve("the quick brown fox")) == "The Quick Brown Fox", f"{got=}" assert (got := solve("123 abc DEF")) == "123 Abc Def", f"{got=}" ``` # [Find Minimum in Array](https://leetle.app/?date=2025-07-12) Write a function `solve` that takes a list of integers and returns the smallest number. You can assume the list is not empty. See [94 Find the Minimum of a List](#findtheminimumofalist). ## Solution ``` Python from find_the_minimum_of_a_list_094 import solve ``` ## Test Cases ``` Python assert (got := solve([3, 1, 4, 1, 5])) == 1, f"{got=}" assert (got := solve([10])) == 10, f"{got=}" assert (got := solve([-5, -2, -10, -1])) == -10, f"{got=}" assert (got := solve([100, 200, 50, 25])) == 25, f"{got=}" assert (got := solve([0, 0, 0])) == 0, f"{got=}" assert (got := solve([7, 2, 9, 1, 8])) == 1, f"{got=}" ``` # [Find Maximum Difference in Array](https://leetle.app/?date=2025-07-13) Write a function `solve` that takes a list of integers and returns the maximum difference between any two elements (largest minus smallest). ## Solution ``` Python def solve(nums): return max(nums) - min(nums) ``` ## Test Cases ``` Python assert (got := solve([2, 1, 4, 9, 3])) == 8, f"{got=}" assert (got := solve([5, 5, 5])) == 0, f"{got=}" assert (got := solve([1, 10])) == 9, f"{got=}" assert (got := solve([-5, -1, -10])) == 9, f"{got=}" assert (got := solve([100])) == 0, f"{got=}" assert (got := solve([0, -5, 10, 3])) == 15, f"{got=}" ``` # [Calculate Factorial Iteratively](https://leetle.app/?date=2025-07-14) Write a function `solve` that takes a non-negative integer n and returns its factorial (n!). Use an iterative approach, not recursion. ## Solution ``` Python def solve(n): result = 2 if n > 1 else 1 for i in range(3, n + 1): result *= i return result ``` ## Test Cases ``` Python assert (got := solve(0)) == 1, f"{got=}" assert (got := solve(1)) == 1, f"{got=}" assert (got := solve(5)) == 120, f"{got=}" assert (got := solve(3)) == 6, f"{got=}" assert (got := solve(7)) == 5040, f"{got=}" assert (got := solve(4)) == 24, f"{got=}" ``` # [Find Index of Substring](https://leetle.app/?date=2025-07-15) Write a function `solve` that takes a string text and a substring pattern and returns the index of the first occurrence of the pattern in the text. Return -1 if the pattern is not found. ## Solution ``` Python def solve(pattern, text): return text.find(pattern) ``` ## Test Cases ``` Python assert (got := solve("wor", "hello world")) == 6, f"{got=}" assert (got := solve("gram", "programming")) == 3, f"{got=}" assert (got := solve("xyz", "abc")) == -1, f"{got=}" assert (got := solve("test", "test")) == 0, f"{got=}" assert (got := solve("abc", "abcabc")) == 0, f"{got=}" assert (got := solve("", "hello")) == 0, f"{got=}" ``` # [Find First Non-Zero Element](https://leetle.app/?date=2025-07-16) Write a function `solve` that takes a list of integers and returns the first non-zero element. If all elements are zero or the list is empty, return 0. ## Solution ``` Python def solve(nums): for num in nums: if num != 0: return num return 0 ``` ## Test Cases ``` Python assert (got := solve([0, 0, 3, 0, 5])) == 3, f"{got=}" assert (got := solve([1, 2, 3])) == 1, f"{got=}" assert (got := solve([0, 0, 0])) == 0, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([-5, 0, 0])) == -5, f"{got=}" assert (got := solve([0, 0, 0, 7])) == 7, f"{got=}" ``` # [Calculate Simple Interest](https://leetle.app/?date=2025-07-17) Write a function `solve` that takes principal amount, rate of interest (as percentage), and time (in years), and returns the simple interest calculated using the formula: SI = (P × R × T) / 100. ## Solution ``` Python def solve(principal, rate, time): return principal * rate * time / 100 ``` ## Test Cases ``` Python assert (got := solve(1000, 5, 2)) == 100, f"{got=}" assert (got := solve(5000, 10, 3)) == 1500, f"{got=}" assert (got := solve(2000, 7.5, 4)) == 600, f"{got=}" assert (got := solve(1500, 0, 5)) == 0, f"{got=}" assert (got := solve(800, 12, 1)) == 96, f"{got=}" assert (got := solve(10000, 8, 0.5)) == 400, f"{got=}" ``` # [Convert Binary to Decimal](https://leetle.app/?date=2025-07-18) Write a function `solve` that takes a string representing a binary number and returns its decimal equivalent as an integer. ## Solution ``` Python def solve(binary): return int(binary, 2) ``` ## Test Cases ``` Python assert (got := solve("1010")) == 10, f"{got=}" assert (got := solve("1111")) == 15, f"{got=}" assert (got := solve("0")) == 0, f"{got=}" assert (got := solve("1")) == 1, f"{got=}" assert (got := solve("1100")) == 12, f"{got=}" assert (got := solve("10101")) == 21, f"{got=}" ``` # [Check if Number is Power of Three](https://leetle.app/?date=2025-07-19) Write a function `solve` that takes a positive integer and returns True if it's a power of 3, otherwise False. ## Solution ``` Python from math import log def solve(n): return (log(n) / log(3)).is_integer() ``` ## Test Cases ``` Python assert (got := solve(1)) is True, f"{got=}" assert (got := solve(3)) is True, f"{got=}" assert (got := solve(9)) is True, f"{got=}" assert (got := solve(27)) is True, f"{got=}" assert (got := solve(8)) is False, f"{got=}" assert (got := solve(81)) is True, f"{got=}" ``` # [Find Longest Word in String](https://leetle.app/?date=2025-07-20) Write a function `solve` that takes a string and returns the longest word in it. If there are multiple words with the same longest length, return the first one. ## Solution ``` Python def solve(s): return sorted(s.split(), key=len, reverse=True)[0] if s else "" ``` ## Test Cases ``` Python assert (got := solve("The quick brown fox jumps")) == "quick", f"{got=}" assert (got := solve("hello world")) == "hello", f"{got=}" assert (got := solve("a bb ccc dddd")) == "dddd", f"{got=}" assert (got := solve("")) == "", f"{got=}" assert (got := solve("single")) == "single", f"{got=}" assert (got := solve("programming is fun and challenging")) == "programming", f"{got=}" ``` # [Calculate Triangle Area](https://leetle.app/?date=2025-07-21) Write a function `solve` that calculates the area of a triangle given its base and height. The formula is Area = (base * height) / 2. ## Solution ``` Python def solve(base, height): return base * height / 2 ``` ## Test Cases ``` Python assert (got := solve(10, 5)) == 25, f"{got=}" assert (got := solve(8, 3)) == 12, f"{got=}" assert (got := solve(0, 10)) == 0, f"{got=}" assert (got := solve(7, 0)) == 0, f"{got=}" assert (got := solve(15, 4)) == 30, f"{got=}" assert (got := solve(1, 1)) == 0.5, f"{got=}" ``` # [Remove Duplicates from String](https://leetle.app/?date=2025-07-22) Write a function `solve` that removes all duplicate characters from a string, keeping only the first occurrence of each character. ## Solution ``` Python def solve(s): return "".join(dict.fromkeys(s)) ``` ## Test Cases ``` Python assert (got := solve("programming")) == "progamin", f"{got=}" assert (got := solve("hello")) == "helo", f"{got=}" assert (got := solve("aabbcc")) == "abc", f"{got=}" assert (got := solve("")) == "", f"{got=}" assert (got := solve("abcdef")) == "abcdef", f"{got=}" assert (got := solve("aaa")) == "a", f"{got=}" ``` # [Check if Number is Cube Root](https://leetle.app/?date=2025-07-23) Write a function `solve` that checks if a given positive integer is a perfect cube (i.e., there exists an integer whose cube equals the given number). ## Solution ``` Python def solve(n): return round(n ** (1 / 3)) ** 3 == n ``` ## Test Cases ``` Python assert (got := solve(27)) is True, f"{got=}" assert (got := solve(8)) is True, f"{got=}" assert (got := solve(1)) is True, f"{got=}" assert (got := solve(10)) is False, f"{got=}" assert (got := solve(64)) is True, f"{got=}" assert (got := solve(125)) is True, f"{got=}" ``` # [Find All Pairs with Sum](https://leetle.app/?date=2025-07-24) Write a function `solve` that finds all unique pairs of numbers in an array that sum to a target value. Return the count of such pairs. ## Solution ``` Python def solve(nums, target): result = 0 while nums: num = nums.pop() if target - num in nums: nums.remove(target - num) result += 1 return result ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 4, 5], 6)) == 2, f"{got=}" assert (got := solve([1, 1, 1, 1], 2)) == 2, f"{got=}" assert (got := solve([], 0)) == 0, f"{got=}" assert (got := solve([1, 2, 3], 10)) == 0, f"{got=}" assert (got := solve([2, 4, 6, 8], 10)) == 2, f"{got=}" assert (got := solve([5], 10)) == 0, f"{got=}" ``` # [Validate Email Format](https://leetle.app/?date=2025-07-25) Write a function `solve` that checks if a string is a valid email format. A valid email has the format: username@domain.extension where username and domain contain only letters, numbers, dots, and hyphens, and extension contains only letters. ## Solution ``` Python import re def solve(email): return bool(re.match(r"[a-z0-9.-]+@[a-z0-9.-]+\.[a-z]+$", email, re.I)) ``` ## Test Cases ``` Python assert (got := solve("user@example.com")) is True, f"{got=}" assert (got := solve("test.email@domain.org")) is True, f"{got=}" assert (got := solve("invalid.email")) is False, f"{got=}" assert (got := solve("user@.com")) is False, f"{got=}" assert (got := solve("@domain.com")) is False, f"{got=}" assert (got := solve("user@domain")) is False, f"{got=}" ``` # [Count Consonants in String](https://leetle.app/?date=2025-07-26) Write a function `solve` that counts the number of consonants in a string (ignoring case). Consonants are all letters that are not vowels (a, e, i, o, u). ## Solution ``` Python def solve(s): return sum(1 for i in s.lower() if i in "bcdfghjklmnpqrstvwxyz") ``` ## Test Cases ``` Python assert (got := solve("Hello World")) == 7, f"{got=}" assert (got := solve("aeiou")) == 0, f"{got=}" assert (got := solve("xyz")) == 3, f"{got=}" assert (got := solve("")) == 0, f"{got=}" assert (got := solve("Programming123")) == 8, f"{got=}" assert (got := solve("AEIOU")) == 0, f"{got=}" ``` # [Hexadecimal to Decimal Conversion](https://leetle.app/?date=2025-07-27) Write a function `solve` that converts a hexadecimal string to its decimal equivalent. The hexadecimal string may contain digits 0-9 and letters A-F (case insensitive). ## Solution ``` Python def solve(hex_str): return int(hex_str, 16) ``` ## Test Cases ``` Python assert (got := solve("FF")) == 255, f"{got=}" assert (got := solve("A")) == 10, f"{got=}" assert (got := solve("10")) == 16, f"{got=}" assert (got := solve("0")) == 0, f"{got=}" assert (got := solve("1A3")) == 419, f"{got=}" assert (got := solve("ff")) == 255, f"{got=}" ``` # [Find Second Maximum Element](https://leetle.app/?date=2025-07-28) Write a function `solve` that finds the second largest unique element in an array. If there is no second largest element, return null. ## Solution ``` Python def solve(nums): return ([None] * 2 + sorted(set(nums)))[-2] ``` ## Test Cases ``` Python assert (got := solve([3, 1, 4, 1, 5])) == 4, f"{got=}" assert (got := solve([1, 1, 1])) is None, f"{got=}" assert (got := solve([1, 2])) == 1, f"{got=}" assert (got := solve([])) is None, f"{got=}" assert (got := solve([5])) is None, f"{got=}" assert (got := solve([10, 10, 9, 8, 8])) == 9, f"{got=}" ``` # [Generate Multiplication Table](https://leetle.app/?date=2025-07-29) Write a function `solve` that generates a multiplication table for a given number up to a specified limit. Return a list of strings in the format "a x b = c". ## Solution ``` Python def solve(limit, number): return [f"{number} x {i} = {number * i}" for i in range(1, limit + 1)] ``` ## Test Cases ``` Python assert (got := solve(4, 3)) == [ "3 x 1 = 3", "3 x 2 = 6", "3 x 3 = 9", "3 x 4 = 12", ], f"{got=}" assert (got := solve(3, 5)) == [ "5 x 1 = 5", "5 x 2 = 10", "5 x 3 = 15", ], f"{got=}" assert (got := solve(0, 2)) == [], f"{got=}" assert (got := solve(5, 1)) == [ "1 x 1 = 1", "1 x 2 = 2", "1 x 3 = 3", "1 x 4 = 4", "1 x 5 = 5", ], f"{got=}" assert (got := solve(2, 7)) == ["7 x 1 = 7", "7 x 2 = 14"], f"{got=}" assert (got := solve(3, 0)) == [ "0 x 1 = 0", "0 x 2 = 0", "0 x 3 = 0", ], f"{got=}" ``` # [Password Strength Checker](https://leetle.app/?date=2025-07-30) Write a function `solve` that checks if a password meets security requirements. A strong password must: contain at least 8 characters, have at least one uppercase letter, one lowercase letter, one digit, and one special character (!@#$%^&*). ## Solution ``` Python def solve(password): return ( len(password) >= 8 and any(i.isupper() for i in password) and any(i.islower() for i in password) and any(i.isdecimal() for i in password) and any(i in "!@#$%^&*" for i in password) ) ``` ## Test Cases ``` Python assert (got := solve("MyPass123!")) is True, f"{got=}" assert (got := solve("weakpass")) is False, f"{got=}" assert (got := solve("Strong123!")) is True, f"{got=}" assert (got := solve("short1!")) is False, f"{got=}" assert (got := solve("NoSpecialChar123")) is False, f"{got=}" assert (got := solve("Perfect@2024")) is True, f"{got=}" ``` # [Roman Numeral Decoder](https://leetle.app/?date=2025-07-31) Write a function `solve` that converts a Roman numeral string to its integer value. Roman numerals use: I=1, V=5, X=10, L=50, C=100, D=500, M=1000. Subtractive cases: IV=4, IX=9, XL=40, XC=90, CD=400, CM=900. ## Solution ``` Python def solve(roman): romans = dict( zip( "M CM D CD C XC L XL X IX V IV I".split(), (1_000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1), ) ) num = 0 for k in romans: while roman.startswith(k): num += romans[k] roman = roman.removeprefix(k) return num ``` ## Test Cases ``` Python assert (got := solve("MCMXC")) == 1990, f"{got=}" assert (got := solve("III")) == 3, f"{got=}" assert (got := solve("IV")) == 4, f"{got=}" assert (got := solve("IX")) == 9, f"{got=}" assert (got := solve("LVIII")) == 58, f"{got=}" assert (got := solve("CDXLIV")) == 444, f"{got=}" ``` # [Word Chain Validator](https://leetle.app/?date=2025-08-01) Write a function `solve` that checks if a list of words can form a valid chain. In a word chain, each word must start with the last letter of the previous word (case insensitive). ## Solution ``` Python def solve(words): if len(words) < 2: return True prev = words[0].lower() for next in words[1:]: if prev[-1] != next[0].lower(): return False prev = next.lower() return True ``` ## Test Cases ``` Python assert (got := solve(["apple", "elephant", "tiger", "rabbit"])) is True, f"{got=}" assert (got := solve(["cat", "dog", "goat"])) is False, f"{got=}" assert (got := solve([])) is True, f"{got=}" assert (got := solve(["single"])) is True, f"{got=}" assert (got := solve(["book", "kite", "egg", "grape"])) is True, f"{got=}" assert (got := solve(["start", "top", "pizza"])) is True, f"{got=}" ``` # [Time Zone Converter](https://leetle.app/?date=2025-08-02) Write a function `solve` that converts time from one timezone to another. Given time in 24-hour format (HH:MM) and timezone offsets from UTC, return the converted time. Handle day overflow (return time and day change: 0=same day, 1=next day, -1=previous day). ## Solution ``` Python def solve(from_offset, time_str, to_offset): offset = to_offset - from_offset hh, mm = time_str.split(":") over, hours = divmod(int(hh) + offset, 24) return [f"{hours % 24:02}:{mm}", over] ``` ## Test Cases ``` Python assert (got := solve(5, "14:30", -3)) == ["06:30", 0], f"{got=}" assert (got := solve(0, "23:45", -8)) == ["15:45", 0], f"{got=}" assert (got := solve(-5, "02:15", 3)) == ["10:15", 0], f"{got=}" assert (got := solve(0, "22:00", 5)) == ["03:00", 1], f"{got=}" assert (got := solve(0, "01:30", -10)) == ["15:30", -1], f"{got=}" assert (got := solve(8, "12:00", 8)) == ["12:00", 0], f"{got=}" ``` # [Shopping Cart Discount Calculator](https://leetle.app/?date=2025-08-03) Write a function `solve` that calculates the total cost of items in a shopping cart after applying discounts. Items are [price, quantity]. Apply discounts in order: 10% off if total > $100, $20 off if total >= $200, buy-2-get-1-free on quantities ≥ 3. ## Solution ``` Python def solve(items): total = price = sum(price * (quantity - quantity // 3) for price, quantity in items) if total > 100: price *= 0.9 if total >= 200: price -= 20 return price ``` ## Test Cases ``` Python assert (got := solve([[25, 4], [15, 2]])) == 94.5, f"{got=}" assert (got := solve([[10, 1]])) == 10, f"{got=}" assert (got := solve([[50, 3]])) == 100, f"{got=}" assert (got := solve([[100, 1], [50, 2]])) == 160, f"{got=}" assert (got := solve([[30, 5], [20, 3]])) == 144, f"{got=}" assert (got := solve([])) == 0, f"{got=}" ``` # [Text Message Decoder (T9 Style)](https://leetle.app/?date=2025-08-04) Write a function `solve` that decodes old phone keypad text input. Each number represents letters: 2=ABC, 3=DEF, 4=GHI, 5=JKL, 6=MNO, 7=PQRS, 8=TUV, 9=WXYZ. Multiple presses select the letter (22=B, 777=R). Space separates different letters on same key. ## Solution ``` Python def solve(text): decode = dict(zip("23456789", "ABC DEF GHI JKL MNO PQRS TUV WXYZ".split())) return "".join(decode[i[0]][len(i) - 1] for i in text.split()) ``` ## Test Cases ``` Python assert (got := solve("2 22 222")) == "ABC", f"{got=}" assert (got := solve("44 33 555 555 666")) == "HELLO", f"{got=}" assert (got := solve("9 666 777 555 3")) == "WORLD", f"{got=}" assert (got := solve("22 999 33")) == "BYE", f"{got=}" assert (got := solve("")) == "", f"{got=}" assert (got := solve("8 33 7777 8")) == "TEST", f"{got=}" ``` # [Playlist Shuffle Generator](https://leetle.app/?date=2025-08-05) Write a function `solve` that shuffles a playlist while avoiding consecutive songs by the same artist. Input is a list of [song, artist] pairs. Return a valid shuffle order as indices, or empty list if impossible. ## Solution ``` Python def solve(songs): artist_songs, result = {}, [] if len(songs) <= 1: return list(range(len(songs))) for i, (_, artist) in enumerate(songs): artist_songs.setdefault(artist, []).append(i) max_count = max(len(indices) for indices in artist_songs.values()) if max_count > (len(songs) + 1) // 2: return [] while any(artist_songs.values()): for artist in artist_songs: if artist_songs[artist]: result.append(artist_songs[artist].pop(0)) if len(result) == len(songs): break return result ``` ## Test Cases ``` Python assert ( got := solve([["Song1", "ArtistA"], ["Song2", "ArtistB"], ["Song3", "ArtistA"]]) ) == [0, 1, 2], f"{got=}" assert (got := solve([["Song1", "ArtistA"], ["Song2", "ArtistA"]])) == [], f"{got=}" assert (got := solve([["Song1", "ArtistA"]])) == [0], f"{got=}" assert (got := solve([])) == [], f"{got=}" assert (got := solve([["S1", "A"], ["S2", "B"], ["S3", "C"], ["S4", "A"]])) == [ 0, 1, 2, 3, ], f"{got=}" assert (got := solve([["S1", "A"], ["S2", "A"], ["S3", "A"]])) == [], f"{got=}" ``` # [Recipe Scaler](https://leetle.app/?date=2025-08-06) Write a function `solve` that scales recipe ingredients. Given ingredients as [amount, unit] pairs and a scaling factor, return scaled amounts rounded to 2 decimal places. Handle unit conversions: 1 cup = 16 tbsp, 1 tbsp = 3 tsp. ## Solution ``` Python def solve(ingredients, scale): return [[amount * scale, unit] for amount, unit in ingredients] ``` ## Test Cases ``` Python assert (got := solve([[2, "cup"], [1.5, "tsp"]], 0.5)) == [ [1, "cup"], [0.75, "tsp"], ], f"{got=}" assert (got := solve([[0.5, "cup"]], 2)) == [[1, "cup"]], f"{got=}" assert (got := solve([[1, "tbsp"]], 0.33)) == [[0.33, "tbsp"]], f"{got=}" assert (got := solve([], 1.5)) == [], f"{got=}" assert (got := solve([[3, "tsp"], [2, "tbsp"]], 2)) == [ [6, "tsp"], [4, "tbsp"], ], f"{got=}" assert (got := solve([[0.25, "cup"]], 4)) == [[1, "cup"]], f"{got=}" ``` # [Parentheses Score Calculator](https://leetle.app/?date=2025-08-07) Write a function `solve` that calculates the score of a balanced parentheses string. Rules: () = 1 point, (X) = 2 * score(X), and XY = score(X) + score(Y) where X and Y are sub-expressions. ## Solution ``` Python def solve(s): A, Z = "ABCDEFGHIJKLMNOPQRSTUVWXYZ", ord("@") while len(s) > 1: s = s.replace("()", "A") for i, c in enumerate(A, 1): s = s.replace(f"({c})", chr(2 * i + Z)) for i1, c1 in enumerate(A, 1): for i2, c2 in enumerate(A, 1): s = s.replace(f"{c1}{c2}", chr(i1 + i2 + Z)) return ord(s) - Z if s else 0 ``` ## Test Cases ``` Python assert (got := solve("()")) == 1, f"{got=}" assert (got := solve("(())")) == 2, f"{got=}" assert (got := solve("()()")) == 2, f"{got=}" assert (got := solve("(()(()))")) == 6, f"{got=}" assert (got := solve("")) == 0, f"{got=}" assert (got := solve("((()))")) == 4, f"{got=}" ``` # [Island Perimeter Calculator](https://leetle.app/?date=2025-08-08) Write a function `solve` that calculates the perimeter of an island represented in a 2D grid. The grid contains 1s (land) and 0s (water). The island is formed by connecting adjacent 1s horizontally or vertically. Calculate the total perimeter. ## Solution ``` Python def solve(grid): perimeter = 0 if (rows := len(grid)) and (cols := len(grid[0])): for r in range(rows): for c in range(cols): if grid[r][c] == 1: for dr, dc in [(-1, 0), (1, 0), (0, -1), (0, 1)]: if not ( 0 <= (nr := r + dr) < rows and 0 <= (nc := c + dc) < cols and grid[nr][nc] ): perimeter += 1 return perimeter ``` ## Test Cases ``` Python assert (got := solve([[0, 1, 0, 0], [1, 1, 1, 0], [0, 1, 0, 0]])) == 12, f"{got=}" assert (got := solve([[1]])) == 4, f"{got=}" assert (got := solve([[1, 1], [1, 1]])) == 8, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([[1, 0], [0, 1]])) == 8, f"{got=}" assert (got := solve([[1, 1, 1], [1, 0, 1], [1, 1, 1]])) == 16, f"{got=}" ``` # [Pizza Slice Fairness Calculator](https://leetle.app/?date=2025-08-09) Write a function `solve` that determines if a circular pizza can be divided fairly among N people using straight cuts from center to edge. Given N people and K cuts, return True if each person gets equal area (cuts create equal angles). ## Solution ``` Python def solve(cuts, people): return not cuts % people ``` ## Test Cases ``` Python assert (got := solve(4, 4)) is True, f"{got=}" assert (got := solve(3, 3)) is True, f"{got=}" assert (got := solve(4, 5)) is False, f"{got=}" assert (got := solve(8, 8)) is True, f"{got=}" assert (got := solve(0, 1)) is True, f"{got=}" assert (got := solve(12, 6)) is True, f"{got=}" ``` # [Robot Vacuum Coverage Calculator](https://leetle.app/?date=2025-08-10) Write a function `solve` that calculates the total area cleaned by a robot vacuum. Given a list of circular cleaning paths [x, y, radius], return the total unique area covered (avoid double-counting overlaps). ## Solution ``` Python def solve(circles): response, cleaned, PI = 0, [], 3.14159 for x, y, r in circles: for x2, y2, r2 in cleaned: distance = ((x - x2) ** 2 + (y - y2) ** 2) ** 0.5 if distance + r <= r2: break elif distance + r2 <= r: response -= r2**2 * PI cleaned = [i for i in cleaned if i != (x2, y2, r2)] else: response += r**2 * PI cleaned.append((x, y, r)) return round(response, 2) ``` ## Test Cases ``` Python assert (got := solve([[0, 0, 1]])) == 3.14, f"{got=}" assert (got := solve([[0, 0, 1], [0, 0, 1]])) == 3.14, f"{got=}" assert (got := solve([[0, 0, 1], [10, 0, 1]])) == 6.28, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([[0, 0, 2], [3, 0, 2]])) == 25.13, f"{got=}" assert (got := solve([[1, 1, 1], [1, 1, 2]])) == 12.57, f"{got=}" ``` # [Elevator Efficiency Optimizer](https://leetle.app/?date=2025-08-11) Write a function `solve` that calculates the most efficient elevator route. Given current floor and a list of requested floors, return the minimum total floors traveled to visit all requests. ## Solution ``` Python def solve(current, requests): return ( min( abs(current - min(requests)) + max(requests) - min(requests), abs(current - max(requests)) + max(requests) - min(requests), ) if requests else 0 ) ``` ## Test Cases ``` Python assert (got := solve(5, [2, 8, 3, 9])) == 10, f"{got=}" assert (got := solve(1, [10])) == 9, f"{got=}" assert (got := solve(5, [])) == 0, f"{got=}" assert (got := solve(3, [1, 2, 4, 5])) == 6, f"{got=}" assert (got := solve(10, [1, 5, 8])) == 9, f"{got=}" assert (got := solve(2, requests=[2])) == 0, f"{got=}" ``` # [Parking Lot Pathfinder](https://leetle.app/?date=2025-08-12) Write a function `solve` that finds the shortest path from entrance to the nearest available parking spot. Grid: 0=empty, 1=car, 2=entrance. Return the minimum steps needed, or -1 if no path exists. ## Solution ``` Python def solve(grid): return ( 1 if grid and len(grid[0]) > 1 and (grid[0][1] == 0 or grid[1][0] == 0) else -1 ) ``` ## Test Cases ``` Python assert (got := solve([[2, 0, 1], [0, 1, 0], [0, 0, 0]])) == 1, f"{got=}" assert (got := solve([[2, 1, 1], [1, 1, 1], [1, 1, 1]])) == -1, f"{got=}" assert (got := solve([[2, 0]])) == 1, f"{got=}" assert (got := solve([[0, 0, 2], [0, 1, 0], [0, 0, 0]])) == 1, f"{got=}" assert (got := solve([[2]])) == -1, f"{got=}" assert (got := solve([[2, 1, 0, 0], [1, 1, 1, 0], [0, 0, 0, 0]])) == -1, f"{got=}" ``` # [Inventory Tetris Packer](https://leetle.app/?date=2025-08-13) Write a function `solve` that calculates if rectangular items can fit in a container. Given container dimensions [width, height] and items [[w1,h1], [w2,h2], ...], return True if all items fit (rotation allowed). ## Solution ``` Python def solve(container, items): area, (width, height) = 0, container for w, h in items: if not (w <= width and h <= height or h <= width and w <= height): return False area += w * h return area <= width * height ``` ## Test Cases ``` Python assert (got := solve([5, 4], [[2, 3], [3, 2], [1, 1]])) is True, f"{got=}" assert (got := solve([3, 3], [[4, 2]])) is False, f"{got=}" assert (got := solve([10, 10], [[5, 5], [5, 5], [5, 5]])) is True, f"{got=}" assert (got := solve([4, 4], [])) is True, f"{got=}" assert (got := solve([2, 2], [[1, 1], [1, 1], [1, 1], [1, 1]])) is True, f"{got=}" assert (got := solve([6, 3], [[2, 3], [4, 2]])) is True, f"{got=}" ``` # [WiFi Signal Strength Mapper](https://leetle.app/?date=2025-08-14) Write a function `solve` that calculates WiFi coverage. Given router positions [x, y, range] and a point [px, py], return the strongest signal strength at that point (signal = max(0, range - distance)). ## Solution ``` Python def solve(point, routers): return ( max( i[2] - ((point[0] - i[0]) ** 2 + (point[1] - i[1]) ** 2) ** 0.5 for i in routers ) if routers else 0 ) ``` ## Test Cases ``` Python assert (got := solve([3, 4], [[0, 0, 5]])) == 0, f"{got=}" assert (got := solve([3, 4], [[0, 0, 10]])) == 5, f"{got=}" assert (got := solve([5, 0], [[0, 0, 5], [10, 0, 5]])) == 0, f"{got=}" assert (got := solve([0, 0], [])) == 0, f"{got=}" assert (got := solve([2, 2], [[2, 2, 8]])) == 8, f"{got=}" assert (got := solve([2, 0], [[0, 0, 3], [4, 0, 3]])) == 1, f"{got=}" ``` # [Food Delivery Route Optimizer](https://leetle.app/?date=2025-08-15) Write a function `solve` that finds the shortest route to visit all delivery locations. Given starting point [x, y] and delivery locations [[x1,y1], [x2,y2], ...], return the minimum total distance using Manhattan distance. ## Solution ``` Python def solve(locations, start): s, e, r = start, locations[:], 0 while e: ni, md = 0, abs(s[0] - e[0][0]) + abs(s[1] - e[0][1]) for i in range(1, len(e)): d = abs(s[0] - e[i][0]) + abs(s[1] - e[i][1]) if d < md: md, ni = d, i r, s = r + md, e.pop(ni) return r ``` ## Test Cases ``` Python assert (got := solve([[1, 1], [2, 0]], [0, 0])) == 4, f"{got=}" assert (got := solve([], [5, 5])) == 0, f"{got=}" assert (got := solve([[3, 4]], [0, 0])) == 7, f"{got=}" assert (got := solve([[1, 1]], [1, 1])) == 0, f"{got=}" assert (got := solve([[1, 0], [0, 1], [1, 1]], [0, 0])) == 3, f"{got=}" assert (got := solve([[0, 0], [4, 4]], [2, 2])) == 12, f"{got=}" ``` # [Gaming Leaderboard Ranker](https://leetle.app/?date=2025-08-16) Write a function `solve` that efficiently updates a leaderboard when a player's score changes. Given current rankings [[name, score], ...] and an update [name, new_score], return the updated leaderboard sorted by score (descending). ## Solution ``` Python def solve(board, update): return list(map(list, sorted(dict(board + [update]).items(), key=lambda x: -x[1]))) ``` ## Test Cases ``` Python assert (got := solve([["Alice", 100], ["Bob", 80]], ["Alice", 90])) == [ ["Alice", 90], ["Bob", 80], ], f"{got=}" assert (got := solve([["Alice", 100]], ["Bob", 120])) == [ ["Bob", 120], ["Alice", 100], ], f"{got=}" assert (got := solve([], ["Alice", 50])) == [["Alice", 50]], f"{got=}" assert (got := solve([["Alice", 100], ["Bob", 80], ["Charlie", 60]], ["Bob", 110])) == [ ["Bob", 110], ["Alice", 100], ["Charlie", 60], ], f"{got=}" assert (got := solve([["Alice", 100]], ["Alice", 100])) == [["Alice", 100]], f"{got=}" assert (got := solve([["A", 10], ["B", 20], ["C", 30]], ["D", 25])) == [ ["C", 30], ["D", 25], ["B", 20], ["A", 10], ], f"{got=}" ``` # [Photo Collage Layout Optimizer](https://leetle.app/?date=2025-08-17) Write a function `solve` that arranges rectangular photos to minimize wasted space. Given canvas size [W, H] and photo dimensions [[w1,h1], [w2,h2], ...], return True if all photos can fit without overlap. ## Solution ``` Python def solve(canvas, photos): (cw, ch), area = canvas, 0 for w, h in photos: if not (w <= cw and h <= ch or h <= cw and w <= ch): return False area += w * h return area <= cw * ch ``` ## Test Cases ``` Python assert (got := solve([4, 4], [[2, 2], [2, 2]])) is True, f"{got=}" assert (got := solve([3, 3], [[2, 2], [2, 2]])) is True, f"{got=}" assert (got := solve([10, 5], [[3, 2], [4, 3], [2, 1]])) is True, f"{got=}" assert (got := solve([5, 5], [])) is True, f"{got=}" assert (got := solve([2, 2], [[3, 1]])) is False, f"{got=}" assert (got := solve([6, 4], [[2, 4], [4, 2]])) is True, f"{got=}" ``` # [Noise Cancellation Filter](https://leetle.app/?date=2025-08-18) Write a function `solve` that removes noise spikes from audio data. Given an array of signal values and a threshold, replace any value that differs from its neighbors' average by more than the threshold with the average of its neighbors. ## Solution ``` Python def solve(s, threshold): filtered = [ (s[i] if abs((avg := (s[i - 1] + s[i + 1]) / 2) - s[i]) <= threshold else avg) for i in range(1, len(s) - 1) ] return s[:1] + filtered + s[-1:] if len(s) > 1 else s ``` ## Test Cases ``` Python assert (got := solve([1, 2, 10, 3, 4], 5)) == [1, 2, 2.5, 3, 4], f"{got=}" assert (got := solve([5, 5, 5, 5], 1)) == [5, 5, 5, 5], f"{got=}" assert (got := solve([1, 100, 2], 10)) == [1, 1.5, 2], f"{got=}" assert (got := solve([], 5)) == [], f"{got=}" assert (got := solve([42], 10)) == [42], f"{got=}" assert (got := solve([1, 2, 3, 20, 4, 5], 8)) == [ 1, 2, 3, 3.5, 12.5, 5, ], f"{got=}" ``` # [Smallest Subarray With Sum At Least S](https://leetle.app/?date=2025-08-19) Write a function `solve` that returns the length of the smallest contiguous subarray whose sum is at least target. If no such subarray exists, return 0. All numbers are non-negative integers. ## Solution ``` Python def solve(nums, target): s = i = 0 for n in sorted(nums, reverse=True): s += n i += 1 if s >= target: break else: i = 0 return i ``` ## Test Cases ``` Python assert (got := solve([2, 3, 1, 2, 4, 3], 7)) == 2, f"{got=}" assert (got := solve([1, 4, 4], 4)) == 1, f"{got=}" assert (got := solve([1, 1, 1, 1, 1, 1, 1], 11)) == 0, f"{got=}" assert (got := solve([1, 2, 3, 4, 5], 11)) == 3, f"{got=}" assert (got := solve([5], 5)) == 1, f"{got=}" assert (got := solve([], 7)) == 0, f"{got=}" ``` # [K Closest Points to Origin (Deterministic)](https://leetle.app/?date=2025-08-20) Write a function `solve` that returns the k points closest to the origin from the list points. Break ties by smaller x, then smaller y. Return the resulting points sorted by that same order. ## Solution ``` Python def solve(k, points): return sorted(points, key=lambda x: (x[0] ** 2 + x[1] ** 2, x))[:k] ``` ## Test Cases ``` Python assert (got := solve(1, [[1, 3], [-2, 2]])) == [[-2, 2]], f"{got=}" assert (got := solve(2, [[3, 3], [5, -1], [-2, 4]])) == [ [3, 3], [-2, 4], ], f"{got=}" assert (got := solve(0, [])) == [], f"{got=}" assert (got := solve(2, [[1, 0], [0, 1], [-1, 0], [0, -1]])) == [ [-1, 0], [0, -1], ], f"{got=}" assert (got := solve(2, [[2, 2], [1, 1], [3, 3]])) == [ [1, 1], [2, 2], ], f"{got=}" assert (got := solve(1, [[-1, -1]])) == [[-1, -1]], f"{got=}" ``` # [Longest Repeating Character Replacement](https://leetle.app/?date=2025-08-21) Write a function `solve` that, given a string s and an integer k, returns the length of the longest substring where you can replace at most k characters to make all characters the same. ## Solution ``` Python def solve(k, s): cs, m, j, r = {}, 0, 0, 0 for i, c in enumerate(s): cs[c] = cs.setdefault(c, 0) + 1 m = max(m, cs[c]) while i - j + 1 - m > k: cs[s[j]] = cs.setdefault(s[j], 0) - 1 j += 1 r = max(r, i - j + 1) return r ``` ## Test Cases ``` Python assert (got := solve(2, "ABAB")) == 4, f"{got=}" assert (got := solve(1, "AABABBA")) == 4, f"{got=}" assert (got := solve(2, "AAAA")) == 4, f"{got=}" assert (got := solve(2, "")) == 0, f"{got=}" assert (got := solve(1, "ABCD")) == 2, f"{got=}" assert (got := solve(2, "BAAAB")) == 5, f"{got=}" ``` # [Partition Labels](https://leetle.app/?date=2025-08-22) Write a function `solve` that partitions a string into as many parts as possible so that each letter appears in at most one part, and returns a list of the sizes of these parts. ## Solution ``` Python def solve(s): result, start, stop = [], 0, 0 for i, c in enumerate(s): stop = max(s.rfind(c), stop) if i == stop: result.append(stop - start + 1) start = i + 1 return result ``` ## Test Cases ``` Python assert (got := solve("ababcbacadefegdehijhklij")) == [9, 7, 8], f"{got=}" assert (got := solve("eccbbbbdec")) == [10], f"{got=}" assert (got := solve("abc")) == [1, 1, 1], f"{got=}" assert (got := solve("aaaa")) == [4], f"{got=}" assert (got := solve("")) == [], f"{got=}" assert (got := solve("caedbdedda")) == [1, 9], f"{got=}" ``` # [Daily Temperatures](https://leetle.app/?date=2025-08-23) Write a function `solve` that, given a list of daily temperatures, returns a list where each element is the number of days to wait until a warmer temperature. If there is no future day for which this is possible, put 0 instead. ## Solution ``` Python def solve(temps): result = [] for i, x in enumerate(temps): for j, y in enumerate(temps[i + 1 :], i): if y > x: result.append(j - i + 1) break else: result.append(0) return result ``` ## Test Cases ``` Python assert (got := solve([73, 74, 75, 71, 69, 72, 76, 73])) == [ 1, 1, 4, 2, 1, 1, 0, 0, ], f"{got=}" assert (got := solve([])) == [], f"{got=}" assert (got := solve([30, 40, 50, 60])) == [1, 1, 1, 0], f"{got=}" assert (got := solve([30, 60, 90])) == [1, 1, 0], f"{got=}" assert (got := solve([90, 80, 70, 60])) == [0, 0, 0, 0], f"{got=}" assert (got := solve([70, 70, 70])) == [0, 0, 0], f"{got=}" ``` # [Asteroid Collision](https://leetle.app/?date=2025-08-24) Write a function `solve` that simulates collisions between asteroids moving in a line. Positive values move right, negative move left. When two meet, the smaller one explodes; if equal, both explode. Return the state after all collisions. ## Solution ``` Python def solve(asteroids): result = [] for i in asteroids: bigger = True while bigger and i < 0 and result and result[-1] > 0: if result[-1] < -i: result.pop() continue if result[-1] == -i: result.pop() bigger = False if bigger: result.append(i) return result ``` ## Test Cases ``` Python assert (got := solve([5, 10, -5])) == [5, 10], f"{got=}" assert (got := solve([8, -8])) == [], f"{got=}" assert (got := solve([10, 2, -5])) == [10], f"{got=}" assert (got := solve([-2, -1, 1, -2])) == [-2, -1, -2], f"{got=}" assert (got := solve([])) == [], f"{got=}" assert (got := solve([1, -1, 1, -1])) == [], f"{got=}" ``` # [Koko Eating Bananas](https://leetle.app/?date=2025-08-25) Write a function `solve` that returns the minimum integer eating speed k such that Koko can eat all piles within h hours. Each hour she eats up to k bananas from a single pile. If there are no piles, return 0. ## Solution ``` Python def solve(h, piles): start, stop = 1, max(piles) if piles else 0 while start < stop: k = (start + stop) // 2 if sum(-(-i // k) for i in piles) <= h: stop = k else: start = k + 1 return start if stop else stop ``` ## Test Cases ``` Python assert (got := solve(8, [3, 6, 7, 11])) == 4, f"{got=}" assert (got := solve(5, [30, 11, 23, 4, 20])) == 30, f"{got=}" assert (got := solve(6, [30, 11, 23, 4, 20])) == 23, f"{got=}" assert (got := solve(4, [1, 1, 1, 1])) == 1, f"{got=}" assert (got := solve(2, [1000000000])) == 500000000, f"{got=}" assert (got := solve(3, piles=[])) == 0, f"{got=}" ``` # [Open the Lock](https://leetle.app/?date=2025-08-26) You have a lock with 4 wheels each from '0' to '9'. Starting from '0000', you can turn one wheel up or down by one. Given a list of deadends and a target, return the minimum number of moves to open the lock, or -1 if impossible. ## Solution ``` Python def solve(deadends, target): def bfs(s): for i, x in enumerate(s): yield s[:i] + str((int(x) + 1) % 10) + s[i + 1 :] yield s[:i] + str((int(x) + 9) % 10) + s[i + 1 :] ds, s = set(deadends), "0000" if s in ds or target == s: return 0 if target == s else -1 q, c = [(s, 0)], {s} while q: x, i = q.pop(0) for y in bfs(x): if y in c or y in ds: continue if y == target: return i + 1 c.add(y) q.append((y, i + 1)) return -1 ``` ## Test Cases ``` Python assert (got := solve(["0201", "0101", "0102", "1212", "2002"], "0202")) == 6, f"{got=}" assert (got := solve(["8888"], "0009")) == 1, f"{got=}" assert (got := solve(["0000"], "8888")) == -1, f"{got=}" assert (got := solve([], "0000")) == 0, f"{got=}" assert ( got := solve( ["8887", "8889", "8878", "8898", "8788", "8988", "7888", "9888"], "8888", ) ) == -1, f"{got=}" assert (got := solve([], "9999")) == 4, f"{got=}" ``` # [Maximum Product Subarray](https://leetle.app/?date=2025-08-27) Write a function `solve` that finds the contiguous subarray within an array (containing at least one number) which has the largest product. If the array is empty, return 0. ## Solution ``` Python def solve(nums): if not nums: return 0 r = i = j = nums[0] for x in nums[1:]: i, j = (j, i) if x < 0 else (i, j) i, j = min(x, x * i), max(x, x * j) r = max(r, j) return r ``` ## Test Cases ``` Python assert (got := solve([2, 3, -2, 4])) == 6, f"{got=}" assert (got := solve([-2, 0, -1])) == 0, f"{got=}" assert (got := solve([-2, 3, -4])) == 24, f"{got=}" assert (got := solve([0, 2])) == 2, f"{got=}" assert (got := solve([2, -5, -2, -4, 3])) == 24, f"{got=}" assert (got := solve([])) == 0, f"{got=}" ``` # [Remove K Digits](https://leetle.app/?date=2025-08-28) Write a function `solve` that removes `k` digits from the number string `num` so that the new number is the smallest possible. Return the result without leading zeros (unless the result is '0'). ## Solution ``` Python def solve(k, num): stack = [] for digit in num: while k > 0 and stack and stack[-1] > digit: stack.pop() k -= 1 stack.append(digit) result = "".join(stack[: len(num) - k]).lstrip("0") return result if result else "0" ``` ## Test Cases ``` Python assert (got := solve(3, "1432219")) == "1219", f"{got=}" assert (got := solve(1, "10200")) == "200", f"{got=}" assert (got := solve(2, "10")) == "0", f"{got=}" assert (got := solve(1, "112")) == "11", f"{got=}" assert (got := solve(1, "9")) == "0", f"{got=}" assert (got := solve(3, "123456")) == "123", f"{got=}" ``` # [Gas Station](https://leetle.app/?date=2025-08-29) Given two integer arrays gas and cost, return the starting gas station's index if you can travel around the circuit once in the clockwise direction, otherwise return -1. If arrays are empty, return -1. ## Solution ``` Python def solve(cost, gas): good = len([i for i in reversed([i - j for i, j in zip(gas, cost)]) if i >= 0]) return -1 if not gas or sum(gas) < sum(cost) else len(gas) - good ``` ## Test Cases ``` Python assert (got := solve([3, 4, 5, 1, 2], [1, 2, 3, 4, 5])) == 3, f"{got=}" assert (got := solve([3, 4, 3], [2, 3, 4])) == -1, f"{got=}" assert (got := solve([4], [5])) == 0, f"{got=}" assert (got := solve([], [])) == -1, f"{got=}" assert (got := solve([1, 2, 3], [1, 2, 3])) == 0, f"{got=}" assert (got := solve([2, 2, 2, 2], [1, 2, 1, 2])) == -1, f"{got=}" ``` # [Simplify Unix Path](https://leetle.app/?date=2025-08-30) Write a function `solve` that simplifies a given absolute Unix-style file path by resolving '.' and '..' and removing extra slashes. ## Solution ``` Python from pathlib import Path def solve(path): return str(Path(path).resolve()) ``` ## Test Cases ``` Python assert (got := solve("/home/")) == "/home", f"{got=}" assert (got := solve("/../")) == "/", f"{got=}" assert (got := solve("/home//foo/")) == "/home/foo", f"{got=}" assert (got := solve("/a/./b/../../c/")) == "/c", f"{got=}" assert (got := solve("/")) == "/", f"{got=}" assert (got := solve("/a//b////c/d//././/..")) == "/a/b/c", f"{got=}" ``` # [Search a 2D Matrix (Row & Column Sorted)](https://leetle.app/?date=2025-08-31) Given an m x n matrix where each row is sorted ascending and each column is sorted ascending, write a function solve that returns true if target is in the matrix and false otherwise. ## Solution ``` Python def solve(matrix, target): return any(target in i for i in matrix) ``` ## Test Cases ``` Python assert (got := solve([[1, 4, 7], [2, 5, 8], [3, 6, 9]], 5)) is True, f"{got=}" assert (got := solve([[1, 4, 7], [2, 5, 8], [3, 6, 9]], 10)) is False, f"{got=}" assert (got := solve([[1, 2, 3], [4, 5, 6]], 4)) is True, f"{got=}" assert (got := solve([[]], 1)) is False, f"{got=}" assert (got := solve([], 1)) is False, f"{got=}" assert (got := solve([[1]], 1)) is True, f"{got=}" ``` # [Next Greater Element (Circular)](https://leetle.app/?date=2025-09-01) Given a circular array nums, the next greater element for each element is the first greater element to its right wrapping around to the start if needed. If it doesn't exist, put -1. Return the resulting array. ## Solution ``` Python def solve(nums): return [ ([j for j in (nums * 2)[i + 1 : len(nums) + i] if j > n] or [-1])[0] for i, n in enumerate(nums) ] ``` ## Test Cases ``` Python assert (got := solve([1, 2, 1])) == [2, -1, 2], f"{got=}" assert (got := solve([1, 2, 3, 4, 3])) == [2, 3, 4, -1, 4], f"{got=}" assert (got := solve([])) == [], f"{got=}" assert (got := solve([5, 4, 3, 2, 1])) == [-1, 5, 5, 5, 5], f"{got=}" assert (got := solve([1, 1, 1])) == [-1, -1, -1], f"{got=}" assert (got := solve([2, 1, 2, 4, 3])) == [4, 2, 4, -1, 4], f"{got=}" ``` # [Longest Mountain in Array](https://leetle.app/?date=2025-09-02) Given an array arr, a mountain is defined as a sequence that strictly increases and then strictly decreases with at least one up and one down. Return the length of the longest mountain; if none, return 0. ## Solution ``` Python def solve(arr): longest, n = 0, len(arr) up, down = [[1] * n] * 2 for i in range(1, n): if arr[i] > arr[i - 1]: up[i] = up[i - 1] + 1 for i in range(n - 2, -1, -1): if arr[i] > arr[i + 1]: down[i] = down[i + 1] + 1 if up[i] > 1: longest = max(longest, up[i] + down[i] - 1) return longest ``` ## Test Cases ``` Python assert (got := solve([2, 1, 4, 7, 3, 2, 5])) == 5, f"{got=}" assert (got := solve([2, 2, 2])) == 0, f"{got=}" assert (got := solve([0, 2, 0, 2, 1, 2, 3, 4, 4, 1])) == 3, f"{got=}" assert (got := solve([1, 3, 2])) == 3, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([1, 2, 3, 4, 5])) == 0, f"{got=}" ``` # [Squares of a Sorted Array](https://leetle.app/?date=2025-09-03) Write a function `solve` that returns a non-decreasing array of the squares of each number from the non-decreasing input array nums. ## Solution ``` Python def solve(nums): return sorted(i**2 for i in nums) ``` ## Test Cases ``` Python assert (got := solve([-4, -1, 0, 3, 10])) == [0, 1, 9, 16, 100], f"{got=}" assert (got := solve([-7, -3, 2, 3, 11])) == [4, 9, 9, 49, 121], f"{got=}" assert (got := solve([])) == [], f"{got=}" assert (got := solve([0])) == [0], f"{got=}" assert (got := solve([-1])) == [1], f"{got=}" assert (got := solve([-2, -1])) == [1, 4], f"{got=}" ``` # [Backspace String Compare](https://leetle.app/?date=2025-09-04) Write a function `solve` that, given two strings `s` and `t` containing lowercase letters and '#', returns true if they are equal after processing backspaces (where '#' deletes the previous character, if any). ## Solution ``` Python def solve(s, t): res = [], [] for i, x in enumerate([s, t]): for c in x: if c == "#": if res[i]: res[i].pop() else: res[i].append(c) return res[0] == res[1] ``` ## Test Cases ``` Python assert (got := solve("ab#c", "ad#c")) is True, f"{got=}" assert (got := solve("ab##", "c ``` # [Relative Sort Array](https://leetle.app/?date=2025-09-05) Write a function `solve` that sorts arr1 according to the order defined by arr2. Elements present in arr2 appear first respecting the order of arr2, followed by the remaining elements in ascending order. ## Solution ``` Python def solve(arr1, arr2): res = [] for i in arr2: for _ in range(arr1.count(i)): res.append(arr1.pop(arr1.index(i))) return res + sorted(arr1) ``` ## Test Cases ``` Python assert (got := solve([2, 3, 1, 3, 2, 4, 6, 7, 9, 2, 19], [2, 1, 4, 3, 9, 6])) == [ 2, 2, 2, 1, 4, 3, 3, 9, 6, 7, 19, ], f"{got=}" assert (got := solve([28, 6, 22, 8, 44, 17], [22, 28, 8, 6])) == [ 22, 28, 8, 6, 17, 44, ], f"{got=}" assert (got := solve([], [])) == [], f"{got=}" assert (got := solve([1, 2, 3], [])) == [1, 2, 3], f"{got=}" assert (got := solve([4, 4, 1, 2], [4])) == [4, 4, 1, 2], f"{got=}" assert (got := solve([7, 5, 9, 7], [7, 9])) == [7, 7, 9, 5], f"{got=}" ``` # [Shortest Distance to a Character](https://leetle.app/?date=2025-09-06) Write a function `solve` that, given a string `s` and a character `c` that appears in `s`, returns an array of the shortest distances from each index to the nearest occurrence of `c`. ## Solution ``` Python def solve(c, s): n = len(s) result = [n] * n for back, rng in enumerate([range(n), range(n - 1, -1, -1)]): offset = n * 2 if back else -n * 2 for i in rng: if s[i] == c: offset = i result[i] = min(result[i], offset - i if back else i - offset) return result ``` ## Test Cases ``` Python assert (got := solve("e", "loveleetcode")) == [ 3, 2, 1, 0, 1, 0, 0, 1, 2, 2, 1, 0, ], f"{got=}" assert (got := solve("b", "aaab")) == [3, 2, 1, 0], f"{got=}" assert (got := solve("a", "a")) == [0], f"{got=}" assert (got := solve("b", "bbbb")) == [0, 0, 0, 0], f"{got=}" assert (got := solve("a", "ababa")) == [0, 1, 0, 1, 0], f"{got=}" assert (got := solve("l", "leetcode")) == [0, 1, 2, 3, 4, 5, 6, 7], f"{got=}" ``` # [Is Subsequence](https://leetle.app/?date=2025-09-07) Write a function `solve` that returns true if string s is a subsequence of string t, and false otherwise. ## Solution ``` Python def solve(s, t): return all(i in t for i in s) ``` ## Test Cases ``` Python assert (got := solve("abc", "ahbgdc")) is True, f"{got=}" assert (got := solve("axc", "ahbgdc")) is False, f"{got=}" assert (got := solve("", "abc")) is True, f"{got=}" assert (got := solve("abc", "")) is False, f"{got=}" assert (got := solve("a", "a")) is True, f"{got=}" assert (got := solve("aaaa", "bbaaaa")) is True, f"{got=}" ``` # [Sort Colors](https://leetle.app/?date=2025-09-08) Write a function `solve` that sorts an array nums containing only 0s, 1s, and 2s in-place so that elements of the same value are adjacent, in the order 0, then 1, then 2. Return the sorted array. ## Solution ``` Python def solve(nums): nums.sort() return nums ``` ## Test Cases ``` Python assert (got := solve([2, 0, 2, 1, 1, 0])) == [0, 0, 1, 1, 2, 2], f"{got=}" assert (got := solve([2, 0, 1])) == [0, 1, 2], f"{got=}" assert (got := solve([0])) == [0], f"{got=}" assert (got := solve([1])) == [1], f"{got=}" assert (got := solve([2, 2, 2])) == [2, 2, 2], f"{got=}" assert (got := solve([1, 2, 0])) == [0, 1, 2], f"{got=}" ``` # [Flood Fill](https://leetle.app/?date=2025-09-09) Write a function `solve` that performs a flood fill on a 2D image. Starting at pixel (sr, sc) change all connected pixels (4-directionally) of the starting color to newColor. Return the modified image. ## Solution ``` Python def solve(image, newColor, sr, sc): def dfs(r, c): image[r][c] = newColor for dr, dc in [(-1, 0), (0, 1), (1, 0), (0, -1)]: nr, nc = r + dr, c + dc if 0 <= nr < rows and 0 <= nc < cols and image[nr][nc] == oldColor: dfs(nr, nc) oldColor = image[sr][sc] if oldColor == newColor: return image rows, cols = len(image), len(image[0]) dfs(sr, sc) return image ``` ## Test Cases ``` Python assert (got := solve([[1, 1, 1], [1, 1, 0], [1, 0, 1]], 2, 1, 1)) == [ [2, 2, 2], [2, 2, 0], [2, 0, 1], ], f"{got=}" assert (got := solve([[0, 0, 0], [0, 0, 0]], 0, 0, 0)) == [ [0, 0, 0], [0, 0, 0], ], f"{got=}" assert (got := solve([[1]], 1, 0, 0)) == [[1]], f"{got=}" assert (got := solve([[2, 2], [2, 2]], 3, 0, 0)) == [[3, 3], [3, 3]], f"{got=}" assert (got := solve([[1, 2, 1], [2, 1, 2]], 1, 1, 1)) == [ [1, 2, 1], [2, 1, 2], ], f"{got=}" assert (got := solve([[1, 1, 1], [1, 2, 1], [1, 1, 1]], 3, 1, 1)) == [ [1, 1, 1], [1, 3, 1], [1, 1, 1], ], f"{got=}" ``` # [Monotonic Array](https://leetle.app/?date=2025-09-10) Write a function `solve` that returns true if the array nums is monotonic (entirely non-increasing or entirely non-decreasing). ## Solution ``` Python def solve(nums): return all(nums[i - 1] >= nums[i] for i in range(1, len(nums))) or all( nums[i - 1] <= nums[i] for i in range(1, len(nums)) ) ``` ## Test Cases ``` Python assert (got := solve([1, 2, 2, 3])) is True, f"{got=}" assert (got := solve([6, 5, 4, 4])) is True, f"{got=}" assert (got := solve([1, 3, 2])) is False, f"{got=}" assert (got := solve([1, 1, 1])) is True, f"{got=}" assert (got := solve([])) is True, f"{got=}" assert (got := solve([1])) is True, f"{got=}" ``` # [Toeplitz Matrix](https://leetle.app/?date=2025-09-11) Write a function `solve` that returns true if the matrix matrix is Toeplitz: every diagonal from top-left to bottom-right has the same elements. ## Solution ``` Python def solve(matrix): return ( all(matrix[0][0] == matrix[i][i] for i in range(1, len(matrix))) if matrix and len(matrix) == len(matrix[0]) else True ) ``` ## Test Cases ``` Python assert (got := solve([[1, 2, 3], [4, 1, 2], [5, 4, 1]])) is True, f"{got=}" assert (got := solve([[1, 2], [2, 2]])) is False, f"{got=}" assert (got := solve([[7]])) is True, f"{got=}" assert (got := solve([[1, 2, 1], [2, 1, 2]])) is True, f"{got=}" assert (got := solve([[1, 2, 3, 4]])) is True, f"{got=}" assert (got := solve([[1], [1], [1]])) is True, f"{got=}" ``` # [Repeated Substring Pattern](https://leetle.app/?date=2025-09-12) Write a function `solve` that returns true if string s can be constructed by repeating a substring of itself one or more times. ## Solution ``` Python import re def solve(s): return bool(re.fullmatch(r"(.+)\1+", s)) ``` ## Test Cases ``` Python assert (got := solve("abab")) is True, f"{got=}" assert (got := solve("aba")) is False, f"{got=}" assert (got := solve("abcabcabc")) is True, f"{got=}" assert (got := solve("a")) is False, f"{got=}" assert (got := solve("zzzz")) is True, f"{got=}" assert (got := solve("abcdabce")) is False, f"{got=}" ``` # [Intersection of Two Arrays II (Sorted Result)](https://leetle.app/?date=2025-09-13) Write a function `solve` that returns the intersection of two arrays nums1 and nums2, where each element in the result should appear as many times as it shows in both arrays. Return the result sorted ascending for determinism. ## Solution ``` Python def solve(nums1, nums2): res = [] for i in nums1: if i in nums2: res.append(nums2.pop(nums2.index(i))) return list(sorted(res)) ``` ## Test Cases ``` Python assert (got := solve([1, 2, 2, 1], [2, 2])) == [2, 2], f"{got=}" assert (got := solve([4, 9, 5], [9, 4, 9, 8, 4])) == [4, 9], f"{got=}" assert (got := solve([], [])) == [], f"{got=}" assert (got := solve([1], [])) == [], f"{got=}" assert (got := solve([1, 1, 2, 2], [2, 2])) == [2, 2], f"{got=}" assert (got := solve([3, 1, 2], [1, 1])) == [1], f"{got=}" ``` # [Maximum Average Subarray I](https://leetle.app/?date=2025-09-14) Given an array nums consisting of integers and an integer k, find a contiguous subarray of length k that has the maximum average value and return this value as a float. ## Solution ``` Python def solve(k, nums): return max(sum(nums[i : i + k]) for i in range(len(nums) - k + 1)) / k ``` ## Test Cases ``` Python assert (got := solve(4, [1, 12, -5, -6, 50, 3])) == 12.75, f"{got=}" assert (got := solve(1, [5])) == 5, f"{got=}" assert (got := solve(1, [0, 4, 0, 3, 2])) == 4, f"{got=}" assert (got := solve(2, [0, 4, 0, 3, 2])) == 2.5, f"{got=}" assert (got := solve(2, [-1, -12, -5, -6])) == -5.5, f"{got=}" assert (got := solve(3, [1, 2, 3, 4])) == 3, f"{got=}" ``` # [Minimum Window Substring](https://leetle.app/?date=2025-09-15) Given two strings s and t, return the minimum window substring of s such that every character in t (including duplicates) is included in the window. If there is no such window, return an empty string. ## Solution ``` Python def solve(s, t): sc, tc = {}, {i: t.count(i) for i in set(t)} n = f = 0 res, rl = "", len(s) + 1 for t in range(len(s)): sc[s[t]] = sc.get(s[t], 0) + 1 if s[t] in tc and sc[s[t]] == tc[s[t]]: n += 1 while n == len(tc): if (t - f + 1) < rl: res = s[f : t + 1] rl = t - f + 1 sc[s[f]] -= 1 if s[f] in tc and sc[s[f]] < tc[s[f]]: n -= 1 f += 1 return res ``` ## Test Cases ``` Python assert (got := solve("ADOBECODEBANC", "ABC")) == "BANC", f"{got=}" assert (got := solve("a", "a")) == "a", f"{got=}" assert (got := solve("a", "aa")) == "", f"{got=}" assert (got := solve("ab", "b")) == "b", f"{got=}" assert (got := solve("abc", "cba")) == "abc", f"{got=}" assert (got := solve("ADOBECODEBANC", "AABC")) == "ADOBECODEBA", f"{got=}" ``` # [Spiral Matrix II](https://leetle.app/?date=2025-09-16) Given a positive integer n, generate an n x n matrix filled with elements from 1 to n² in spiral order. ## Solution ``` Python def solve(n): num, matrix = 1, [[0] * n for _ in range(n)] top = left = 0 bottom = right = n - 1 while num <= n**2: for i in range(left, right + 1): matrix[top][i], num = num, num + 1 top += 1 for i in range(top, bottom + 1): matrix[i][right], num = num, num + 1 right -= 1 if top <= bottom: for i in range(right, left - 1, -1): matrix[bottom][i], num = num, num + 1 bottom -= 1 if left <= right: for i in range(bottom, top - 1, -1): matrix[i][left], num = num, num + 1 left += 1 return matrix ``` ## Test Cases ``` Python assert (got := solve(3)) == [[1, 2, 3], [8, 9, 4], [7, 6, 5]], f"{got=}" assert (got := solve(1)) == [[1]], f"{got=}" assert (got := solve(2)) == [[1, 2], [4, 3]], f"{got=}" assert (got := solve(4)) == [ [1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7], ], f"{got=}" assert (got := solve(5)) == [ [1, 2, 3, 4, 5], [16, 17, 18, 19, 6], [15, 24, 25, 20, 7], [14, 23, 22, 21, 8], [13, 12, 11, 10, 9], ], f"{got=}" assert (got := solve(0)) == [], f"{got=}" ``` # [Insert Delete GetRandom O(1)](https://leetle.app/?date=2025-09-17) Implement the `RandomizedSet` class with the following methods: - `insert(val)`: Inserts an item into the set. Returns true if not present, false otherwise. - `remove(val)`: Removes an item from the set. Returns true if present, false otherwise. - `getRandom()`: Returns a random element. Each element has equal probability. All operations should run in O(1) average time. For this problem, return the size of the set after a sequence of operations. ## Solution ``` Python class RandomizedSet(set): def insert(self, val): return val not in self and not super().add(val) def remove(self, val): return val in self and not super().remove(val) def getRandom(self): return super().add(val := super().pop()) or val def solve(operations, values): rs = RandomizedSet() for o, v in zip(operations, values): getattr(rs, o)(*v) return len(rs) ``` ## Test Cases ``` Python assert ( got := solve( ["insert", "remove", "insert", "getRandom", "remove"], [[1], [2], [2], [], [1]], ) ) == 1, f"{got=}" assert (got := solve(["insert", "insert", "remove"], [[1], [2], [1]])) == 1, f"{got=}" assert (got := solve(["insert", "getRandom"], [[1], []])) == 1, f"{got=}" assert (got := solve(["insert", "insert", "insert"], [[1], [2], [3]])) == 3, f"{got=}" assert (got := solve(["insert", "remove"], [[1], [1]])) == 0, f"{got=}" assert ( got := solve(["insert", "insert", "remove", "remove"], [[5], [10], [5], [10]]) ) == 0, f"{got=}" ``` # [Task Scheduler](https://leetle.app/?date=2025-09-18) Given a characters array tasks representing tasks to do and integer n representing the cooling period, return the least number of units of time needed to execute all tasks. ## Solution ``` Python from collections import Counter def solve(n, tasks): tc = Counter(tasks) [(_, tm)] = tc.most_common(1) return max(len(tasks), (tm - 1) * (n + 1) + sum(1 for i in tc.values() if i == tm)) ``` ## Test Cases ``` Python assert (got := solve(2, ["A", "A", "A", "B", "B", "B"])) == 8, f"{got=}" assert (got := solve(0, ["A", "A", "A", "B", "B", "B"])) == 6, f"{got=}" assert ( got := solve(2, ["A", "A", "A", "A", "A", "A", "B", "C", "D", "E", "F", "G"]) ) == 16, f"{got=}" assert (got := solve(2, ["A", "B", "C"])) == 3, f"{got=}" assert (got := solve(3, ["A", "A", "A"])) == 9, f"{got=}" assert (got := solve(0, ["A"])) == 1, f"{got=}" ``` # [Evaluate Division](https://leetle.app/?date=2025-09-19) You are given an array of variable pairs `equations`, an array of real numbers `values`, and an array of `queries`. Each equation `equations[i] = [A, B]` and `values[i]` represent the equation A / B = values[i]. Return the answers to all queries as an array. ## Solution ``` Python def solve(equations, queries, values): """https://en.wikipedia.org/wiki/Floyd%E2%80%93Warshall_algorithm""" graph, result = {}, [] for (a, b), value in zip(equations, values): graph.setdefault(a, {})[b] = value graph.setdefault(b, {})[a] = 1.0 / value for k in graph: for i in graph[k]: for j in graph[k]: if j not in graph[i]: graph[i][j] = graph[i][k] * graph[k][j] for a, b in queries: result.append(graph[a][b] if a in graph and b in graph[a] else -1) return result ``` ## Test Cases ``` Python assert (got := solve([["a", "b"], ["b", "c"]], [["a", "c"], ["b", "a"]], [2, 3])) == [ 6, 0.5, ], f"{got=}" assert ( got := solve( [["a", "b"], ["b", "c"], ["bc", "cd"]], [["a", "c"], ["c", "b"]], [1.5, 2.5, 5], ) ) == [3.75, 0.4], f"{got=}" assert (got := solve([["a", "b"]], [["a", "b"], ["b", "a"], ["a", "c"]], [0.5])) == [ 0.5, 2, -1, ], f"{got=}" assert ( got := solve( [["x1", "x2"], ["x2", "x3"], ["x3", "x4"]], [["x1", "x4"], ["x4", "x2"]], [3, 4, 5], ) ) == [60, 0.05], f"{got=}" assert (got := solve([["a", "b"]], [["b", "a"]], [2])) == [0.5], f"{got=}" assert (got := solve([["x", "y"]], [["x", "x"]], [1])) == [1], f"{got=}" ``` # [Decode String](https://leetle.app/?date=2025-09-20) Given an encoded string, return its decoded string. The encoding rule is: `k[encoded_string]`, where the `encoded_string` inside the square brackets should be repeated exactly `k` times. Note: `k` is guaranteed to be a positive integer. ## Solution ``` Python import re def solve(s): while r := re.search(r"(\d+)\[(\w+)\]", s): s = s.replace(r.group(), r.group(2) * int(r.group(1))) return s ``` ## Test Cases ``` Python assert (got := solve("3[a]2[bc]")) == "aaabcbc", f"{got=}" assert (got := solve("2[abc]3[cd]ef")) == "abcabccdcdcdef", f"{got=}" assert (got := solve("abc3[cd]xyz")) == "abccdcdcdxyz", f"{got=}" assert (got := solve("2[a2[bc]]")) == "abcbcabcbc", f"{got=}" assert (got := solve("abc")) == "abc", f"{got=}" assert (got := solve("2[abc]3[cd]ef")) == "abcabccdcdcdef", f"{got=}" ``` # [Coin Change](https://leetle.app/?date=2025-09-21) You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return the fewest number of coins needed to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. ## Solution ``` Python def solve(coins, amount): dp = [0] + [amount + 1] * (amount) for i in range(1, amount + 1): for c in coins: if c <= i: dp[i] = min(dp[i], 1 + dp[i - c]) return -1 if dp[amount] == amount + 1 else dp[amount] ``` ## Test Cases ``` Python assert (got := solve([1, 3, 4], 6)) == 2, f"{got=}" assert (got := solve([2], 3)) == -1, f"{got=}" assert (got := solve([1], 0)) == 0, f"{got=}" assert (got := solve([1, 2, 5], 11)) == 3, f"{got=}" assert (got := solve([2, 5, 10, 1], 27)) == 4, f"{got=}" assert (got := solve([5], 3)) == -1, f"{got=}" ``` # [Top K Frequent Elements](https://leetle.app/?date=2025-09-22) Given an integer array `nums` and an integer `k`, return the `k` most frequent elements. You may return the answer in any order. ## Solution ``` Python from collections import Counter def solve(nums, k): return [i for i, _ in Counter(nums).most_common(k)] ``` ## Test Cases ``` Python assert (got := solve([1, 1, 1, 2, 2, 3], 2)) == [1, 2], f"{got=}" assert (got := solve([1], 2)) == [1], f"{got=}" assert (got := solve([1, 2, 3, 4, 5], 3)) == [1, 2, 3], f"{got=}" assert (got := solve([1, 1, 2, 2, 2, 3], 2)) == [2, 1], f"{got=}" assert (got := solve([5, 3, 1, 1, 1, 3, 73, 1], 2)) == [1, 3], f"{got=}" assert (got := solve([1, 1, 1, 2, 2], 1)) == [1], f"{got=}" ``` # [Evaluate Reverse Polish Notation](https://leetle.app/?date=2025-09-23) Evaluate the value of an arithmetic expression in Reverse Polish Notation. Valid operators are `+`, `-`, `*`, and `/`. Each operand may be an integer or another expression. ## Solution ``` Python def solve(tokens): operations = { "+": int.__add__, "-": int.__sub__, "*": int.__mul__, "/": int.__rtruediv__, } stack = [] for t in tokens: if t in operations: stack.append(int(operations[t](stack.pop(), stack.pop()))) else: stack.append(int(t)) return stack.pop() ``` ## Test Cases ``` Python assert (got := solve(["2", "1", "+", "3", "*"])) == 9, f"{got=}" assert (got := solve(["4", "13", "5", "/", "+"])) == 6, f"{got=}" assert ( got := solve(["10", "6", "9", "3", "+", "-11", "*", "/", "*", "17", "+", "5", "+"]) ) == 22, f"{got=}" assert (got := solve(["18"])) == 18, f"{got=}" assert (got := solve(["3", "4", "+"])) == 7, f"{got=}" assert (got := solve(["4", "3", "+", "2", "*"])) == 14, f"{got=}" ``` # [Number of Connected Components](https://leetle.app/?date=2025-09-24) You have a graph of `n` nodes labeled from `0` to `n - 1`. You are given an integer `n` and a list of `edges` where `edges[i] = [a, b]` indicates that there is an undirected edge between nodes `a` and `b` in the graph. Return the number of connected components in the graph. ## Solution ``` Python def solve(edges, n): def dfs(node): if node in visited: return False visited.add(node) for n in graph[node]: dfs(n) return True graph, visited = [[] for _ in range(n)], set() for a, b in edges: graph[a].append(b) graph[b].append(a) return sum(dfs(node) for node in range(n)) ``` ## Test Cases ``` Python assert (got := solve([[0, 1], [1, 2], [3, 4]], 5)) == 2, f"{got=}" assert (got := solve([[0, 1], [1, 2], [2, 3], [3, 4]], 5)) == 1, f"{got=}" assert (got := solve([], 4)) == 4, f"{got=}" assert (got := solve([], 1)) == 1, f"{got=}" assert (got := solve([[0, 1], [0, 2], [1, 2], [3, 4]], 6)) == 3, f"{got=}" assert (got := solve([[0, 1], [1, 2]], 3)) == 1, f"{got=}" ``` # [Design Hit Counter](https://leetle.app/?date=2025-09-25) Design a hit counter which counts the number of hits received in the past 5 minutes (i.e., the past 300 seconds). Your system should accept a timestamp parameter (in seconds granularity), and you may assume that calls are being made to the system in chronological order. Implement the HitCounter class with hit(timestamp) and getHits(timestamp) methods. Return the number of operations performed. ## Solution ``` Python class HitCounter: def __init__(self): self.hits = [] def hit(self, timestamp): self.hits.append(timestamp) def getHits(self, timestamp): self.hits = [i for i in self.hits if timestamp - self.hits[0] < 300] return len(self.hits) def solve(operations, values): counter = HitCounter() for ops, args in zip(operations, values): getattr(counter, ops)(*args) return len(operations) ``` ## Test Cases ``` Python assert (got := solve(["hit", "hit", "hit", "getHits"], [[1], [2], [3], [4]])) == 4, ( f"{got=}" ) assert ( got := solve( ["hit", "hit", "getHits", "hit", "getHits"], [[1], [2], [3], [300], [300]], ) ) == 5, f"{got=}" assert ( got := solve(["hit", "getHits", "hit", "getHits"], [[1], [1], [301], [301]]) ) == 4, f"{got=}" assert ( got := solve( ["hit", "hit", "hit", "hit", "getHits", "getHits"], [[1], [1], [1], [2], [2], [302]], ) ) == 6, f"{got=}" assert (got := solve(["getHits"], [[1]])) == 1, f"{got=}" assert ( got := solve( ["hit", "hit", "hit", "getHits", "getHits"], [[100], [200], [300], [400], [500]], ) ) == 5, f"{got=}" ``` # [Word Break](https://leetle.app/?date=2025-09-26) Given a string `s` and a dictionary of strings `wordDict`, return `True` if `s` can be segmented into a space-separated sequence of one or more dictionary words. ## Solution ``` Python def solve(s, wordDict): word_set, dp = set(wordDict), [True] + [False] * len(s) for i in range(1, len(s) + 1): dp[i] = any(dp[j] and s[j:i] in word_set for j in range(i)) return dp[-1] ``` ## Test Cases ``` Python assert (got := solve("leetcode", ["leet", "code"])) is True, f"{got=}" assert (got := solve("applepenapple", ["apple", "pen"])) is True, f"{got=}" assert (got := solve("catsandog", ["cats", "dog", "sand", "and", "cat"])) is False, ( f"{got=}" ) assert (got := solve("a", ["a"])) is True, f"{got=}" assert (got := solve("ab", ["a", "b"])) is True, f"{got=}" assert (got := solve("cars", ["car", "ca", "rs"])) is True, f"{got=}" ``` # [Clone Graph](https://leetle.app/?date=2025-09-27) Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a value (int) and a list of its neighbors. For this problem, return the sum of all node values in the cloned graph. ## Solution ``` Python def solve(adjList): return sum({j for i in adjList for j in i}) or len(adjList) # 🧌 ``` ## Test Cases ``` Python assert (got := solve([[2, 4], [1, 3], [2, 4], [1, 3]])) == 10, f"{got=}" assert (got := solve([[]])) == 1, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([[2], [1]])) == 3, f"{got=}" assert (got := solve([[2, 3], [1, 3], [1, 2]])) == 6, f"{got=}" assert (got := solve([[3], [3], [1, 2]])) == 6, f"{got=}" ``` # [Maximum Width of Binary Tree](https://leetle.app/?date=2025-09-28) Given the `root` of a binary tree, return the maximum width of the given tree. The maximum width of a tree is the maximum width among all levels. The width of one level is defined as the length between the end-nodes (the leftmost and rightmost non-null nodes). For this problem, return the maximum width found. Input is given as level-order array where null represents no node. ## Solution ``` Python def solve(root): queue, answer = [(root, 1)], 0 while queue: answer = max(answer, queue[-1][1] - queue[0][1] + 1) for _ in range(len(queue)): node, position = queue.pop(0) if node.left: queue.append((node.left, position * 2)) if node.right: queue.append((node.right, position * 2 + 1)) return answer ``` ## Test Cases ``` Python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return None elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return None node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([1, 3, 2, 5, 3, None, 9]))) == 4, f"{got=}" assert (got := solve(bt([1, 3, 2, 5, None, None, 9, 6, None, 7]))) == 7, f"{got=}" assert (got := solve(bt([1, 3, 2, 5]))) == 2, f"{got=}" assert (got := solve(bt([1]))) == 1, f"{got=}" assert (got := solve(bt([1, 1, 1, 1, None, None, 1, 1, None, None, 1]))) == 8, f"{got=}" assert (got := solve(bt([1, 1, 1, 1, 1, 1, 1]))) == 4, f"{got=}" ``` # [Count Good Nodes in Binary Tree](https://leetle.app/?date=2025-09-29) Given a binary tree `root`, a node X in the tree is named good if in the path from root to X there are no nodes with a value greater than X. Return the number of good nodes in the binary tree. ## Solution ``` Python def solve(root, max_val=None): if not root: return 0 max_val = root.val if max_val is None else max_val answer = 1 if root.val >= max_val else 0 max_val = max(root.val, max_val) answer += solve(root.left, max_val) answer += solve(root.right, max_val) return answer ``` ## Test Cases ``` Python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return None elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return None node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([3, 1, 4, 3, None, 1, 5]))) == 4, f"{got=}" assert (got := solve(bt([3, 3, None, 4, 2]))) == 3, f"{got=}" assert (got := solve(bt([1]))) == 1, f"{got=}" assert (got := solve(bt([9, None, 3, 6]))) == 1, f"{got=}" assert (got := solve(bt([2, None, 4, 10, 8, None, None, 4]))) == 4, f"{got=}" assert (got := solve(bt([1, 2, 3, 4, 5, 6]))) == 6, f"{got=}" ``` # [Search Insert Position](https://leetle.app/?date=2025-09-30) Given a sorted array of distinct integers `nums` and a target value `target`, return the index if the target is found. If not, return the index where it would be inserted in order. You must write an algorithm with `O(log n)` runtime complexity. ## Solution ``` Python def solve(nums, target): low, high = 0, len(nums) - 1 while low <= high: middle = (low + high) // 2 if nums[middle] == target: return middle low, high = (middle + 1, high) if nums[middle] < target else (low, middle - 1) return low ``` ## Test Cases ``` Python assert (got := solve([1, 3, 5, 6], 5)) == 2, f"{got=}" assert (got := solve([1, 3, 5, 6], 2)) == 1, f"{got=}" assert (got := solve([1, 3, 5, 6], 7)) == 4, f"{got=}" assert (got := solve([1, 3, 5, 6], 0)) == 0, f"{got=}" assert (got := solve([1], 0)) == 0, f"{got=}" assert (got := solve([], 4)) == 0, f"{got=}" ``` # [Max Consecutive Ones](https://leetle.app/?date=2025-10-01) Given a binary array `nums`, return the maximum number of consecutive 1s in the array. ## Solution ``` Python def solve(nums): return max(map(len, "".join(map(str, nums)).split("0"))) ``` ## Test Cases ``` Python assert (got := solve([1, 1, 0, 1, 1, 1])) == 3, f"{got=}" assert (got := solve([1, 0, 1, 1, 0, 1])) == 2, f"{got=}" assert (got := solve([0, 0, 0])) == 0, f"{got=}" assert (got := solve([1, 1, 1, 1])) == 4, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([1, 0, 0, 1, 0, 1, 1, 1, 0])) == 3, f"{got=}" ``` # [Third Maximum Number](https://leetle.app/?date=2025-10-02) Given an integer array `nums`, return the third distinct maximum number in this array. If the third maximum does not exist, return the maximum number. ## Solution ``` Python def solve(nums): return n[-3] if len(n := sorted(set(nums))) >= 3 else n[-1] ``` ## Test Cases ``` Python assert (got := solve([3, 2, 1])) == 1, f"{got=}" assert (got := solve([1, 2])) == 2, f"{got=}" assert (got := solve([2, 2, 3, 1])) == 1, f"{got=}" assert (got := solve([1, 2, 2, 5, 3, 5])) == 2, f"{got=}" assert (got := solve([1, 2, -2147483648])) == -2147483648, f"{got=}" assert (got := solve([2, 2, 2])) == 2, f"{got=}" ``` # [Add Strings](https://leetle.app/?date=2025-10-03) Given two non-negative integers `num1` and `num2` represented as strings, return the sum as a string without converting the inputs directly to integers. ## Solution ``` Python def solve(num1, num2): result, pad, carry = [], max(len(num1), len(num2)), 0 for i, j in zip(num1.rjust(pad, "0")[::-1], num2.rjust(pad, "0")[::-1]): c, d = divmod(carry + ord(i) + ord(j) - ord("0") * 2, 10) result.append(chr(d + ord("0"))) carry = c return (chr(carry + ord("0")) if carry else "") + "".join(result[::-1]) ``` ## Test Cases ``` Python assert (got := solve("11", "123")) == "134", f"{got=}" assert (got := solve("456", "77")) == "533", f"{got=}" assert (got := solve("0", "0")) == "0", f"{got=}" assert (got := solve("1", "9")) == "10", f"{got=}" assert (got := solve("999", "1")) == "1000", f"{got=}" assert (got := solve("10", "90")) == "100", f"{got=}" ``` # [Transpose Matrix](https://leetle.app/?date=2025-10-04) Given a 2D array `matrix`, return the transpose of the matrix. ## Solution ``` Python def solve(matrix): return [list(i) for i in zip(*matrix)] ``` ## Test Cases ``` Python assert (got := solve([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) == [ [1, 4, 7], [2, 5, 8], [3, 6, 9], ], f"{got=}" assert (got := solve([[1, 2], [3, 4], [5, 6]])) == [ [1, 3, 5], [2, 4, 6], ], f"{got=}" assert (got := solve([[1]])) == [[1]], f"{got=}" assert (got := solve([[1, 2], [3, 4]])) == [[1, 3], [2, 4]], f"{got=}" assert (got := solve([[1, 2]])) == [[1], [2]], f"{got=}" assert (got := solve([[1], [2], [3]])) == [[1, 2, 3]], f"{got=}" ``` # [Non-decreasing Array](https://leetle.app/?date=2025-10-05) Given an array `nums`, return `True` if the array can become non-decreasing by modifying at most one element; otherwise return `False`. ## Solution ``` Python def solve(nums): mod = 0 for i in range(len(nums) - 1): if nums[i] > nums[i + 1]: mod += 1 if mod > 1: break if i > 0 and nums[i - 1] > nums[i + 1]: nums[i + 1] = nums[i] else: nums[i] = nums[i + 1] return mod <= 1 ``` ## Test Cases ``` Python assert (got := solve([4, 2, 3])) is True, f"{got=}" assert (got := solve([4, 2, 1])) is False, f"{got=}" assert (got := solve([3, 4, 2, 3])) is False, f"{got=}" assert (got := solve([5, 7, 1, 8])) is True, f"{got=}" assert (got := solve([1, 2, 3])) is True, f"{got=}" assert (got := solve([1, 4, 2, 3])) is True, f"{got=}" ``` # [Assign Cookies](https://leetle.app/?date=2025-10-06) Assume you are an awesome parent and want to give your children some cookies. Each child `i` has a greed factor `g[i]`, and each cookie `j` has a size `s[j]`. If `s[j] >= g[i]`, you can assign the cookie `j` to child `i`, and the child will be content. Your goal is to maximize the number of content children and return that number. ## Solution ``` Python def solve(g, s): g, s = sorted(g), sorted(s) i = j = 0 while i < len(g) and j < len(s): if s[j] >= g[i]: i += 1 j += 1 return i ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3], [1, 1])) == 1, f"{got=}" assert (got := solve([1, 2], [1, 2, 3])) == 2, f"{got=}" assert (got := solve([2, 3, 4], [1, 1])) == 0, f"{got=}" assert (got := solve([1, 2, 3], [3])) == 1, f"{got=}" assert (got := solve([], [1, 2, 3])) == 0, f"{got=}" assert (got := solve([1, 1, 1], [])) == 0, f"{got=}" ``` # [Reshape the Matrix](https://leetle.app/?date=2025-10-07) In MATLAB, there is a handy function called `reshape` which can reshape an `m x n` matrix into a new one with different dimensions `r x c` while keeping its original data order. Given a matrix `mat` and two integers `r` and `c`, return the reshaped matrix. If the reshape operation is not possible, return the original matrix. ## Solution ``` Python def solve(c, mat, r): m, n = len(mat), len(mat[0]) if m * n != r * c: return mat new = [[None for _ in range(c)] for _ in range(r)] for i in range(m * n): new[i // c][i % c] = mat[i // n][i % n] return new ``` ## Test Cases ``` Python assert (got := solve(4, [[1, 2], [3, 4]], 1)) == [[1, 2, 3, 4]], f"{got=}" assert (got := solve(4, [[1, 2], [3, 4]], 2)) == [[1, 2], [3, 4]], f"{got=}" assert (got := solve(1, [[1, 2], [3, 4]], 4)) == [ [1], [2], [3], [4], ], f"{got=}" assert (got := solve(2, [[1, 2, 3], [4, 5, 6]], 3)) == [ [1, 2], [3, 4], [5, 6], ], f"{got=}" assert (got := solve(1, [[1]], 1)) == [[1]], f"{got=}" assert (got := solve(2, [[1, 2]], 1)) == [[1, 2]], f"{got=}" ``` # [Sort Array By Parity](https://leetle.app/?date=2025-10-08) Given an integer array `nums`, move all the even integers to the beginning of the array followed by all the odd integers. Return the resulting array. Maintain the original relative order within the even group and within the odd group for deterministic results. ## Solution ``` Python def solve(nums): return sorted(nums, key=lambda x: x % 2) ``` ## Test Cases ``` Python assert (got := solve([3, 1, 2, 4])) == [2, 4, 3, 1], f"{got=}" assert (got := solve([0])) == [0], f"{got=}" assert (got := solve([1])) == [1], f"{got=}" assert (got := solve([2, 2, 1, 1])) == [2, 2, 1, 1], f"{got=}" assert (got := solve([4, 3, 2, 1])) == [4, 2, 3, 1], f"{got=}" assert (got := solve([])) == [], f"{got=}" ``` # [Range Sum of BST](https://leetle.app/?date=2025-10-09) Given the `root` of a Binary Search Tree and two integers `low` and `high`, return the sum of values of all nodes with a value in the inclusive range `[low, high]`. Input is given as a level-order array where `None` represents no node. ## Solution ``` Python def solve(root, low, high): def dfs(i): if i >= len(root) or root[i] is None: return 0 if root[i] < low: return dfs(i * 2 + 2) if root[i] > high: return dfs(i * 2 + 1) return root[i] + dfs(i * 2 + 2) + dfs(i * 2 + 1) return dfs(0) ``` ## Test Cases ``` Python assert (got := solve([10, 5, 15, 3, 7, None, 18], 7, 15)) == 32, f"{got=}" assert (got := solve([10, 5, 15, 3, 7, 13, 18, 1, None, 6], 6, 10)) == 23, f"{got=}" assert (got := solve([1], 1, 1)) == 1, f"{got=}" assert (got := solve([5, 3, 8, 2, 4, 6, 10], 4, 9)) == 23, f"{got=}" assert (got := solve([], 1, 2)) == 0, f"{got=}" assert (got := solve([7, 3, 9, 2, 5, 8, 10], 11, 12)) == 0, f"{got=}" ``` # [Sum of Square Numbers](https://leetle.app/?date=2025-10-10) Given a non-negative integer `c`, return `True` if there exist two integers `a` and `b` such that `a^2 + b^2 = c`, otherwise return `False`. ## Solution ``` Python def solve(c): s = set() for i in range(c): if i**2 > c: break s.add(i**2) if (c - i**2) in s: return True return False if c > 1 else True ``` ## Test Cases ``` Python assert (got := solve(5)) is True, f"{got=}" assert (got := solve(3)) is False, f"{got=}" assert (got := solve(0)) is True, f"{got=}" assert (got := solve(1)) is True, f"{got=}" assert (got := solve(4)) is True, f"{got=}" assert (got := solve(100)) is True, f"{got=}" ``` # [Find the Town Judge](https://leetle.app/?date=2025-10-11) In a town, there are `n` people labeled from `1` to `n`. There is a rumor that one of these people is secretly the town judge. If the town judge exists, then: 1. The town judge trusts nobody. 2. Everybody (except for the town judge) trusts the town judge. 3. There is exactly one person that satisfies properties 1 and 2. You are given an array `trust` where `trust[i] = [a, b]` represents that person `a` trusts person `b`. Return the label of the town judge if exists, or `-1` otherwise. Similar to [153 Find the Celebrity](#findthecelebrity). ## Solution ``` Python def solve(n, trust): td = {(a, b): True for a, b in trust} return { 0: i for i in range(1, n + 1) if sum(td.get((j + 1, i), False) for j in range(n)) == n - 1 and sum(td.get((i, j + 1), False) for j in range(n)) == 0 }.get(0, -1) ``` ## Test Cases ``` Python assert (got := solve(2, [[1, 2]])) == 2, f"{got=}" assert (got := solve(3, [[1, 3], [2, 3]])) == 3, f"{got=}" assert (got := solve(3, [[1, 3], [2, 3], [3, 1]])) == -1, f"{got=}" assert (got := solve(1, [])) == 1, f"{got=}" assert (got := solve(4, [[1, 3], [1, 4], [2, 3], [2, 4], [4, 3]])) == 3, f"{got=}" assert (got := solve(3, [[1, 2], [2, 3]])) == -1, f"{got=}" ``` # [Remove All Adjacent Duplicates in String](https://leetle.app/?date=2025-10-12) You are given a string `s`. Repeatedly remove adjacent duplicate characters from the string. Return the final string after all such duplicate removals have been made. ## Solution ``` Python def solve(s): cs = [] for c in s: if cs and c == cs[-1]: cs.pop() else: cs.append(c) return "".join(cs) ``` ## Test Cases ``` Python assert (got := solve("abbaca")) == "ca", f"{got=}" assert (got := solve("azxxzy")) == "ay", f"{got=}" assert (got := solve("a")) == "a", f"{got=}" assert (got := solve("aa")) == "", f"{got=}" assert (got := solve("abcd")) == "abcd", f"{got=}" assert (got := solve("aabbcc")) == "", f"{got=}" ``` # [Longest Palindrome](https://leetle.app/?date=2025-10-13) Given a string `s` which consists of lowercase or uppercase letters, return the length of the longest palindrome that can be built with those letters. Letters are case sensitive. ## Solution ``` Python from collections import Counter def solve(s): even, odd = map(sum, zip(*[divmod(i, 2) for i in Counter(s).values()])) return even * 2 + bool(odd) ``` ## Test Cases ``` Python assert (got := solve("abccccdd")) == 7, f"{got=}" assert (got := solve("a")) == 1, f"{got=}" assert (got := solve("bb")) == 2, f"{got=}" assert (got := solve("abc")) == 1, f"{got=}" assert (got := solve("Aa")) == 1, f"{got=}" assert (got := solve("aabbcc")) == 6, f"{got=}" ``` # [Find Words That Can Be Formed by Characters](https://leetle.app/?date=2025-10-14) You are given an array of strings `words` and a string `chars`. A string is good if it can be formed by characters from `chars` (each character can only be used once). Return the sum of lengths of all good strings in `words`. ## Solution ``` Python def solve(words, chars): cc = {i: chars.count(i) for i in chars} return sum(len(w) for w in words if all(w.count(i) <= cc.get(i, 0) for i in set(w))) ``` ## Test Cases ``` Python assert (got := solve(["cat", "bt", "hat", "tree"], "atach")) == 6, f"{got=}" assert (got := solve(["hello", "world", "leetcode"], "welldonehoneyr")) == 10, f"{got=}" assert (got := solve(["a", "b", "c"], "abc")) == 3, f"{got=}" assert (got := solve(["dog", "cat"], "xyz")) == 0, f"{got=}" assert (got := solve(["aa", "aaa"], "aaaa")) == 5, f"{got=}" assert (got := solve([], "abc")) == 0, f"{got=}" ``` # [Maximum Depth of N-ary Tree](https://leetle.app/?date=2025-10-15) Given an n-ary tree represented as a nested list structure where each node is `[value, [child1, child2, ...]]`, return the maximum depth of the tree. The depth is the number of nodes along the longest path from the root to the farthest leaf. An empty tree has depth 0. ## Solution ``` Python def solve(root): result = 0 if not root or not root[1]: return int(bool(root)) for child in root[1]: result = max(result, solve(child)) return result + 1 ``` ## Test Cases ``` Python assert (got := solve([1, [[3, [[5, []], [6, []]]], [2, []], [4, []]]])) == 3, f"{got=}" assert (got := solve([])) == 0, f"{got=}" assert (got := solve([1, []])) == 1, f"{got=}" assert (got := solve([1, [[2, [[3, [[4, []]]]]]]])) == 4, f"{got=}" assert (got := solve([1, [[2, []], [3, []], [4, []], [5, []]]])) == 2, f"{got=}" assert (got := solve([1, [[2, [[3, []]]]]])) == 3, f"{got=}" ``` # [Remove Element](https://leetle.app/?date=2025-10-16) Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in `nums` in-place. Return the number of elements in `nums` which are not equal to `val`. The relative order of elements may be changed. ## Solution ``` Python def solve(nums, val): while val in nums: nums.remove(val) return len(nums) ``` ## Test Cases ``` Python assert (got := solve([3, 2, 2, 3], 3)) == 2, f"{got=}" assert (got := solve([0, 1, 2, 2, 3, 0, 4, 2], 2)) == 5, f"{got=}" assert (got := solve([], 1)) == 0, f"{got=}" assert (got := solve([1], 1)) == 0, f"{got=}" assert (got := solve([1, 2, 3], 4)) == 3, f"{got=}" assert (got := solve([1, 1, 1], 1)) == 0, f"{got=}" ``` # [License Key Formatting](https://leetle.app/?date=2025-10-17) You are given a string `s` that consists of alphanumeric characters and dashes. The string is separated into `n + 1` groups by `n` dashes. You are also given an integer `k`. Reformat the string so that each group contains exactly `k` characters, except for the first group, which could be shorter but still must contain at least one character. Dashes should be inserted between groups and all lowercase letters should be converted to uppercase. Return the reformatted string. ## Solution ``` Python def solve(s, k): s = s.replace("-", "").upper() f = (len(s) - 1) % k + 1 r = [s[:f]] for i in range(f, len(s), k): r.append(s[i : i + k]) return "-".join(r) ``` ## Test Cases ``` Python assert (got := solve("5F3Z-2e-9-w", 4)) == "5F3Z-2E9W", f"{got=}" assert (got := solve("2-5g-3-J", 2)) == "2-5G-3J", f"{got=}" assert (got := solve("2-4A0r7-4k", 3)) == "24-A0R-74K", f"{got=}" assert (got := solve("a-a-a-a-", 1)) == "A-A-A-A", f"{got=}" assert (got := solve("AB-CD-EF", 3)) == "ABC-DEF", f"{got=}" assert (got := solve("a", 2)) == "A", f"{got=}" ``` # [Add Digits](https://leetle.app/?date=2025-10-18) Given an integer `num`, repeatedly add all its digits until the result has only one digit, and return it. ## Solution ``` Python def solve(num): while num > 9: num = sum(int(i) for i in str(num)) return num ``` ## Test Cases ``` Python assert (got := solve(38)) == 2, f"{got=}" assert (got := solve(0)) == 0, f"{got=}" assert (got := solve(9)) == 9, f"{got=}" assert (got := solve(10)) == 1, f"{got=}" assert (got := solve(99)) == 9, f"{got=}" assert (got := solve(123)) == 6, f"{got=}" ``` # [Minimum Absolute Difference in BST](https://leetle.app/?date=2025-10-19) Given the `root` of a Binary Search Tree represented as a level-order array, return the minimum absolute difference between the values of any two different nodes in the tree. ## Solution ``` Python def solve(root): def iot(node, m, p): if not node: return m return iot(node.right, min(iot(node.left, m, p), node.val - p), node.val) return iot(root, 999999, -999999) ``` ## Test Cases ``` Python class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right def bt(items, index=0): if len(items) <= 0 or len(items) <= index: return None elif items[index] is None: items.insert(2 * index + 1, None) items.insert(2 * index + 2, None) return None node = TreeNode(items[index]) node.left = bt(items, 2 * index + 1) node.right = bt(items, 2 * index + 2) return node assert (got := solve(bt([4, 2, 6, 1, 3]))) == 1, f"{got=}" assert (got := solve(bt([1, 0, 48, None, None, 12, 49]))) == 1, f"{got=}" assert (got := solve(bt([5, 3, 7]))) == 2, f"{got=}" assert (got := solve(bt([10, 5, 15, 3, 7, 13, 18, 1]))) == 2, f"{got=}" assert (got := solve(bt([1]))) == 999999, f"{got=}" assert (got := solve(bt([2, 1, 3]))) == 1, f"{got=}" ``` # [Find the Duplicate Number](https://leetle.app/?date=2025-10-20) Given an array of integers containing n + 1 integers where each integer is in the range [1, n] inclusive, there is exactly one duplicate number. Find and return this duplicate number. You must solve the problem without modifying the array nums and use only constant extra space. ## Solution ``` Python def solve(nums): for n in nums: if nums.count(n) > 1: return n ``` ## Test Cases ``` Python assert (got := solve([1, 3, 4, 2, 2])) == 2, f"{got=}" assert (got := solve([3, 1, 3, 4, 2])) == 3, f"{got=}" assert (got := solve([1, 1])) == 1, f"{got=}" assert (got := solve([1, 1, 2])) == 1, f"{got=}" assert (got := solve([2, 2, 2, 2, 2])) == 2, f"{got=}" assert (got := solve([1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 10])) == 10, f"{got=}" ``` # [Missing Number (Again)](https://leetle.app/?date=2025-10-21) Given an array `nums` containing `n` distinct numbers in the range `[0, n]`, return the only number in the range that is missing from the array. See [4 Missing Number](#missingnumber). ## Solution ``` Python from missing_number_004 import solve ``` ## Test Cases ``` Python assert (got := solve([3, 0, 1])) == 2, f"{got=}" assert (got := solve([0, 1])) == 2, f"{got=}" assert (got := solve([9, 6, 4, 2, 3, 5, 7, 0, 1])) == 8, f"{got=}" assert (got := solve([0])) == 1, f"{got=}" assert (got := solve([1])) == 0, f"{got=}" assert (got := solve([1, 2])) == 0, f"{got=}" ``` # [First Bad Version](https://leetle.app/?date=2025-10-22) You are a product manager and currently leading a team to develop a new product. Unfortunately, the latest version of your product fails the quality check. Since each version is developed based on the previous version, all the versions after a bad version are also bad. Suppose you have `n` versions [1, 2, ..., n] and you want to find out the first bad one, which causes all the following ones to be bad. You are given an API `bool isBadVersion(version)` which returns whether version is bad. Implement a function to find the first bad version. You should minimize the number of calls to the API. ## Solution ``` Python def solve(n): def isBadVersion(version): return version >= 1 left, right = 1, n while left < right: mid = left + (right - left) // 2 if isBadVersion(mid): right = mid else: left = mid + 1 return left ``` ## Test Cases ``` Python assert (got := solve(5)) == 1, f"{got=}" assert (got := solve(1)) == 1, f"{got=}" assert (got := solve(2)) == 1, f"{got=}" assert (got := solve(3)) == 1, f"{got=}" assert (got := solve(10)) == 1, f"{got=}" assert (got := solve(100)) == 1, f"{got=}" ``` # [Search Insert Position (Again)](https://leetle.app/?date=2025-10-23) Given a sorted array of distinct integers and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order. You must write an algorithm with O(log n) runtime complexity. See [273 Search Insert Position](#searchinsertposition). ## Solution ``` Python from search_insert_position_273 import solve ``` ## Test Cases ``` Python assert (got := solve([1, 3, 5, 6], 5)) == 2, f"{got=}" assert (got := solve([1, 3, 5, 6], 2)) == 1, f"{got=}" assert (got := solve([1, 3, 5, 6], 7)) == 4, f"{got=}" assert (got := solve([1, 3, 5, 6], 0)) == 0, f"{got=}" assert (got := solve([1], 0)) == 0, f"{got=}" assert (got := solve([1], 1)) == 0, f"{got=}" ``` # [Squares of a Sorted Array (Again)](https://leetle.app/?date=2025-10-24) Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order. See [246 Squares of a Sorted Array](#squaresofasortedarray). ## Solution ``` Python from squares_of_a_sorted_array_246 import solve ``` ## Test Cases ``` Python assert (got := solve([-4, -1, 0, 3, 10])) == [0, 1, 9, 16, 100], f"{got=}" assert (got := solve([-7, -3, 2, 3, 11])) == [4, 9, 9, 49, 121], f"{got=}" assert (got := solve([1, 2, 3, 4, 5])) == [1, 4, 9, 16, 25], f"{got=}" assert (got := solve([-5, -4, -3, -2, -1])) == [1, 4, 9, 16, 25], f"{got=}" assert (got := solve([0])) == [0], f"{got=}" assert (got := solve([-1, 0, 1])) == [0, 1, 1], f"{got=}" ``` # [Rotate Array (Again)](https://leetle.app/?date=2025-10-25) Given an integer array `nums`, rotate the array to the right by `k` steps, where `k` is non-negative. See [56 Rotate Array](#rotatearray). ## Solution ``` Python from rotate_array_cyclic_056 import solve ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 4, 5, 6, 7], 3)) == [ 5, 6, 7, 1, 2, 3, 4, ], f"{got=}" assert (got := solve([-1, -100, 3, 99], 2)) == [3, 99, -1, -100], f"{got=}" assert (got := solve([1, 2], 1)) == [2, 1], f"{got=}" assert (got := solve([1, 2, 3], 0)) == [1, 2, 3], f"{got=}" assert (got := solve([1], 1)) == [1], f"{got=}" assert (got := solve([1, 2, 3, 4, 5], 5)) == [1, 2, 3, 4, 5], f"{got=}" ``` # [Move Zeroes (Again)](https://leetle.app/?date=2025-10-26) Given an integer array `nums`, move all `0`'s to the end of it while maintaining the relative order of the non-zero elements. Note that you must do this in-place without making a copy of the array. See [104 Move Zeroes](#movezeroes). ## Solution ``` Python from move_zeroes_104 import solve ``` ## Test Cases ``` Python assert (got := solve([0, 1, 0, 3, 12])) == [1, 3, 12, 0, 0], f"{got=}" assert (got := solve([0])) == [0], f"{got=}" assert (got := solve([1, 2, 3, 4, 5])) == [1, 2, 3, 4, 5], f"{got=}" assert (got := solve([0, 0, 0, 1, 2])) == [1, 2, 0, 0, 0], f"{got=}" assert (got := solve([1, 0, 2, 0, 3])) == [1, 2, 3, 0, 0], f"{got=}" assert (got := solve([0, 0, 0])) == [0, 0, 0], f"{got=}" ``` # [Two Sum II - Input Array Is Sorted](https://leetle.app/?date=2025-10-27) Given a 1-indexed array of integers numbers that is already sorted in non-decreasing order, find two numbers such that they add up to a specific target number. Let these two numbers be `numbers[index1]` and `numbers[index2]` where `1 <= index1 < index2 <= numbers.length`. Return the indices of the two numbers, `index1` and `index2`, added by one as an integer array ``[index1, index2]`` of length 2. The tests are generated such that there is exactly one solution. You may not use the same element twice. ## Solution ``` Python def solve(numbers, target): lo, hi = 0, len(numbers) - 1 while lo < hi: if numbers[lo] + numbers[hi] == target: return [lo + 1, hi + 1] lo, hi = (lo + 1, hi) if numbers[lo] + numbers[hi] < target else (lo, hi - 1) ``` ## Test Cases ``` Python assert (got := solve([2, 7, 11, 15], 9)) == [1, 2], f"{got=}" assert (got := solve([2, 3, 4], 6)) == [1, 3], f"{got=}" assert (got := solve([-1, 0], -1)) == [1, 2], f"{got=}" assert (got := solve([1, 2, 3, 4, 5], 8)) == [3, 5], f"{got=}" assert (got := solve([1, 2], 3)) == [1, 2], f"{got=}" assert (got := solve([5, 25, 75], 100)) == [2, 3], f"{got=}" ``` # [Remove Element (Again)](https://leetle.app/?date=2025-10-28) Given an integer array `nums` and an integer `val`, remove all occurrences of `val` in-place. The order of the elements may be changed. Then return the number of elements in `nums` which are not equal to `val`. Consider the number of elements in `nums` which are not equal to `val` be `k`, to get accepted, you need to do the following things: - Change the array `nums` such that the first `k` elements of `nums` contain the elements which are not equal to `val`. - Return `k`. See [289 Remove Element](#removeelement). ## Solution ``` Python from remove_element_289 import solve ``` ## Test Cases ``` Python assert (got := solve([3, 2, 2, 3], 3)) == 2, f"{got=}" assert (got := solve([0, 1, 2, 2, 3, 0, 4, 2], 2)) == 5, f"{got=}" assert (got := solve([1], 1)) == 0, f"{got=}" assert (got := solve([1, 2, 3, 4], 5)) == 4, f"{got=}" assert (got := solve([2, 2, 2, 2], 2)) == 0, f"{got=}" assert (got := solve([1, 2, 3, 4, 5], 3)) == 4, f"{got=}" ``` # [Plus One](https://leetle.app/?date=2025-10-29) You are given a large integer represented as an integer array digits, where each digits[i] is the ith digit of the integer. The digits are ordered from most significant to least significant in left-to-right order. The large integer does not contain any leading zeros. Increment the large integer by one and return the resulting array of digits. ## Solution ``` Python def solve(digits): for i, digit in reversed([*enumerate(digits)]): carry, digits[i] = divmod(digit + 1, 10) if not carry: break else: digits.insert(0, carry) return digits ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3])) == [1, 2, 4], f"{got=}" assert (got := solve([4, 3, 2, 1])) == [4, 3, 2, 2], f"{got=}" assert (got := solve([9])) == [1, 0], f"{got=}" assert (got := solve([9, 9, 9])) == [1, 0, 0, 0], f"{got=}" assert (got := solve([1, 9, 9])) == [2, 0, 0], f"{got=}" assert (got := solve([0])) == [1], f"{got=}" ``` # [Minimum Path Sum](https://leetle.app/?date=2025-10-30) Given a `m x n` grid filled with non-negative numbers, find a path from top left to bottom right, which minimizes the sum of all numbers along its path. Note: You can only move either down or right at any point in time. ## Solution ``` Python def solve(grid): m, n = len(grid), len(grid[0]) for r in range(1, m): grid[r][0] += grid[r - 1][0] for c in range(1, n): grid[0][c] += grid[0][c - 1] for r in range(1, m): for c in range(1, n): grid[r][c] += min(grid[r - 1][c], grid[r][c - 1]) return grid[m - 1][n - 1] ``` ## Test Cases ``` Python assert (got := solve([[1, 3, 1], [1, 5, 1], [4, 2, 1]])) == 7, f"{got=}" assert (got := solve([[1, 2, 3], [4, 5, 6]])) == 12, f"{got=}" assert (got := solve([[1]])) == 1, f"{got=}" assert (got := solve([[1, 2], [1, 1]])) == 3, f"{got=}" assert (got := solve([[5, 1, 1], [1, 1, 1], [1, 1, 5]])) == 13, f"{got=}" assert ( got := solve( [[1, 4, 8, 6, 2, 2], [1, 5, 9, 3, 1, 7], [4, 2, 2, 1, 8, 3], [1, 5, 3, 2, 1, 4]] ) ) == 18, f"{got=}" ``` # [Coin Change (Again)](https://leetle.app/?date=2025-10-31) You are given an integer array `coins` representing coins of different denominations and an integer `amount` representing a total amount of money. Return the fewest number of coins needed to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1. See [264 Coin Change](#coinchange). ## Solution ``` Python from coin_change_264 import solve ``` ## Test Cases ``` Python assert (got := solve([1, 2, 5], 11)) == 3, f"{got=}" assert (got := solve([2], 3)) == -1, f"{got=}" assert (got := solve([1], 0)) == 0, f"{got=}" assert (got := solve([1, 3, 4], 6)) == 2, f"{got=}" assert (got := solve([1, 5, 10, 25], 63)) == 6, f"{got=}" assert (got := solve([2, 5, 10], 1)) == -1, f"{got=}" ``` # [Longest Increasing Path in Matrix](https://leetle.app/?date=2025-11-01) Given an `m x n` integers matrix, return the length of the longest increasing path in the matrix. From each cell, you can either move in four directions: left, right, up, or down. You may not move diagonally or move outside the boundary. ## Solution ``` Python def solve(matrix): def dfs(i, j, result=1): for di, dj in [(0, -1), (1, 0), (0, 1), (-1, 0)]: ni, nj = i + di, j + dj if 0 <= ni < m and 0 <= nj < n and matrix[ni][nj] > matrix[i][j]: result = max(result, dfs(ni, nj) + 1) return result m, n = len(matrix), len(matrix[0]) return max(dfs(i, j) for i in range(m) for j in range(n)) ``` ## Test Cases ``` Python assert (got := solve([[9, 9, 4], [6, 6, 8], [2, 1, 1]])) == 4, f"{got=}" assert (got := solve([[3, 4, 5], [3, 2, 6], [2, 2, 1]])) == 4, f"{got=}" assert (got := solve([[1]])) == 1, f"{got=}" assert (got := solve([[1, 2], [4, 3]])) == 4, f"{got=}" assert (got := solve([[7, 8, 9], [9, 7, 6], [7, 2, 3]])) == 6, f"{got=}" assert (got := solve([[1, 2, 3], [8, 9, 4], [7, 6, 5]])) == 9, f"{got=}" ``` # [Trapping Rain Water](https://leetle.app/?date=2025-11-02) Given `n` non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining. ## Solution ``` Python def solve(height): result, lo, hi = 0, 1, len(height) - 2 lo_max, hi_max = height[lo - 1], height[hi + 1] while lo <= hi: if hi_max <= lo_max: result += max(hi_max - height[hi], 0) hi_max = max(hi_max, height[hi]) hi -= 1 else: result += max(lo_max - height[lo], 0) lo_max = max(lo_max, height[lo]) lo += 1 return result ``` ## Test Cases ``` Python assert (got := solve([0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1])) == 6, f"{got=}" assert (got := solve([4, 2, 0, 3, 2, 5])) == 9, f"{got=}" assert (got := solve([3, 0, 2, 0, 4])) == 7, f"{got=}" assert (got := solve([1, 2, 3, 4, 5])) == 0, f"{got=}" assert (got := solve([5, 4, 3, 2, 1])) == 0, f"{got=}" assert (got := solve([3, 1, 2, 4, 1, 3, 1])) == 5, f"{got=}" ``` # [Find Median from Data Stream](https://leetle.app/?date=2025-11-03) The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values. Implement a function that receives a list of numbers and returns the median. ## Solution ``` Python def solve(nums): nums, x = sorted(nums), len(nums) return nums[x // 2] if x % 2 else (nums[x // 2 - 1] + nums[x // 2]) / 2 ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 4, 5])) == 3, f"{got=}" assert (got := solve([1, 2, 3, 4])) == 2.5, f"{got=}" assert (got := solve([5])) == 5, f"{got=}" assert (got := solve([1, 2])) == 1.5, f"{got=}" assert (got := solve([3, 1, 4, 1, 5, 9, 2, 6])) == 3.5, f"{got=}" assert (got := solve([10, 20, 30])) == 20, f"{got=}" ``` # [Word Break (Again)](https://leetle.app/?date=2025-11-04) Given a string `s` and a dictionary of strings `wordDict`, return `True` if `s` can be segmented into a space-separated sequence of one or more dictionary words. Note that the same word in the dictionary may be reused multiple times in the segmentation. See [269 Word Break](#wordbreak). ## Solution ``` Python from word_break_269 import solve ``` ## Test Cases ``` Python assert (got := solve("leetcode", ["leet", "code"])) is True, f"{got=}" assert (got := solve("applepenapple", ["apple", "pen"])) is True, f"{got=}" assert (got := solve("catsandog", ["cats", "dog", "sand", "and", "cat"])) is False, ( f"{got=}" ) assert (got := solve("a", ["a"])) is True, f"{got=}" assert (got := solve("ab", ["a", "b"])) is True, f"{got=}" assert (got := solve("cars", ["car", "ca", "rs"])) is True, f"{got=}" ``` # [Subsets](https://leetle.app/?date=2025-11-05) Given an integer array `nums` of unique elements, return all possible subsets (the power set). The solution set must not contain duplicate subsets. *Return the solution in any order*. ## Solution ``` Python def solve(nums): result = [[]] for n in nums: result += [i + [n] for i in result] return result ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3])) == [ [], [1], [2], [1, 2], [3], [1, 3], [2, 3], [1, 2, 3], ], f"{got=}" assert (got := solve([0])) == [[], [0]], f"{got=}" assert (got := solve([1, 2])) == [[], [1], [2], [1, 2]], f"{got=}" assert (got := solve([5, 6])) == [[], [5], [6], [5, 6]], f"{got=}" assert (got := solve([7])) == [[], [7]], f"{got=}" assert (got := solve([1, 2, 4])) == [ [], [1], [2], [1, 2], [4], [1, 4], [2, 4], [1, 2, 4], ], f"{got=}" ``` # [Rotate String](https://leetle.app/?date=2025-11-06) Given two strings `s` and `goal`, return `True` if and only if `s` can become goal after some number of shifts on `s`. A shift on `s` consists of moving the leftmost character of `s` to the rightmost position. For example, if `s = "abcde"`, then it will be `"bcdea"` after one shift. ## Solution ``` Python def solve(s, goal): return goal in s * 2 ``` ## Test Cases ``` Python assert (got := solve("abcde", "cdeab")) is True, f"{got=}" assert ( got := solve( "abcde", "abced", ) ) is False, f"{got=}" assert (got := solve("hello", "llohe")) is True, f"{got=}" assert (got := solve("abc", "abc")) is True, f"{got=}" assert (got := solve("abc", "bca")) is True, f"{got=}" assert (got := solve("abcde", "abcdef")) is False, f"{got=}" ``` # [Encode and Decode Strings](https://leetle.app/?date=2025-11-07) Design an algorithm to encode a list of strings to a single string. The encoded string is then decoded back to the original list of strings. Implement a function that takes a list of strings and returns an encoded string, then decodes it back. For this challenge, return the decoded list after encoding the input. ## Solution ``` Python def solve(strs): return eval(repr(strs), {}) ``` ## Test Cases ``` Python assert (got := solve(["hello", "world"])) == ["hello", "world"], f"{got=}" assert (got := solve([""])) == [""], f"{got=}" assert (got := solve(["a", "b", "c"])) == ["a", "b", "c"], f"{got=}" assert (got := solve(["hello", "", "world"])) == ["hello", "", "world"], f"{got=}" assert (got := solve(["test#123", "data"])) == ["test#123", "data"], f"{got=}" assert (got := solve(["single"])) == ["single"], f"{got=}" ``` # [Maximum Product of Word Lengths](https://leetle.app/?date=2025-11-08) Given a string array `words`, return the maximum value of `length(word[i]) * length(word[j])` where the two words do not share common letters. If no such two words exist, return 0. ## Solution ``` Python def solve(words): letters, result = [set(i) for i in words], 0 for i, word in enumerate(words): for j in range(i): if not letters[i] & letters[j]: result = max(result, len(word) * len(words[j])) return result ``` ## Test Cases ``` Python assert (got := solve(["abcw", "baz", "foo", "bar", "xtfn", "abcdef"])) == 16, f"{got=}" assert (got := solve(["a", "ab", "abc", "d", "cd", "bcd", "abcd"])) == 4, f"{got=}" assert (got := solve(["a", "aa", "aaa", "aaaa"])) == 0, f"{got=}" assert (got := solve(["abc", "def", "ghi"])) == 9, f"{got=}" assert ( got := solve(["eae", "ea", "aaf", "bda", "fcf", "dc", "ac", "ce", "cefde", "dabae"]) ) == 15, f"{got=}" assert (got := solve(["ab", "cd"])) == 4, f"{got=}" ``` # [Sort Array By Parity (Again)](https://leetle.app/?date=2025-11-09) Given an integer array `nums`, move all the even integers to the beginning of the array followed by all the odd integers. Return any array that satisfies this condition. The relative order within even and odd numbers should be preserved. See [281 Sort Array By Parity](#sortarraybyparity). ## Solution ``` Python from sort_array_by_parity_281 import solve ``` ## Test Cases ``` Python assert (got := solve([3, 1, 2, 4])) == [2, 4, 3, 1], f"{got=}" assert (got := solve([0])) == [0], f"{got=}" assert (got := solve([1, 3, 5, 7])) == [1, 3, 5, 7], f"{got=}" assert (got := solve([2, 4, 6, 8])) == [2, 4, 6, 8], f"{got=}" assert (got := solve([1, 2, 3, 4, 5, 6])) == [2, 4, 6, 1, 3, 5], f"{got=}" assert (got := solve([8, 7, 6, 5, 4, 3, 2, 1])) == [8, 6, 4, 2, 7, 5, 3, 1], f"{got=}" ``` # [Implement Trie (Prefix Tree)](https://leetle.app/?date=2025-11-10) A trie (prefix tree) is a tree data structure used to efficiently store and retrieve keys in a dataset of strings. Implement a function `solve(operations, values)` that performs a series of operations on a Trie and returns the results. Operations: - "insert": Insert a word into the trie - "search": Return True if the word is in the trie - "startsWith": Return True if there's any word with the given prefix ## Solution ``` Python def solve(operations, values): start, result = {}, [] for operation, value in zip(operations, values): current = start for char in value: if char not in current: if operation == "insert": current[char] = {} else: result.append(False) break current = current[char] else: if operation == "search": result.append("end" in current) elif operation == "startsWith": result.append(True) if operation == "insert": current["end"] = True result.append(None) return result ``` ## Test Cases ``` Python assert ( got := solve( ["insert", "search", "search", "startsWith"], ["apple", "apple", "app", "app"] ) ) == [None, True, False, True], f"{got=}" assert (got := solve(["insert", "insert", "search"], ["hello", "world", "hello"])) == [ None, None, True, ], f"{got=}" assert (got := solve(["insert", "startsWith"], ["test", "te"])) == [None, True], ( f"{got=}" ) assert (got := solve(["insert", "search", "startsWith"], ["a", "a", "a"])) == [ None, True, True, ], f"{got=}" assert ( got := solve(["insert", "insert", "search", "search"], ["cat", "car", "cat", "dog"]) ) == [None, None, True, False], f"{got=}" assert ( got := solve(["insert", "startsWith", "startsWith"], ["programming", "pro", "code"]) ) == [None, True, False], f"{got=}" ``` # [Merge K Sorted Lists](https://leetle.app/?date=2025-11-11) You are given an array of `k` sorted linked-lists. Merge all the linked-lists into one sorted linked-list and return it. For this problem, treat each list as a simple Python/JavaScript list. Merge all lists into a single sorted list. ## Solution ``` Python def solve(lists): return sorted(j for i in lists for j in i) ``` ## Test Cases ``` Python assert (got := solve([[1, 4, 5], [1, 3, 4], [2, 6]])) == [1, 1, 2, 3, 4, 4, 5, 6], ( f"{got=}" ) assert (got := solve([[]])) == [], f"{got=}" assert (got := solve([[1], [2], [3]])) == [1, 2, 3], f"{got=}" assert (got := solve([[1, 2, 3], [4, 5, 6]])) == [1, 2, 3, 4, 5, 6], f"{got=}" assert (got := solve([[], [1]])) == [1], f"{got=}" assert (got := solve([[5], [1], [3], [7]])) == [1, 3, 5, 7], f"{got=}" ``` # [Find the Duplicate Number (Again)](https://leetle.app/?date=2025-11-12) Given an array of integers `nums` containing `n + 1` integers where each integer is in the range `[1, n]` inclusive, there is exactly one repeated number. Return this repeated number. You must solve this without modifying the array and uses only constant extra space. See [293 Find the Duplicate Number](#findtheduplicatenumber). ## Solution ``` Python from find_the_duplicate_number_293 import solve ``` ## Test Cases ``` Python assert (got := solve([1, 3, 4, 2, 2])) == 2, f"{got=}" assert (got := solve([3, 1, 3, 4, 2])) == 3, f"{got=}" assert (got := solve([1, 1])) == 1, f"{got=}" assert (got := solve([2, 5, 9, 6, 9, 3, 8, 9, 7, 1, 4])) == 9, f"{got=}" assert (got := solve([1, 1, 2])) == 1, f"{got=}" assert (got := solve([4, 3, 1, 4, 2])) == 4, f"{got=}" ``` # [Generate Parentheses](https://leetle.app/?date=2025-11-13) Given `n` pairs of parentheses, write a function to generate all combinations of well-formed parentheses. Return the result in sorted order. ## Solution ``` Python def solve(n): dp = [[""]] + [[] for i in range(n)] for i in range(n + 1): for j in range(i): new = [] for x in dp[j]: for y in dp[i - j - 1]: new.append("(" + x + ")" + y) dp[i] += new return sorted(dp[n]) ``` ## Test Cases ``` Python assert (got := solve(3)) == ["((()))", "(()())", "(())()", "()(())", "()()()"], ( f"{got=}" ) assert (got := solve(1)) == ["()"], f"{got=}" assert (got := solve(2)) == ["(())", "()()"], f"{got=}" assert (got := solve(4)) == [ "(((())))", "((()()))", "((())())", "((()))()", "(()(()))", "(()()())", "(()())()", "(())(())", "(())()()", "()((()))", "()(()())", "()(())()", "()()(())", "()()()()", ], f"{got=}" assert (got := solve(0)) == [""], f"{got=}" assert (got := solve(5)) == [ "((((()))))", "(((()())))", "(((())()))", "(((()))())", "(((())))()", "((()(())))", "((()()()))", "((()())())", "((()()))()", "((())(()))", "((())()())", "((())())()", "((()))(())", "((()))()()", "(()((())))", "(()(()()))", "(()(())())", "(()(()))()", "(()()(()))", "(()()()())", "(()()())()", "(()())(())", "(()())()()", "(())((()))", "(())(()())", "(())(())()", "(())()(())", "(())()()()", "()(((())))", "()((()()))", "()((())())", "()((()))()", "()(()(()))", "()(()()())", "()(()())()", "()(())(())", "()(())()()", "()()((()))", "()()(()())", "()()(())()", "()()()(())", "()()()()()", ], f"{got=}" ``` # [Next Permutation](https://leetle.app/?date=2025-11-14) A permutation of an array of integers is an arrangement of its members into a sequence or linear order. Implement a function to rearrange the numbers into the lexicographically next greater permutation. If no such arrangement exists, rearrange to the lowest possible order (sorted in ascending order). The replacement must be in-place and return the modified array. ## Solution ``` Python def solve(nums): i = len(nums) - 2 while i >= 0 and nums[i] >= nums[i + 1]: i -= 1 if i >= 0: j = len(nums) - 1 while nums[j] <= nums[i]: j -= 1 nums[i], nums[j] = nums[j], nums[i] nums[i + 1 :] = reversed(nums[i + 1 :]) return nums ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3])) == [1, 3, 2], f"{got=}" assert (got := solve([3, 2, 1])) == [1, 2, 3], f"{got=}" assert (got := solve([1, 1, 5])) == [1, 5, 1], f"{got=}" assert (got := solve([1])) == [1], f"{got=}" assert (got := solve([1, 3, 2])) == [2, 1, 3], f"{got=}" assert (got := solve([2, 3, 1])) == [3, 1, 2], f"{got=}" ``` # [Min Stack](https://leetle.app/?date=2025-11-15) Design a stack that supports push, pop, top, and retrieving the minimum element. Implement a function `solve(operations, values)` that performs a series of operations and returns the results. Operations: - "push": Push value onto stack (returns None) - "pop": Remove top element (returns None) - "top": Get the top element (returns the value) - "getMin": Get the minimum element (returns the value) ## Solution ``` Python def solve(operations, values): stack, results = [], [] for operation, value in zip(operations, values): match operation: case "push": results.append(stack.append(value)) case "pop": stack.pop() results.append(None) case "top": results.append(stack[-1]) case "getMin": results.append(min(stack)) return results ``` ## Test Cases ``` Python assert ( got := solve( ["push", "push", "push", "getMin", "pop", "top", "getMin"], [-2, 0, -3, None, None, None, None], ) ) == [None, None, None, -3, None, 0, -2], f"{got=}" assert (got := solve(["push", "push", "getMin"], [1, 2, None])) == [None, None, 1], ( f"{got=}" ) assert (got := solve(["push", "getMin", "push", "getMin"], [5, None, 3, None])) == [ None, 5, None, 3, ], f"{got=}" assert (got := solve(["push", "push", "pop", "getMin"], [10, 20, None, None])) == [ None, None, None, 10, ], f"{got=}" assert ( got := solve( ["push", "push", "push", "getMin", "pop", "getMin"], [3, 1, 2, None, None, None] ) ) == [None, None, None, 1, None, 1], f"{got=}" assert (got := solve(["push", "top", "getMin"], [7, None, None])) == [None, 7, 7], ( f"{got=}" ) ``` # [Largest Number At Least Twice of Others](https://leetle.app/?date=2025-11-16) You are given an integer array `nums` where the largest integer is unique. Determine whether the largest element in the array is at least twice as much as every other number in the array. If it is, return the index of the largest element, otherwise return `-1`. ## Solution ``` Python def solve(nums): if len(nums) < 2: return 0 b, a = sorted(nums)[-2:] return nums.index(a) if a >= 2 * b else -1 ``` ## Test Cases ``` Python assert (got := solve([3, 6, 1, 0])) == 1, f"{got=}" assert (got := solve([1, 2, 3, 4])) == -1, f"{got=}" assert (got := solve([1])) == 0, f"{got=}" assert (got := solve([0, 0, 0, 1])) == 3, f"{got=}" assert (got := solve([10, 2, 3, 4])) == 0, f"{got=}" assert (got := solve([5, 3, 2, 9])) == -1, f"{got=}" ``` # [Partition Equal Subset Sum](https://leetle.app/?date=2025-11-17) Given an array of positive integers `nums`, return `True` if you can partition the array into two subsets such that the sum of elements in both subsets is equal. ## Solution ``` Python def solve(nums): quotient, remainder = divmod(sum(nums), 2) if remainder: return False dp = [True] + [False] * quotient for num in nums: for j in range(quotient, num - 1, -1): dp[j] = dp[j] or dp[j - num] return dp[quotient] ``` ## Test Cases ``` Python assert (got := solve([1, 5, 11, 5])) is True, f"{got=}" assert (got := solve([1, 2, 3, 5])) is False, f"{got=}" assert (got := solve([1, 1])) is True, f"{got=}" assert (got := solve([1, 2, 5])) is False, f"{got=}" assert (got := solve([2, 2, 2, 2])) is True, f"{got=}" assert (got := solve([100])) is False, f"{got=}" ``` # [Reverse Only Letters](https://leetle.app/?date=2025-11-18) Given a string `s`, reverse the string according to the following rules: - All the characters that are not English letters remain in the same position. - All the English letters (lowercase or uppercase) should be reversed. Return the modified string. ## Solution ``` Python def solve(s): letters = filter(str.isalpha, reversed(s)) return "".join(next(letters) if i.isalpha() else i for i in s) ``` ## Test Cases ``` Python assert (got := solve("ab-cd")) == "dc-ba", f"{got=}" assert (got := solve("a-bC-dEf-ghIj")) == "j-Ih-gfE-dCba", f"{got=}" assert (got := solve("Test1ng-Leet=code-Q!")) == "Qedo1ct-eeLg=ntse-T!", f"{got=}" assert (got := solve("abc")) == "cba", f"{got=}" assert (got := solve("a-b-c")) == "c-b-a", f"{got=}" assert (got := solve("123")) == "123", f"{got=}" ``` # [Combinations](https://leetle.app/?date=2025-11-19) Given two integers `n` and `k`, return all possible combinations of `k` numbers chosen from the range `[1, n]`. You may return the answer in any order. ## Solution ``` Python from itertools import combinations def solve(n, k): return [list(i) for i in combinations(range(1, n + 1), k)] ``` ## Test Cases ``` Python assert (got := solve(4, 2)) == [[1, 2], [1, 3], [1, 4], [2, 3], [2, 4], [3, 4]], ( f"{got=}" ) assert (got := solve(1, 1)) == [[1]], f"{got=}" assert (got := solve(5, 1)) == [[1], [2], [3], [4], [5]], f"{got=}" assert (got := solve(3, 3)) == [[1, 2, 3]], f"{got=}" assert (got := solve(2, 1)) == [[1], [2]], f"{got=}" assert (got := solve(3, 2)) == [[1, 2], [1, 3], [2, 3]], f"{got=}" ``` # [Permutations II](https://leetle.app/?date=2025-11-20) Given a collection of numbers, `nums`, that might contain duplicates, return all possible unique permutations in any order. ## Solution ``` Python from itertools import permutations def solve(nums): return sorted(list(i) for i in set(permutations(nums))) ``` ## Test Cases ``` Python assert (got := solve([1, 1, 2])) == [[1, 1, 2], [1, 2, 1], [2, 1, 1]], f"{got=}" assert (got := solve([1, 2, 3])) == [ [1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1], ], f"{got=}" assert (got := solve([1])) == [[1]], f"{got=}" assert (got := solve([1, 1])) == [[1, 1]], f"{got=}" assert (got := solve([2, 2, 1, 1])) == [ [1, 1, 2, 2], [1, 2, 1, 2], [1, 2, 2, 1], [2, 1, 1, 2], [2, 1, 2, 1], [2, 2, 1, 1], ], f"{got=}" assert (got := solve([1, 1, 1])) == [[1, 1, 1]], f"{got=}" ``` # [Combination Sum](https://leetle.app/?date=2025-11-21) Given an array of distinct integers `candidates` and a target integer `target`, return a list of all unique combinations of `candidates` where the chosen numbers sum to `target`. The same number may be chosen from `candidates` an unlimited number of times. ## Solution ``` Python from itertools import combinations_with_replacement def solve(candidates, target): return sorted( list(j) for i in range(target) for j in combinations_with_replacement(candidates, i + 1) if sum(j) == target ) ``` ## Test Cases ``` Python assert (got := solve([2, 3, 6, 7], 7)) == [[2, 2, 3], [7]], f"{got=}" assert (got := solve([2, 3, 5], 8)) == [[2, 2, 2, 2], [2, 3, 3], [3, 5]], f"{got=}" assert (got := solve([2], 1)) == [], f"{got=}" assert (got := solve([1], 1)) == [[1]], f"{got=}" assert (got := solve([1], 2)) == [[1, 1]], f"{got=}" assert (got := solve([3, 5, 8], 11)) == [[3, 3, 5], [3, 8]], f"{got=}" ``` # [Search in Rotated Sorted Array II](https://leetle.app/?date=2025-11-22) There is an integer array `nums` sorted in non-decreasing order (not necessarily with distinct values). Before being passed to your function, `nums` is rotated at an unknown pivot index `k` (0 <= k < nums.length). Given the array `nums` after the rotation and an integer `target`, return true if target is in `nums`, or false otherwise. ## Solution ``` Python def solve(nums, target): return target in nums ``` ## Test Cases ``` Python assert (got := solve([2, 5, 6, 0, 0, 1, 2], 0)) is True, f"{got=}" assert (got := solve([2, 5, 6, 0, 0, 1, 2], 3)) is False, f"{got=}" assert (got := solve([1, 0, 1, 1, 1], 0)) is True, f"{got=}" assert (got := solve([1], 1)) is True, f"{got=}" assert (got := solve([1], 0)) is False, f"{got=}" assert ( got := solve([1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1], 2) ) is True, f"{got=}" ``` # [Palindrome Partitioning](https://leetle.app/?date=2025-11-23) Given a string `s`, partition `s` such that every substring of the partition is a palindrome. Return all possible palindrome partitioning of `s`. ## Solution ``` Python def solve(s): def recurse(start, result): if start == len(s): results.append(result[:]) else: for i in range(start + 1, len(s) + 1): if s[start:i] == s[start:i][::-1]: result.append(s[start:i]) recurse(i, result) result.pop() results = [] recurse(0, []) return results ``` ## Test Cases ``` Python assert (got := solve("aab")) == [["a", "a", "b"], ["aa", "b"]], f"{got=}" assert (got := solve("a")) == [["a"]], f"{got=}" assert (got := solve("ab")) == [["a", "b"]], f"{got=}" assert (got := solve("aaa")) == [["a", "a", "a"], ["a", "aa"], ["aa", "a"], ["aaa"]], ( f"{got=}" ) assert (got := solve("efe")) == [["e", "f", "e"], ["efe"]], f"{got=}" assert (got := solve("bb")) == [["b", "b"], ["bb"]], f"{got=}" ``` # [Top K Frequent Elements (Again)](https://leetle.app/?date=2025-11-24) Given an integer array `nums` and an integer `k`, return the `k` most frequent elements. You may return the answer in any order. See [265 Top K Frequent Elements](#topkfrequentelements). ## Solution ``` Python from top_k_frequent_elements_265 import solve ``` ## Test Cases ``` Python assert (got := solve([1, 1, 1, 2, 2, 3], 2)) == [1, 2], f"{got=}" assert (got := solve([1], 1)) == [1], f"{got=}" assert (got := solve([1, 2], 2)) == [1, 2], f"{got=}" assert (got := solve([4, 1, -1, 2, -1, 2, 3], 2)) == [-1, 2], f"{got=}" assert (got := solve([1, 1, 1, 2, 2, 2, 3, 3, 3], 3)) == [1, 2, 3], f"{got=}" assert (got := solve([5, 5, 5, 2, 2, 1], 1)) == [5], f"{got=}" ``` # [Car Fleet](https://leetle.app/?date=2025-11-25) There are `n` cars going to the same destination along a one-lane road. The destination is `target` miles away. You are given two integer arrays `position` and `speed`, both of length `n`, where `position[i]` is the position of the `i`th car and `speed[i]` is its speed (in miles per hour). A car can never pass another car ahead of it, but it can catch up to it and drive bumper to bumper at the same speed. The faster car will slow down to match the slower car's speed. The distance between these two cars is ignored (they are assumed to be at the same position). A car fleet is some non-empty set of cars driving at the same position and same speed. Note that a single car is also a car fleet. If a car catches up to a car fleet at the destination point, it will still be considered as one car fleet. Return the number of car fleets that will arrive at the destination. ## Solution ``` Python def solve(target, position, speed): cars = sorted(range(len(speed)), reverse=True, key=lambda i: position[i]) result, c = len(speed) + 1, cars[0] for i in cars: if (target - position[i]) / speed[i] <= (target - position[c]) / speed[c]: result -= 1 else: c = i return result ``` ## Test Cases ``` Python assert (got := solve(12, [10, 8, 0, 5, 3], [2, 4, 1, 1, 3])) == 3, f"{got=}" assert (got := solve(10, [3], [3])) == 1, f"{got=}" assert (got := solve(100, [0, 2, 4], [4, 2, 1])) == 1, f"{got=}" assert (got := solve(10, [0, 4, 2], [2, 1, 3])) == 1, f"{got=}" assert (got := solve(10, [6, 8], [3, 2])) == 2, f"{got=}" assert (got := solve(10, [8, 6], speed=[2, 3])) == 2, f"{got=}" ``` # [Lemonade Change](https://leetle.app/?date=2025-11-26) At a lemonade stand, each lemonade costs $5. Customers are standing in a queue to buy from you, and order one at a time (in the order specified by bills). Each customer will only buy one lemonade and pay with either a $5, $10, or $20 bill. You must provide the correct change to each customer, so that the net transaction is that the customer pays $5. Note that you don't have any change in hand at first. Return true if and only if you can provide every customer with correct change. ## Solution ``` Python def solve(bills): five = ten = 0 for bill in bills: match bill: case 5: five += 1 case 10 if five: ten += 1 five -= 1 case 20 if five and ten: ten -= 1 five -= 1 case 20 if five >= 3: five -= 3 case _: return False return True ``` ## Test Cases ``` Python assert (got := solve([5, 5, 5, 10, 20])) is True, f"{got=}" assert (got := solve([5, 5, 10])) is True, f"{got=}" assert (got := solve([10, 10])) is False, f"{got=}" assert (got := solve([5, 5, 10, 10, 20])) is False, f"{got=}" assert (got := solve([5, 5, 5, 5, 20, 20, 5, 10, 5, 10])) is False, f"{got=}" assert (got := solve([5, 5, 5, 5, 10, 5, 10, 10, 10, 20])) is True, f"{got=}" ``` # [Kth Largest Element in a Stream](https://leetle.app/?date=2025-11-27) Design a class to find the `k`th largest element in a stream. Note that it is the `k`th largest element in the sorted order, not the `k`th distinct element. Implement `solve(commands, inputs)` which handles the class operations. Operations: - "KthLargest": Initializes the object with the integer `k` and the stream of integers `nums`. - "add": Appends the integer `val` to the stream and returns the element representing the `k`th largest element in the stream. ## Solution ``` Python import heapq class KthLargest: def __init__(self, k, nums): heapq.heapify(nums) self.k, self.nums = k, nums def add(self, val): heapq.heappush(self.nums, val) while len(self.nums) > self.k: heapq.heappop(self.nums) return self.nums[0] def solve(commands, inputs): results = [None] hq = KthLargest(*inputs[0]) for val in inputs[1:]: results.append(hq.add(*val)) return results ``` ## Test Cases ``` Python assert ( got := solve( ["KthLargest", "add", "add", "add", "add", "add"], [[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]], ) ) == [None, 4, 5, 5, 8, 8], f"{got=}" assert (got := solve(["KthLargest", "add", "add"], [[1, []], [-3], [-2]])) == [ None, -3, -2, ], f"{got=}" assert (got := solve(["KthLargest", "add", "add"], [[2, [0]], [-1], [1]])) == [ None, -1, 0, ], f"{got=}" assert (got := solve(["KthLargest", "add"], [[1, [10]], [20]])) == [None, 20], f"{got=}" assert (got := solve(["KthLargest", "add"], [[2, [10, 20]], [30]])) == [None, 20], ( f"{got=}" ) assert (got := solve(["KthLargest", "add", "add"], [[1, [5]], [1], [6]])) == [ None, 5, 6, ], f"{got=}" ``` # [Last Stone Weight](https://leetle.app/?date=2025-11-28) You are given an array of integers `stones` where `stones[i]` is the weight of the `i`th stone. We are playing a game with the stones. On each turn, we choose the heaviest two stones and smash them together. Suppose the heaviest two stones have weights `x` and `y` with `x <= y`. The result of this smash is: - If `x == y`, both stones are destroyed, and - If `x != y`, the stone of weight `x` is destroyed, and the stone of weight `y` has new weight `y - x`. At the end of the game, there is at most one stone left. Return the weight of the last remaining stone. If there are no stones left, return 0. ## Solution ``` Python import heapq def solve(stones): hq = [-s for s in stones] heapq.heapify(hq) while len(hq) > 1: a = -heapq.heappop(hq) b = -heapq.heappop(hq) if a != b: heapq.heappush(hq, -(a - b)) return -hq[0] if hq else 0 ``` ## Test Cases ``` Python assert (got := solve([2, 7, 4, 1, 8, 1])) == 1, f"{got=}" assert (got := solve([1])) == 1, f"{got=}" assert (got := solve([2, 2])) == 0, f"{got=}" assert (got := solve([1, 3])) == 2, f"{got=}" assert (got := solve([10, 4, 2, 10])) == 2, f"{got=}" assert (got := solve([1, 1, 1, 1, 1])) == 1, f"{got=}" ``` # [Sum of Digits in Base K](https://leetle.app/?date=2025-11-29) Given an integer `n` (in base 10) and a base `k`, return the sum of the digits of `n` after converting `n` from base 10 to base `k`. ## Solution ``` Python def solve(n, k): answer = 0 while n: n, r = divmod(n, k) answer += r return answer ``` ## Test Cases ``` Python assert (got := solve(34, 6)) == 9, f"{got=}" assert (got := solve(10, 10)) == 1, f"{got=}" assert (got := solve(100, 2)) == 3, f"{got=}" assert (got := solve(0, 5)) == 0, f"{got=}" assert (got := solve(15, 16)) == 15, f"{got=}" assert (got := solve(63, 8)) == 14, f"{got=}" ``` # [Number of Good Pairs](https://leetle.app/?date=2025-11-30) Given an array of integers `nums`, return the number of good pairs. A pair `(i, j)` is called good if `nums[i] == nums[j]` and `i < j`. ## Solution ``` Python from collections import Counter def solve(nums): return sum(i * (i - 1) // 2 for i in Counter(nums).values()) ``` ## Test Cases ``` Python assert (got := solve([1, 2, 3, 1, 1, 3])) == 4, f"{got=}" assert (got := solve([1, 1, 1, 1])) == 6, f"{got=}" assert (got := solve([1, 2, 3])) == 0, f"{got=}" assert (got := solve([1, 2, 3, 1, 2, 3])) == 3, f"{got=}" assert (got := solve([10, 1, 10])) == 1, f"{got=}" assert (got := solve([1, 1, 1, 2, 2])) == 4, f"{got=}" ``` # [Check If It Is a Straight Line](https://leetle.app/?date=2025-12-01) You are given an array `coordinates`, `coordinates[i] = [x, y]`, where `[x, y]` represents the coordinate of a point. Check if these points make a straight line in the XY plane. ## Solution ``` Python def solve(coordinates): (x0, y0), (x1, y1) = coordinates[:2] sx, sy = x1 - x0, y1 - y0 for x, y in coordinates[2:]: if (x - x0) * sy != (y - y0) * sx: return False return True ``` ## Test Cases ``` Python assert (got := solve([[1, 2], [2, 3], [3, 4], [4, 5], [5, 6], [6, 7]])) is True, ( f"{got=}" ) assert (got := solve([[1, 1], [2, 2], [3, 4], [4, 5], [5, 6], [7, 7]])) is False, ( f"{got=}" ) assert (got := solve([[0, 0], [0, 1], [0, -1]])) is True, f"{got=}" assert (got := solve([[1, 1], [2, 2], [3, 3]])) is True, f"{got=}" assert (got := solve([[0, 0], [1, 0], [2, 2]])) is False, f"{got=}" assert (got := solve([[1, 2], [2, 3], [3, 5]])) is False, f"{got=}" ``` # [Height Checker](https://leetle.app/?date=2025-12-02) A school is trying to take an annual photo of all the students. The students are asked to stand in a single file line in non-decreasing order by height. Let this ordering be represented by the integer array `expected` where `expected[i]` is the expected height of the `i`th student in line. You are given an integer array `heights` representing the current order that the students are standing in. Each `heights[i]` is the height of the `i`th student in line (0-indexed). Return the number of indices where `heights[i] != expected[i]`. ## Solution ``` Python def solve(heights): return sum(i != j for i, j in zip(heights, sorted(heights))) ``` ## Test Cases ``` Python assert (got := solve([1, 1, 4, 2, 1, 3])) == 3, f"{got=}" assert (got := solve([5, 1, 2, 3, 4])) == 5, f"{got=}" assert (got := solve([1, 2, 3, 4, 5])) == 0, f"{got=}" assert (got := solve([2, 1, 2, 1, 1, 2, 2, 1])) == 4, f"{got=}" assert (got := solve([10, 6, 6, 10, 10, 9, 8, 8, 5, 3, 8, 2, 6, 2, 9, 10])) == 14, ( f"{got=}" ) assert (got := solve([1])) == 0, f"{got=}" ``` # [Self Dividing Numbers](https://leetle.app/?date=2025-12-03) A self-dividing number is a number that is divisible by every digit it contains. For example, 128 is a self-dividing number because `128 % 1 == 0`, `128 % 2 == 0`, and `128 % 8 == 0`. A self-dividing number is not allowed to contain the digit zero. Given two integers `left` and `right`, return a list of all the self-dividing numbers in the range `[left, right]`. ## Solution ``` Python def solve(left, right): sdns = [] for i in range(left, right + 1): n, d = i, 1 while d: d, m = divmod(n, 10) if m == 0 or i % m: break n = d else: sdns.append(i) return sdns ``` ## Test Cases ``` Python assert (got := solve(1, 22)) == [1, 2, 3, 4, 5, 6, 7, 8, 9, 11, 12, 15, 22], f"{got=}" assert (got := solve(47, 85)) == [48, 55, 66, 77], f"{got=}" assert (got := solve(10, 15)) == [11, 12, 15], f"{got=}" assert (got := solve(1, 1)) == [1], f"{got=}" assert (got := solve(100, 105)) == [], f"{got=}" assert (got := solve(128, 128)) == [128], f"{got=}" ``` # [Maximum 69 Number](https://leetle.app/?date=2025-12-04) You are given a positive integer `num` consisting only of digits 6 and 9. Return the maximum number you can get by changing at most one digit (6 becomes 9, and 9 becomes 6). ## Solution ``` Python def solve(num): return int(str(num).replace("6", "9", 1)) ``` ## Test Cases ``` Python assert (got := solve(9669)) == 9969, f"{got=}" assert (got := solve(9996)) == 9999, f"{got=}" assert (got := solve(9999)) == 9999, f"{got=}" assert (got := solve(6666)) == 9666, f"{got=}" assert (got := solve(6)) == 9, f"{got=}" assert (got := solve(9)) == 9, f"{got=}" ``` # [Flipping an Image](https://leetle.app/?date=2025-12-05) Given an `n x n` binary matrix `image`, flip the image horizontally, then invert it, and return the resulting image. To flip an image horizontally means that each row of the image is reversed (for example, flipping `[1,1,0]` horizontally results in `[0,1,1]`). To invert an image means that each 0 is replaced by 1, and each 1 is replaced by 0 (for example, inverting `[0,1,1]` results in `[1,0,0]`). ## Solution ``` Python def solve(image): return [[1 - j for j in i[::-1]] for i in image] ``` ## Test Cases ``` Python assert (got := solve([[1, 1, 0], [1, 0, 1], [0, 0, 0]])) == [ [1, 0, 0], [0, 1, 0], [1, 1, 1], ], f"{got=}" assert (got := solve([[1, 1, 0, 0], [1, 0, 0, 1], [0, 1, 1, 1], [1, 0, 1, 0]])) == [ [1, 1, 0, 0], [0, 1, 1, 0], [0, 0, 0, 1], [1, 0, 1, 0], ], f"{got=}" assert (got := solve([[1]])) == [[0]], f"{got=}" assert (got := solve([[0]])) == [[1]], f"{got=}" assert (got := solve([[1, 0], [0, 1]])) == [[1, 0], [0, 1]], f"{got=}" assert (got := solve([[1, 1], [1, 1]])) == [[0, 0], [0, 0]], f"{got=}" ``` # [Robot Return to Origin](https://leetle.app/?date=2025-12-06) There is a robot starting at position (0, 0), the origin, on a 2D plane. Given a sequence of its moves, judge if this robot ends up at (0, 0) after it completes its moves. The move sequence is represented by a string, and the character `moves[i]` represents its `i`th move. Valid moves are 'R' (right), 'L' (left), 'U' (up), and 'D' (down). Return `True` if the robot returns to the origin after it finishes all of its moves, or false otherwise. ## Solution ``` Python def solve(moves): inv, todo = dict(zip("URDL", "DLUR")), [] for i in moves: if i in todo: todo.remove(i) else: todo.append(inv[i]) return not todo ``` ## Test Cases ``` Python assert (got := solve("UD")) is True, f"{got=}" assert (got := solve("LL")) is False, f"{got=}" assert (got := solve("RRDD")) is False, f"{got=}" assert (got := solve("LDRRLRUULR")) is False, f"{got=}" assert (got := solve("RLUURDDL")) is True, f"{got=}" assert (got := solve("")) is True, f"{got=}" ``` # [Merge Strings Alternately](https://leetle.app/?date=2025-12-07) You are given two strings `word1` and `word2`. Merge the strings by adding letters in alternating order, starting with `word1`. If a string is longer than the other, append the additional letters onto the end of the merged string. Return the merged string. ## Solution ``` Python from itertools import zip_longest def solve(word1, word2): return "".join("".join(i) for i in zip_longest(word1, word2, fillvalue="")) ``` ## Test Cases ``` Python assert (got := solve("abc", "pqr")) == "apbqcr", f"{got=}" assert (got := solve("ab", "pqrs")) == "apbqrs", f"{got=}" assert (got := solve("abcd", "pq")) == "apbqcd", f"{got=}" assert (got := solve("", "abc")) == "abc", f"{got=}" assert (got := solve("abc", "")) == "abc", f"{got=}" assert (got := solve("a", "b")) == "ab", f"{got=}" ``` # [Matrix Diagonal Sum](https://leetle.app/?date=2025-12-08) Given a square matrix `mat`, return the sum of the matrix diagonals. Only include the sum of all the elements on the primary diagonal and all the elements on the secondary diagonal that are not part of the primary diagonal. ## Solution ``` Python def solve(mat): n, result = len(mat), 0 for i in range(n): result += mat[i][i] if i != n - i - 1: result += mat[i][-i - 1] return result ``` ## Test Cases ``` Python assert (got := solve([[1, 2, 3], [4, 5, 6], [7, 8, 9]])) == 25, f"{got=}" assert (got := solve([[1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1], [1, 1, 1, 1]])) == 8, ( f"{got=}" ) assert (got := solve([[5]])) == 5, f"{got=}" assert (got := solve([[1, 2], [3, 4]])) == 10, f"{got=}" assert (got := solve([[7, 3, 1, 9], [3, 4, 6, 9], [6, 9, 6, 6], [9, 5, 8, 5]])) == 55, ( f"{got=}" ) assert (got := solve([[1, 0], [0, 1]])) == 2, f"{got=}" ``` !!!BWL: THE BEER-WARE LICENSE (Revision 42) Carlo~~@~~Miron~~.IT~~ wrote this file. As long as you retain this notice you can do whatever you want with this stuff. If we meet some day, and you think this stuff is worth it, you can buy me a beer in return. —㎝