Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Given an array of integers where some numbers repeat 1 time or 2 times but one number repeats 3 times, how do you find it?

Tags:

algorithm

Given an array of integers where some numbers repeat 1 time, some numbers repeat 2 times and only one number repeats 3 times, how do you find the number that repeat 3 times. Using hash was not allowed. Complexity of algorithm should be O(n)

like image 358
Supriya Sane Avatar asked Mar 23 '10 03:03

Supriya Sane


People also ask

How do you find a repeating number in an array?

Duplicate elements can be found using two loops. The outer loop will iterate through the array from 0 to length of the array. The outer loop will select an element. The inner loop will be used to compare the selected element with the rest of the elements of the array.

How do you find the missing and repeating numbers in an array?

Traverse the array. While traversing, use the absolute value of every element as an index and make the value at this index as negative to mark it visited. If something is already marked negative then this is the repeating element. To find missing, traverse the array again and look for a positive value.

How do you know if an array has one or consecutive numbers?

Method 1 (Use Sorting) 1) Sort all the elements. 2) Do a linear scan of the sorted array. If the difference between the current element and the next element is anything other than 1, then return false. If all differences are 1, then return true.


1 Answers

I assume the array is not sorted, or similary, repeats of a number don't appear in one contiguous run. Otherwise, the problem is really trivial: just scan the array once with a window of size 3, and if each number in that window is the same, then that's the number that repeats 3 times in one contiguous run.

If the repeats are scattered, then the problem becomes more interesting.

Since this is homework, I will only give you a hint.

This problem is a cousin of where you're given an array of unsorted integers, and all numbers appear an even number of times, except one that appears an odd number of times.

That number can be found quite easily in O(N) by performing an exclusive-or of all the numbers in the array; the result is the number that appears an odd number of times.

The reason why this works is that x xor x = 0.

So for example, 3 xor 4 xor 7 xor 0 xor 4 xor 0 xor 3 = 7.

like image 200
polygenelubricants Avatar answered Nov 16 '22 04:11

polygenelubricants