fix quardratic runtime in cases when there are many duplicate keys in array