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.
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
Given this information, we can use the properties of a
set or a
Given a string
s, find the first non-repeating character in it and return its index. If it does not exist, return
-1. An example is the word
leetcode where the
l only appears once, therefore returning
0 as result.
The obvious, but very slow, solution is to iterate over the string and then for ever character, check the whole string if the character appears again. This has a time complexity of
A better solution is to write all characters in a map and count the number of occurrences. This way, we can iterate again and simply look at the counter in the map. This yields a time complexity of
The task is to determine if a tree is symmetric, meaning mirrored along the
root node. The usual tree structure is given in form of a
The logic itself is quite straightforward look at two nodes and compare the values. If their respective values are the same look at both of their children and compare them. Repeat this process until every node is visited.
There are some special cases here that need to be handled. The left child can be
None while the right child is not and vice versa. If both children are
True and do not proceed because this means we reached a leaf node.
The task is to traverse a binary tree inorder. This means, that starting from the root node, nodes should be visited in the following order: left, self, right. With this knowledge it is easy to come up with a recursive algorithm.
The only special case that needs to be handled are the leaf nodes that don’t have any children. By still visiting the non-existing children and then returning an empty list (
) when a
None is encountered, the whole algorithm fits into two lines.
Runtime: 41 ms, faster than 70.32% of Python3 online submissions for Binary Tree Inorder Traversal.
Memory Usage: 13.8 MB, less than 60.08% of Python3 online submissions for Binary Tree Inorder Traversal.