# Posts

• ## Leetcode: Contains duplicate

Given an array of `nums`, return `True` if there is a duplicated number and `False` otherwise. The simple most solution I could find was to use a `set` and 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 is `O(n)`, assuming that the access to the hash set is `O(1)`, it takes only one iteration over the whole list.

• ## Leetcode: Move zeros

The 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:

This obviously overrides `nums` and 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 a `0` is found to account for double `0`. The number of steps needs to always be increased.

• ## Leetcode: Reverse string

Reverse a string and only use one extra variable. The solution is straightforward with two pointers, `p1` and `p2`. THe idea here is to start from both ends and increment `p1` and decrement `p2` until both of them meet in the middle. To switch the values of variables without assigning a temporary variable, the notation of `a, b = b, a` can be used. To convert a string into a list of characters, surroung the string with `[*s]`.

• ## Leetcode: Majority number

Given 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 of `O(n)` in the worst case, that is, if all the numbers appear exactly once.

• ## Leetcode: Single number

Given a list of integers `[1,1,2]`, there is only one number which is not repeated. The numbers can be in any order. The minimum length of the array is `1`. Numbers can be negative or positive. The algorithm should have a time complexity of `O(n)` and a space complexity should be constant `O(1)`. Given this information, we can use the properties of a `set` or a `map`.

Page: 11 of 28