Tech — Work — Ramblings

by Mike Kalvas

Results: 34

  • Leetcode Minimum Amount of Time to Fill Cups

    2026-11-01 12:50

    #project

    You have a water dispenser that can dispense cold, warm, and hot water. Every second, you can either fill up 2 cups with different types of water, or 1 cup of any type of water.

    You are given a 0-indexed integer array amount of length 3 where amount[0], amount[1], and amount[2] denote the number of cold, warm, and hot water cups you need to fill respectively. Return the minimum number of seconds needed to fill up all the cups.

    Example 1:

    Input: amount = [1,4,2]
    Output: 4
    Explanation: One way to fill up the cups is:
    Second 1: Fill up a cold cup and a warm cup.
    Second 2: Fill up a warm cup and a hot cup.
    Second 3: Fill up a warm cup and a hot cup.
    Second 4: Fill up a warm cup.
    It can be proven that 4 is the minimum number of seconds needed.
    

    Example 2:

    Input: amount = [5,4,4]
    Output: 7
    Explanation: One way to fill up the cups is:
    Second 1: Fill up a cold cup, and a hot cup.
    Second 2: Fill up a cold cup, and a warm cup.
    Second 3: Fill up a cold cup, and a warm cup.
    Second 4: Fill up a warm cup, and a hot cup.
    Second 5: Fill up a cold cup, and a hot cup.
    Second 6: Fill up a cold cup, and a warm cup.
    Second 7: Fill up a hot cup.
    

    Continue reading

  • Leetcode Intersection of Two Arrays II

    2026-11-01 10:38

    #project

    Given two integer arrays nums1 and nums2, return an array containing their intersection. Include each value as many times as it occurs in both arrays, using the smaller of its two occurrence counts. The result may be in any order.

    Example 1:

    Input: nums1 = [1,2,2,1], nums2 = [2,2]
    Output: [2,2]
    

    Example 2:

    Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
    Output: [4,9]
    Explanation: [9,4] is also accepted.
    

    Constraints:

    • 1 <= nums1.length, nums2.length <= 1000
    • 0 <= nums1[i], nums2[i] <= 1000

    Follow-up:

    • How could you optimize the algorithm if the arrays were already sorted?
    • Which algorithm would you choose if nums1 were much smaller than nums2?
    • How would you handle nums2 stored on disk when memory cannot hold all of its elements at once?

    Solution

    The interesting wrinkle here is that we need to return the same number of copies of the intersecting value as there are in the array with fewer copies of that value. This takes away the simple path of converting to sets and taking the intersection.

    We can get an O(n⋅m) solution (in the worst case, where the arrays share no values at all) by simply walking the first array, checking the second for the value, and removing it from the second if we find it so we don't count it again.

    Continue reading

  • Leetcode Prime Number of Set Bits in Binary Representation

    2026-10-08 11:37

    #project

    Given two integers left and right, return the count of numbers in the inclusive range [left, right] having a prime number of set bits in their binary representation.

    Recall that the number of set bits an integer has is the number of 1's present when written in binary.

    • For example, 21 written in binary is 10101, which has 3 set bits.

    Example 1:

    Input: left = 6, right = 10
    Output: 4
    Explanation:
    6  -> 110 (2 set bits, 2 is prime)
    7  -> 111 (3 set bits, 3 is prime)
    8  -> 1000 (1 set bit, 1 is not prime)
    9  -> 1001 (2 set bits, 2 is prime)
    10 -> 1010 (2 set bits, 2 is prime)
    4 numbers have a prime number of set bits.
    

    Example 2:

    Input: left = 10, right = 15
    Output: 5
    Explanation:
    10 -> 1010 (2 set bits, 2 is prime)
    11 -> 1011 (3 set bits, 3 is prime)
    12 -> 1100 (2 set bits, 2 is prime)
    13 -> 1101 (3 set bits, 3 is prime)
    14 -> 1110 (3 set bits, 3 is prime)
    15 -> 1111 (4 set bits, 4 is not prime)
    5 numbers have a prime number of set bits.
    

    Constraints:

    • 1 <= left <= right <= 10^6
    • 0 <= right - left <= 10^4

    Solution

    This is a surprisingly deep problem even though it's very simple to get a satisfactory solution working.

    Continue reading

  • Leetcode Rotate Image

    2026-10-05 16:30

    #project

    You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

    You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

    Example 1:

    example 1 before and after image rotation

    Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
    Output: [[7,4,1],[8,5,2],[9,6,3]]
    

    Example 2:

    example 2 before and after image rotation

    Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
    Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]
    

    Constraints:

    • n == matrix.length == matrix[i].length
    • 1 <= n <= 20
    • -1000 <= matrix[i][j] <= 1000

    Solution

    For a given (i,j) pair, where i is the row and j is the column, we want to transform the value at that coordinate. Let's write down a 3x3 case and see if we can't glean the general formula from old position to new position.

    Continue reading

  • Leetcode Lexicographically Smallest String After a Swap

    2026-10-05 10:56

    #project

    Given a string s containing only digits, return the lexicographically smallest string that can be obtained after swapping adjacent digits in s with the same parity at most once.

    Digits have the same parity if both are odd or both are even. For example, 5 and 9, as well as 2 and 4, have the same parity, while 6 and 9 do not.

    Example 1:

    Input: s = "45320"
    Output: "43520"
    Explanation:
    `s[1] == '5'` and `s[2] == '3'` both have the same parity, and swapping them results in the lexicographically smallest string.
    

    Example 2:

    Input: s = "001"
    Output: "001"
    Explanation:
    There is no need to perform a swap because `s` is already the lexicographically smallest.
    

    Constraints:

    • 2 <= s.length <= 100
    • s consists only of digits.

    Solution

    I first read the sentence

    after swapping adjacent digits in s with the same parity at most once.

    as allowing us to do multiple swaps in the string but each digit could only participate in 1 swap. For the first example, this would mean that we would swap the 5 and 3 but then also swap the 2 and 0. I'm pretty sure this is in fact what this sentence means grammatically and the "correct" version is a classic example of a misplaced modifier. A clearer definition would be something like

    Continue reading

  • Leetcode Time Needed to Inform All Employees

    2026-09-28 15:20

    #project

    A company has n employees with a unique ID for each employee from 0 to n - 1. The head of the company is the one with headID.

    Each employee has one direct manager given in the manager array where manager[i] is the direct manager of the i-th employee, manager[headID] = -1. Also, it is guaranteed that the subordination relationships have a tree structure.

    The head of the company wants to inform all the company employees of an urgent piece of news. He will inform his direct subordinates, and they will inform their subordinates, and so on until all employees know about the urgent news.

    The i-th employee needs informTime[i] minutes to inform all of his direct subordinates (i.e., After informTime[i] minutes, all his direct subordinates can start spreading the news).

    Return the number of minutes needed to inform all the employees about the urgent news.

    Example 1:

    Input: n = 1, headID = 0, manager = [-1], informTime = [0]
    Output: 0
    Explanation: The head of the company is the only employee in the company.
    

    Example 2:

    graph representation of example 2

    Input: n = 6, headID = 2, manager = [2,2,-1,2,2,2], informTime = [0,0,1,0,0,0]
    
    [Continue reading](/notes/202609281520)
    
  • Leetcode Count Asterisks

    2026-09-28 12:44

    #project

    You are given a string s, where every two consecutive vertical bars '|' are grouped into a pair. In other words, the 1st and 2nd '|' make a pair, the 3rd and 4th '|' make a pair, and so forth.

    Return the number of '*' in s, excluding the* '*' between each pair of '|'.

    Note that each '|' will belong to exactly one pair.

    Example 1:

    Input: s = "l|*e*et|c**o|*de|"
    Output: 2
    Explanation: The considered characters are underlined: "l|*e*et|c**o|*de|".
    The characters between the first and second '|' are excluded from the answer.
    Also, the characters between the third and fourth '|' are excluded from the answer.
    There are 2 asterisks considered. Therefore, we return 2.
    

    Example 2:

    Input: s = "iamprogrammer"
    Output: 0
    Explanation: In this example, there are no asterisks in s. Therefore, we return 0.
    

    Example 3:

    Input: s = "yo|uar|e**|b|e***au|tifu|l"
    Output: 5
    Explanation: All 5 asterisks are outside of pairs
    

    Constraints:

    • 1 <= s.length <= 1000
    • s consists of lowercase English letters, vertical bars '|', and asterisks '*'.
    • s contains an even number of vertical bars '|'.

    Solution

    Continue reading

  • Leetcode Substring with Concatenation of All Words

    2026-09-24 10:55

    #project

    You are given a string s and an array of strings words. All the strings of words are of the same length.

    A concatenated string is a string that exactly contains all the strings of any permutation of words concatenated.

    • For example, if words = ["ab","cd","ef"], then "abcdef", "abefcd", "cdabef", "cdefab", "efabcd", and "efcdab" are all concatenated strings. "acdbef" is not a concatenated string because it is not the concatenation of any permutation of words.

    Return an array of the starting indices of all the concatenated substrings in s. You can return the answer in any order.

    Example 1:

    Input: s = "barfoothefoobarman", words = ["foo","bar"]
    Output: [0,9]
    Explanation:
    - The substring starting at 0 is `"barfoo"`. It is the concatenation of `["bar","foo"]` which is a permutation of `words`.  
    - The substring starting at 9 is `"foobar"`. It is the concatenation of `["foo","bar"]` which is a permutation of `words`.
    

    Example 2:

    Input: s = "wordgoodgoodgoodbestword", words = ["word","good","best","word"]
    Output: []
    Explanation:
    - There is no concatenated substring.
    

    Example 3:

    Input: s = "barfoofoobarthefoobarman", words = ["bar","foo","the"]
    
    [Continue reading](/notes/202609241055)
    
  • Leetcode Minimum Energy to Maintain Brightness

    2026-09-22 21:58

    #project

    You are given an integer n, representing n light bulbs arranged in a line and indexed from 0 to n - 1.

    You are also given an integer brightness and a 2D integer array intervals, where intervals[i] = [start_i, end_i] represents an inclusive time interval during which the lighting requirement must be satisfied.

    At each time unit, every bulb can independently be either on or off. A bulb that is on illuminates its own position and its adjacent positions, if they exist.

    The total illumination at a time unit is the number of illuminated positions. Each position is counted at most once.

    For every integer time unit covered by at least one interval in intervals, the total illumination must be at least brightness. At time units not covered by any interval, all bulbs may remain off. Each bulb that is on consumes 1 unit of energy for that time unit.

    Return an integer denoting the minimum total energy required.

    Example 1:

    Input: n = 5, brightness = 5, intervals = [[6,12]]
    Output: 14
    Explanation:
    - Turn on the light bulbs at positions 1 and 4.
    - Current state of line: `0 1 0 0 1`.
    - All 5 positions are illuminated, so the required brightness is reached.
    
    [Continue reading](/notes/202609222158)
    
  • Leetcode Reverse Prefix of Word

    2026-09-22 17:28

    #project

    Given a 0-indexed string word and a character ch, reverse the segment of word that starts at index 0 and ends at the index of the first occurrence of ch (inclusive). If the character ch does not exist in word, do nothing.

    • For example, if word = "abcdefd" and ch = "d", then you should reverse the segment that starts at 0 and ends at 3 (inclusive). The resulting string will be "dcbaefd".

    Return the resulting string.

    Example 1:

    Input: word = "abcdefd", ch = "d"
    Output: "dcbaefd"
    Explanation: The first occurrence of "d" is at index 3.
    Reverse the part of word from 0 to 3 (inclusive), the resulting string is "dcbaefd".
    

    Example 2:

    Input: word = "xyxzxe", ch = "z"
    Output: "zxyxxe"
    Explanation: The first and only occurrence of "z" is at index 3.
    Reverse the part of word from 0 to 3 (inclusive), the resulting string is "zxyxxe".
    

    Example 3:

    Input: word = "abcd", ch = "z"
    Output: "abcd"
    Explanation: "z" does not exist in word.
    You should not do any reverse operation, the resulting string is "abcd".
    

    Constraints:

    • 1 <= word.length <= 250
    • word consists of lowercase English letters.

    Continue reading

  • Leetcode Sum of Floored Pairs

    2026-09-17 10:30

    #project

    Given an integer array nums, return the sum of floor(nums[i] / nums[j]) for all pairs of indices 0 <= i, j < nums.length in the array. Since the answer may be too large, return it modulo 10^9 + 7.

    The floor() function returns the integer part of the division.

    Example 1:

    Input: nums = [2,5,9]
    Output: 10
    Explanation:
    floor(2 / 5) = floor(2 / 9) = floor(5 / 9) = 0
    floor(2 / 2) = floor(5 / 5) = floor(9 / 9) = 1
    floor(5 / 2) = 2
    floor(9 / 2) = 4
    floor(9 / 5) = 1
    We calculate the floor of the division for every pair of indices in the array then sum them up.
    

    Example 2:

    Input: nums = [7,7,7,7,7,7,7]
    Output: 49
    

    Constraints:

    • 1 <= nums.length <= 10^5
    • 1 <= nums[i] <= 10^5

    Other solutions

    Obviously this works but it's too slow.

    const MODULO: i64 = 1_000_000_007;
    
    pub fn sum_of_floored_pairs(nums: Vec<i32>) -> i32 {
        let mut sum: i64 = 0;
        for i in &nums {
            for j in &nums {
                sum += i / j;
            }
        }
        (sum % MODULO) as i32
    }
    

    So what's the trick? When we look at one denominator j we know that the floor-ed value will be constant for a range of numerators. For instance, with nums = [1, 2, 3, 10, 11, 12, 13, 20] and j = 10 we have [1, 2, 3], [10, 11, 12, 13], and [20] as the buckets corresponding to 0, 1, and 2. So the sum (for only j = 10) is 0*3 + 1*4 + 2*1. This also shows us that we can sort and ignore all numbers i < j.

    Continue reading

  • Leetcode Perfect Number

    2026-09-15 12:27

    #project

    A perfect number is a positive integer that is equal to the sum of its positive divisors, excluding the number itself. A divisor of an integer x is an integer that can divide x evenly.

    Given an integer n, return true if n is a perfect number, otherwise return false.

    Example 1:

    Input: num = 28
    Output: true
    Explanation: 28 = 1 + 2 + 4 + 7 + 14
    1, 2, 4, 7, and 14 are all divisors of 28.
    

    Example 2:

    Input: num = 7
    Output: false
    

    Constraints:

    • 1 <= num <= 10^8

    Solution

    The key insight to this one is that we only need to check up to the square root of a number since we can just add its pair when we find one. For instance, to get all the clean divisors of 28 we can check 1 through 6 since when we check 4 we also get 7 from the division check.

    Other than that, there's some bookkeeping for adding 1 and also not adding the number n itself (though we could instead check against 2n for a match). This definition also excludes 1 from being a perfect number so in the second version below we short circuit that.

    pub fn check_perfect_number(num: i32) -> bool {
    
    [Continue reading](/notes/202609151227)
    
  • Leetcode Number of Perfect Pairs

    2026-09-14 17:42

    #project

    You are given an integer array nums.

    A pair of indices (i, j) is called perfect if the following conditions are satisfied:

    • i < j
    • Let a = nums[i], b = nums[j]. Then:
      • min(|a - b|, |a + b|) <= min(|a|, |b|)
      • max(|a - b|, |a + b|) >= max(|a|, |b|)

    Return the number of distinct perfect pairs.

    Note: The absolute value |x| refers to the non-negative value of x.

    Example 1:

    Input: nums = [0,1,2,3]
    Output: 2
    Explanation:
    There are 2 perfect pairs
    
    (i, j) (a, b) min(abs(a − b), abs(a + b)) min(abs(a), abs(b)) max(abs(a − b), abs(a + b)) max(abs(a), abs(b))
    (1, 2) (1, 2) min(abs(1 − 2), abs(1 + 2)) = 1 1 max(abs(1 − 2), abs(1 + 2)) = 3 2
    (2, 3) (2, 3) min(abs(2 − 3), abs(2 + 3)) = 1 2 max(abs(2 − 3), abs(2 + 3)) = 5 3

    Example 2:

    Input: nums = [-3,2,-1,4]
    Output: 4
    Explanation:
    There are 4 perfect pairs
    

    | (i, j) | (a, b) | min(abs(a − b), abs(a + b)) | min(abs(a), abs(b)) | max(abs(a − b), abs(a + b)) | max(abs(a), abs(b)) |

    Continue reading

  • Leetcode Find Indices of Stable Mountains

    2026-09-14 11:14

    #project

    There are n mountains in a row, and each mountain has a height. You are given an integer array height where height[i] represents the height of mountain i, and an integer threshold.

    A mountain is called stable if the mountain just before it (if it exists) has a height strictly greater than threshold. Note that mountain 0 is not stable.

    Return an array containing the indices of all stable mountains in any order.

    Example 1:

    Input: height = [1,2,3,4,5], threshold = 2
    Output: [3,4]
    Explanation:
    - Mountain 3 is stable because height[2] == 3 is greater than threshold == 2.
    - Mountain 4 is stable because height[3] == 4 is greater than threshold == 2.
    

    Example 2:

    Input: height = [10,1,10,1,10], threshold = 3
    Output: [1,3]
    

    Example 3:

    Input: height = [10,1,10,1,10], threshold = 10
    Output: []
    

    Constraints:

    • 2 <= n == height.length <= 100
    • 1 <= height[i] <= 100
    • 1 <= threshold <= 100

    Solution

    This is as simple as it seems. Just figure out if the entry satisfies the predicate and add it to the list if it does.

    First pass, relatively naïve and non-"rusty"

    pub fn stable_mountains(height: Vec<i32>, threshold: i32) -> Vec<i32> {
    
    [Continue reading](/notes/202609141114)
    
  • Leetcode Maximum Number of Words You Can Type

    2026-09-12 16:50

    #project

    There is a malfunctioning keyboard where some letter keys do not work. All other keys on the keyboard work properly.

    Given a string text of words separated by a single space (no leading or trailing spaces) and a string brokenLetters of all distinct letter keys that are broken, return the number of words in text you can fully type using this keyboard.

    Example 1:

    Input: text = "hello world", brokenLetters = "ad"
    Output: 1
    Explanation: We cannot type "world" because the 'd' key is broken.
    

    Example 2:

    Input: text = "leet code", brokenLetters = "lt"
    Output: 1
    Explanation: We cannot type "leet" because the 'l' and 't' keys are broken.
    

    Example 3:

    Input: text = "leet code", brokenLetters = "e"
    Output: 0
    Explanation: We cannot type either word because the 'e' key is broken.
    

    Constraints:

    • 1 <= text.length <= 104
    • 0 <= brokenLetters.length <= 26
    • text consists of words separated by a single space without any leading or trailing spaces.
    • Each word only consists of lowercase English letters.
    • brokenLetters consists of distinct lowercase English letters.

    Solution

    For this problem we just need to look at every word and check if any of our broken letters are in them.

    Continue reading

  • Leetcode Find Closest Number to Zero

    2026-09-10 12:33

    #project

    Given an integer array nums of size n, return the number with the value closest to 0 in nums. If there are multiple answers, return the number with the largest value.

    Example 1:

    Input: nums = [-4,-2,1,4,8]
    Output: 1
    Explanation:
    The distance from -4 to 0 is |-4| = 4.
    The distance from -2 to 0 is |-2| = 2.
    The distance from 1 to 0 is |1| = 1.
    The distance from 4 to 0 is |4| = 4.
    The distance from 8 to 0 is |8| = 8.
    Thus, the closest number to 0 in the array is 1.
    

    Example 2:

    Input: nums = [2,-1,1]
    Output: 1
    Explanation: 1 and -1 are both the closest numbers to 0, so 1 being larger is returned.
    

    Constraints:

    • 1 <= n <= 1000
    • -105 <= nums[i] <= 105

    Solution

    This one is straightforward as a problem, but the simplicity of the solution relies on some cool Rust features to be so concise.

    pub fn find_closest_number(nums: Vec<i32>) -> i32 {
        nums.into_iter()
            .max_by_key(|&number| (Reverse(number.unsigned_abs()), number))
            .expect("nums is guaranteed to be non-empty")
    }
    

    First, we have a max_by_key function (there are similar functions like sort_by_key, min_by_key, and more) that will allow us to iterate through an iterator, provide some key for each element, and then only retain the max.

    Continue reading

  • Leetcode Split Strings by Separator

    2026-09-09 14:41

    #project

    Given an array of strings words and a character separator, split each string in words by separator.

    Return an array of strings containing the new strings formed after the splits, excluding empty strings.

    • separator is used to determine where the split should occur, but it is not included as part of the resulting strings.
    • A split may result in more than two strings.
    • The resulting strings must maintain the same order as they were initially given.

    Example 1:

    Input: words = ["one.two.three","four.five","six"], separator = "."
    Output: ["one","two","three","four","five","six"]
    Explanation: In this example we split as follows:
    
    "one.two.three" splits into "one", "two", "three"
    "four.five" splits into "four", "five"
    "six" splits into "six"
    
    Hence, the resulting array is ["one","two","three","four","five","six"].
    

    Example 2:

    Input: words = ["$easy$","$problem$"], separator = "$"
    Output: ["easy","problem"]
    Explanation: In this example we split as follows:
    
    "$easy$" splits into "easy" (excluding empty strings)
    "$problem$" splits into "problem" (excluding empty strings)
    
    Hence, the resulting array is ["easy","problem"].
    

    Example 3:

    Continue reading

  • Leetcode Split Array Into Maximum Number of Subarrays

    2026-08-31 15:01

    #project

    You are given an array nums consisting of non-negative integers.

    We define the score of subarray nums[l..r] such that l <= r as nums[l] AND nums[l + 1] AND ... AND nums[r] where AND is the bitwise AND operation.

    Consider splitting the array into one or more subarrays such that the following conditions are satisfied:

    • Each element of the array belongs to exactly one subarray.
    • The sum of scores of the subarrays is the minimum possible.

    Return the maximum number of subarrays in a split that satisfies the conditions above.

    A subarray is a contiguous part of an array.

    Example 1:

    Input: nums = [1,0,2,0,1,2]
    Output: 3
    Explanation: We can split the array into the following subarrays:
    - [1,0]. The score of this subarray is 1 AND 0 = 0.
    - [2,0]. The score of this subarray is 2 AND 0 = 0.
    - [1,2]. The score of this subarray is 1 AND 2 = 0.
    The sum of scores is 0 + 0 + 0 = 0, which is the minimum possible score that we can obtain.
    It can be shown that we cannot split the array into more than 3 subarrays with a total score of 0. So we return 3.
    

    Example 2:

    Input: nums = [5,7,1,3]
    Output: 1
    Explanation: We can split the array into one subarray: [5,7,1,3] with a score of 1, which is the minimum possible score that we can obtain.
    
    [Continue reading](/notes/202608311501)
    
  • Leetcode Top Travelers

    2026-08-31 11:09

    #project

    Table: Users

    +---------------+---------+
    | Column Name   | Type    |
    +---------------+---------+
    | id            | int     |
    | name          | varchar |
    +---------------+---------+
    id is the column with unique values for this table.
    name is the name of the user.
    

    Table: Rides

    +---------------+---------+
    | Column Name   | Type    |
    +---------------+---------+
    | id            | int     |
    | user_id       | int     |
    | distance      | int     |
    +---------------+---------+
    id is the column with unique values for this table.
    user_id is the id of the user who traveled the distance "distance".
    

    Write a solution to report the distance traveled by each user.

    Return the result table ordered by travelled_distance in descending order, if two or more users traveled the same distance, order them by their name in ascending order.

    The result format is in the following example.

    Example 1:

    Input:
    Users table:
    +------+-----------+
    | id   | name      |
    +------+-----------+
    | 1    | Alice     |
    | 2    | Bob       |
    | 3    | Alex      |
    | 4    | Donald    |
    | 7    | Lee       |
    | 13   | Jonathan  |
    | 19   | Elvis     |
    +------+-----------+
    Rides table:
    
    [Continue reading](/notes/202608311109)
    
  • Leetcode Find the Difference

    2026-08-24 13:38

    #project

    You are given two strings s and t.

    String t is generated by random shuffling string s and then add one more letter at a random position.

    Return the letter that was added to t.

    Example 1:

    Input: s = "abcd", t = "abcde"
    Output: "e"
    Explanation: 'e' is the letter that was added.
    

    Example 2:

    Input: s = "", t = "y"
    Output: "y"
    

    Constraints:

    • 0 <= s.length <= 1000
    • t.length == s.length + 1
    • s and t consist of lowercase English letters.

    Solution

    This one is really straightforward. We just create a frequency count of the characters in the string, then decrement them until we find the one that has an extra count.

    pub fn find_the_difference(s: String, t: String) -> char {
        let mut counts: HashMap<char, u16> = HashMap::with_capacity(26);
        for c in s.chars() {
            *counts.entry(c).or_default() += 1;
        }
    
        for c in t.chars() {
            match counts.get_mut(&c) {
                Some(count) if *count > 0 => *count -= 1,
                _ => return c,
            }
        }
    
        unreachable!("problem guarantees one char difference");
    }
    

    There is however a cool, different solution that uses xor on the character bytes.

    Continue reading

  • Leetcode Two Sum

    2026-08-21 13:29

    #project

    You are given an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.

    You may assume that each input would have exactly one solution, and you may not use the same element twice.

    You can return the answer in any order.

    Example 1:

    Input: nums = [2,7,11,15], target = 9
    Output: [0,1]
    Explanation: Because nums[0] + nums[1] == 9, we return [0, 1].
    

    Example 2:

    Input: nums = [3,2,4], target = 6
    Output: [1,2]
    

    Example 3:

    Input: nums = [3,3], target = 6
    Output: [0,1]
    

    Constraints:

    • 2 <= nums.length <= 10^4
    • -10^9 <= nums[i] <= 10^9
    • -10^9 <= target <= 10^9
    • Only one valid answer exists.

    Follow-up: Can you come up with an algorithm that is less than O(n^2) time complexity?

    Solution

    The trick to get a better than O(n2) complexity is to understand that as we go through the list of integers, we can keep track of the numbers we see. Then in the future, we check if that number was in the list.

    For instance, if we have the array [1, 7, 8, 4, 9] and the target is 5. When we read the first number 1, we store that we've seen it. Then when we see 4 we check if 5 - 4 = 1 is in the list of seen numbers, find it, and get our match.

    Continue reading

  • Leetcode

    Programming puzzles

    2026-08-21 13:28

    #wip #project #structure

    A centralized list of some Leetcode problems I've solved with write-up explanations and interesting learning deep dives.

  • Advent of Code 2024 Day 11

    Plutonian Pebbles

    2024-12-11 00:00

    #project #blog #tech

    Today we're visiting the ancient civilization on Pluto from 2019 day 20 and find some interesting physics-defying stones.

  • Advent of Code 2024 Day 10

    Hoof It

    2024-12-10 00:00

    #blog #project

    Today we're back at the Lava Production Facility from 2023 day 15 helping reindeer find the best hiking routes around their floating island.

  • Advent of Code 2024 Day 09

    Disk Fragmenter

    2024-12-09 00:00

    #project #blog

    Today we're back under the sea with our amphipod friends from 2021 day 23 and need to help one of them defragment their hard drive.

  • Advent of Code 2024 Day 08

    Resonant Collinearity

    2024-12-08 00:00

    #blog #project

    Today we're visiting the roof of a top-secret Easter Bunny installation and need to put a stop to their plot to get people to buy Easter Bunny brand Imitation Mediocre Chocolate as a Christmas gift.

  • Advent of Code 2024 Day 07

    Bridge Repair

    2024-12-07 00:00

    #project #blog

    Today we're visiting the rope bridge from 2022 day 9 and need to help the elves repair it by sorting out there test calculations.

  • Advent of Code 2024 Day 06

    Guard Gallivant

    2024-12-06 00:00

    #blog #project

    Today we visit the suit manufacturing plant from 2018 day 5 and need to avoid creating time paradoxes by hiding from the guard.

  • Advent of Code 2024 Day 05

    Print Queue

    2024-12-05 00:00

    #project #blog

    Today we found the printer from 2017 day 1 and need to help sort it out.

  • Advent of Code 2024 Day 04

    Ceres Search

    2024-12-04 00:00

    #blog #project

    Today were visiting the Ceres monitoring station from 2019 day 10 and helping the station chief solve her word searches.

  • Advent of Code 2024 Day 03

    Mull It Over

    2024-12-03 00:00

    #project #blog

    Today we're visiting the toboggan rental shop from 2020 day 2 and need to help the elves with corrupted data in their computers.

  • Advent of Code 2024 Day 02

    Red-Nosed Report

    2024-12-02 00:00

    #blog #project

    We've made it to our first location in our search for the chief elf historian, the reindeer reactor from 2015 day 19. The reindeer need some help finding out which series of readings from their reactor are safe.

  • Advent of Code 2024 Day 01

    Historian Hysteria

    2024-12-01 00:00

    #blog #project

    This year finds us helping elf historians track down their chief historian who has gone missing and needs to be back for the sleigh launch on Christmas. Today we're comparing lists of numbers for historians.

  • Advent of Code 2024

    A season of code

    2024-11-30 23:59

    #structure #blog #project #tech

    We're back for another year or saving Christmas through the power of programming.