I have an array with an even number of ints and want to check if all of those elements are 'paired', ie [0, 1, 0, 1] has a pair of 1s and a pair of 0s vs [0, 1, 1, 2] has only one 0 and one 2.
My first thought was to cast it to a set and check if the set had a length of half of the original:
def isPaired(arr):
return len(arr) / 2 == len(set(arr)
But that's incorrect if the arr is [0, 1, 0, 0].
my next thought was to sort the array, and compare each even-numbered index with the next index:
def isPaired(arr):
arr.sort
for i in range(0, len(arr) - 1):
if i % 2 == 0 && arr[i] != arr[i+1]:
return False
return True
This works, but the runtime is at least the runtime of the sort. Is there a solution to this problem without sorting the array?