Find two repeating elements in a given array

The problem is as follows:
Given an array with n+2 elements, all elements of the array are in range 1 to n and also all
elements occur only once except two numbers which occur twice. Find those two repeating numbers.

Sample Input: [4,2,4,5,2,3,1]
Sample Output: 2,4


arr = [4,2,4,5,2,3,1]

'''Using hash table concept
Complexity Time: O(n), Space: O(n)'''

def twiceOccurringElement(arr):
    countarr = [0]* len(arr)
    
    for entry in arr:
        countarr[entry] += 1
    
    elements = []  
    for i in range(len(countarr)):
        if countarr[i] > 1:
            elements.append(i)

    return elements

print twiceOccurringElement(arr)


Advertisement

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s