Friedrich Ewald My Personal Website

Posts


  • Leetcode: Intersection of two arrays II

    Given two arrays, nums1 and nums2, return the intersection of those arrays in any order. The easiest way I was able to come up with was to sort the arrays first and then look at the beginning of the arrays. If both are equal, add the element to the output and pop the first element from each array. Otherwise, pop the smaller element of both arrays. Repeat this until one of the arrays is empty at which point there can be no more intersecting elements.

    Continue reading

  • Leetcode: Power of three

    Given a number n, check if this number is a power of three, that is that it can be represented by 3^x. A straightforward solution looks as follows. Multiply by 3 until we reach n. If we’re greater than n, return False, and True otherwise.

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

    Continue reading

  • Leetcode: Kth smallest element in matrix

    Given a n*n matrix, find the kth smallest element. Each row in the matrix is sorted in ascending order and independent of the other rows. Do not use O(n*n) space when solving this. One example matrix looks like this:

      1  5  9
     10 11 13
     12 13 15
    
    For k = 8 return 13 because 13 is the 8th smallest element.
    If we could use all the space we wanted, we could just perform an n-way merge sort on every row at once. This would work because the rows itself are sorted already. Afterwards, we would need to pick the kth element from the list and would be done.

    Continue reading

  • Leetcode: Copy list with random pointer

    Given a head of a list with pointers to next and a random element, copy the list to a new list without any random pointers pointing to the old list.

    # Definition for a Node.
    class Node:
      def __init__(self, x: int, next: 'Node' = None, random: 'Node' = None):
        self.val = int(x)
        self.next = next
        self.random = random

    Continue reading

  • Leetcode: Decode ways

    Characters can be encoded via different numbers. A -> 1, B -> 2, ..., Z -> 26. Given a string s of numbers, return the number of possible decodings. For example 12 can be decoded as A,B and as L.

    Continue reading

Page: 4 of 28