Writing
-
Leetcode: Linked list cycle
Continue readingGiven the head of a linked list, determine if there is a cycle in the list. A cycle is defined as a chain of arbitrary length that point to the same node. As an added difficulty, the solution should have a space complexity of
O(1).The first observation is that the cycle can be of arbitrary length. Thus, saving the visited nodes in a set would have a space complexity of
O(n). Secondly, the numbers cannot be compared because numbers might be duplicated throughout the list. Instead, we need to compare the list objects themselves. -
Leetcode: Contains duplicate
Continue readingGiven an array of
nums, returnTrueif there is a duplicated number andFalseotherwise.The simple most solution I could find was to use a
setand then see for every number if it is already contained in the set. A map would have worked as well. The time complexity for this isO(n), assuming that the access to the hash set isO(1), it takes only one iteration over the whole list. -
Leetcode: Move zeros
Continue readingThe task is as follows: 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.
The last note is actually the important part. Without this, it would be easy to just use array splitting in Python and add a zero. This would look similar to this:
if nums[pos] == 0: nums = nums[:pos] + nums[pos+1:] + [0]This obviously overrides
numsand the change is no longer in place. The next best solution that I found was to delete the items at position I from the list and then add a zero to the end. It is important to note, that the index needs to be decremented by one in case a0is found to account for double0. The number of steps needs to always be increased. -
Leetcode: Reverse string
Continue readingReverse a string and only use one extra variable. The solution is straightforward with two pointers,
p1andp2. THe idea here is to start from both ends and incrementp1and decrementp2until both of them meet in the middle. To switch the values of variables without assigning a temporary variable, the notation ofa, b = b, acan be used. To convert a string into a list of characters, surroung the string with[*s]. -
Leetcode: Majority number
Continue readingGiven an array nums of size
n, return the majority element. The majority element is the element that appears more than⌊n / 2⌋times. You may assume that the majority element always exists in the array.Unfortunately, it is not clear from the description whether there are only two different numbers or multiple ones. Some of the solutions seem to suggest that there are only two different ones. The solution that I will show has a time complexity of
O(n)and a space complexity ofO(n)in the worst case, that is, if all the numbers appear exactly once.