This is another version for smaller arrays:
func find_duplicates_small(a):
var duplicates = []
for i in range(0, a.size()):
for j in range(j+1, a.size()):
if a[j] == a[i]:
duplicates.append(j)
return duplicates
The idea is to loop a second time for each element, but only starting from the next so we can discard b == a
because that's the same as a == b
.
As for my first version, it will return the index of duplicates, but not the first occurences of the value. So for example, if you have ["a", "b", "c", "b"], the function will return [3]. If you want both you can adapt the function so it also inserts i
the first time a duplicate is found. Or, if order doesn't matters, you can check the size of duplicates
after the inner loop, then if it changed insert i
.
Again, you can tweak it the way you like. You know your problem, so you could make this algorithm more efficient by adapting it for you need :)