Writing
-
Leetcode: Word break
Continue readingGiven a string
sand a list ofwords, returnTrueif the string can be constructed from any combination of the words andFalseotherwise. The alphabet contains only lowercase English characters.My initial idea was to replace all occurrences of a
wordin the strings. The problem with this approach is that a stringaabbwith the words['ab']is considered valid, while it is not. I then tried on adding breaking characters (.) to prevent this. It worked although very slowly. -
Leetcode: Maximum product subarray
Continue readingGiven an array
numswith integer values-10 <= x <= 10, calculate the maximum consecutive product. For example, the array[2,3,-1,4]produces the maximum product6because2*3=6.The first obsveration that we can make is that whenever a
0is encountered, it sets the whole product to0. This means, if a0is somewhere in the middle of the array, we need to look at the left and right part individually because they cannot be connected.Secondly, an odd amount of negative numbers makes the whole product negative. Having
2,4,,6, … negative numbers will keep the product at the same amount (if all of them are-1) or increase it.Finally, since those numbers are all integers, the longer the chain of multiplied numbers, the higher to outcome.
-
Leetcode: Sort list
Continue readingGiven a single linked list, sort the values in ascending order.
# Example Input: (4)->(3)->(1)->(2) Output: (1)->(2)->(3)-(4) -
Leetcode: Gas station
Continue readingGiven two arrays,
gasandcostand an infinite tank, it costscosts[i]to go from one index to the other. The most a car can get gas isgas[i]. The task is to determine whether a car can go a full round for any possible starting point. The program should return the starting index if it is possible and-1if it is not possible to do so.Example:
gas = [1,1,2] cost = [2,1,1] # result: 2The result is
2, because we can start from index2, get2units of gas, and it costs us1unit to go to1, leaving us with1unit. Then we can get another unit which is exactly the required2units it takes us to get to1and from there we get1leaving us with0at2and completing the cycle. -
Leetcode: LRU cache
Continue readingGiven the following code skeleton, implement an LRU cache with a variable capacity. The time complexity for
getandputshould beO(1)respectively.class LRUCache: def __init__(self, capacity: int): pass def get(self, key: int) -> int: pass def put(self, key: int, value: int) -> None: passIn general, a cache is just a map which assigns keys to values. What makes a cache special is that values get evicted. This can be either after a certain time or when values are not used. In the case of an LRU cache, the least recently used element should be deleted once a cache reaches its predefined capacity.