find repeated values in array code example
Example 1: find duplicates and their count in an array javascript
var counts = {};
your_array.forEach(function(x) { counts[x] = (counts[x] || 0)+1; });
Example 2: count of duplicate number in array
def FirstOccurrence ( array, n ) :
beg = 0
end = len(array) - 1
while (beg <= end) :
mid = int (beg + (end-beg)/2)
if (array[mid] == n) :
if (mid-1 >= 0 and array[mid-1] == n) :
end = mid-1
continue
return mid
elif (array[mid] < n) :
beg = mid + 1
else :
end = mid - 1
return -1
def LastOccurrence (array, n) :
beg = 0
end = len(array)-1
while (beg <= end) :
mid = int(beg + (end-beg)/2)
if (array[mid] == n) :
if (mid+1 < len(array) and array[mid+1] == n) :
beg = mid + 1
continue
return mid
elif (array[mid] < n) :
beg = mid + 1
else :
end = mid - 1
return -1;
array = [ 1, 2, 3, 9, 9, 9, 9, 10, 10, 12, 13 ]
n = int (input("Enter the number : "))
first_index = FirstOccurrence (array, n)
last_index = LastOccurrence (array, n)
if (first_index == -1 or last_index == - 1) :
print("Element does not exist")
else :
print("First occurrence of " + str(n) + " is at index : " + str(first_index))
print("Last occurrence of " + str(n) + " is at index : " + str(last_index))
print("Total count : "+ str(last_index - first_index + 1))