Friedrich Ewald My Personal Website


  • Leetcode: House robber II

    Similar to “House Robber”, but now we have to assume that the houses are aligned in a circle and the last house is a neighbor of the first house.

    Continue reading

  • Leetcode: House robber

    Given an array of nums that represent the loot of a house robber, return the maximum amount of money a robber can steal. The only rule is that a robber can not steal from two neighboring houses. When looking at this problem, we can see that we want to maximize the number of houses that we rob from. Consider the following array: [0,1,0,1]. Our maximum profit is 2, because we can rob the house at index 1 and index 3. If we were to rob at index 0 and 2, we would only gain 0 profit. We cannot however simply compare the even versus the odd indices because there could also be the following situation: [10,5,5,10]. Here, it is advantageous to skip 2 instead of just skipping 1. We need to look at every step if we want to visit the one after the next or the one after this. We don’t need to look if we want to visit the one after this, because then we could also simply have visited the one after the next.

    Continue reading

  • Leetcode: Palindrome linked list

    Given the head of a linked list, determine if the linked list is a palindrome and return True if it is, False otherwise. For added difficulty, find an algorithm that runs in O(n) and uses O(1) space.

    Continue reading

  • 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

Page: 3 of 28