1

Given an array of integers I have to return true if all the elements in the array are different or all the elements are the same. Otherwise, I have to return false.

E.g.

[1, 1, 1, 1] - all the elements are the same, so it is true

[12, 20, 1, 23] - all the elements are different, so it is also true

[12, 20, 1, 1] - we have just two 1, so it is false

The easy thing I was able to come up with is to use a hashmap to map an integer to a number of occurrences of that integer in the array. And then to iterate over the hashmap and check if there is at least one entry whose value is greater than 1 and is not equal to the length of the array, then I return false. Otherwise, I return true after the iteration.

The problem with my solution is that it has a linear space complexity and I feel that it should be possible to somehow solve the problem using a constant space complexity and linear time complexity.

So, could someone help me come up with an O(1) space complexity and O(n) linear complexity with respect to the array size solution, please?

I am working on this problem just for fun.

D.W.
  • 167,959
  • 22
  • 232
  • 500
some1 here
  • 113
  • 5

2 Answers2

3

The problem does not have any $O(n)$ time algorithm. Note that it is easy to check in linear time if all the elements in the array are the same or not. However, to check if all the elements are district, the problem is known as Element distinctness problem. And, this problem has an $\Omega(n \log n)$ lower bound complexity (for comparison based models). More technically, your problem can be reduced to element distinctness problem in linear time.

Therefore, the best possible solution here is $O(n \log n)$ time algorithm. For that, you can employ merge sort algorithm using a linked list. It also has an $O(1)$ space complexity.


Note: Since the input is a set of integers, you can employ Radix sort to solve the problem in linear time.

Inuyasha Yagami
  • 6,277
  • 1
  • 12
  • 23
-1

I have just started to look into time and space complexity and it is all a mess for me atm, but this particular problem can be solved with converting the list of integers into a set, then comparing lenghts. Would that be linear in time? Sample function:

def same_diff(a_list):
    a_list.sort()
    temp_set = set(a_list)
    if len(temp_set) <= 1 or len(temp_set) == len(a_list):
        return True
    return False

Sorting is not required, but neater I guess?

Thanks :)