Given an unsorted array of positive integers, find the length of the longest subarray whose elements when sorted are continuous. Can you think of an O(n) solution?
Examp
The first is O(nlog(n))
in time and O(n)
space, the second is O(n)
in time and O(n)
in space, and the third is O(n)
in time and O(1)
in space.
build a binary search tree
then traverse it in order.
keep 2 pointers one for the start of max subset and one for the end.
keep the max_size
value while iterating the tree.
it is a O(n*log(n))
time and space complexity.
you can always sort numbers set using counting sort in a linear time
and run through the array, which means O(n)
time and space
complexity.
Assuming there isn't overflow or a big integer data type. Assuming the array is a mathematical set (no duplicate values). You can do it in O(1)
of memory:
O(n)
time complexity.