2

There is an array of integers, his length is n. In more than half of his elements there is a constant k that is unknown. You can't change the array (he is read-only) and you only have a memory of O(1) size. You need to find k in best complexity (you think you can get lower than O(n)?)

example:

{1, 6, 44, 1, 1, 8, 1} so k = 1

I thought about uding median, but I'm not allowed to change the array...

Thanks

Museful
  • 6,711
  • 5
  • 42
  • 68
Stabilo
  • 269
  • 3
  • 11

1 Answers1

5

I believe this is what you're looking for: http://www.cs.utexas.edu/users/moore/best-ideas/mjrty/index.html

Essentially, you iterate and maintain two pieces of data: a candidate and a vote count. Each element either increases or decreases the vote count, depending on if the element itself matches the candidate. If the vote is 0, then the element itself becomes the candidate.

As long as there is a majority present, by the end of the iterative process, the current candidate will be that majority element.

Ben
  • 2,065
  • 1
  • 13
  • 19