-1

if a table of N integer is present how to check if an element is repeating if present it shows message that table has repeating elements, if this is to be achieved in minimum time complexity

1 Answers1

0

Hash table is the way to go (ie normal Lua table). Just loop over each integer and place it into the table as the key but first check if the key already exists. If it does then you have a repeat value. So something like:

values = { 1, 2, 3, 4, 5, 1 } -- input values

local htab = {}
for _, v in ipairs(values) do
  if htab[v] then print('duplicate value: ' .. v)
  else htab[v] = true end
end

With small integer values the table will use an array so will be O(1) to access. With larger and therefore sparser values the values will be in the hash table part of the table which can just be assumed to be O(1) as well. And since you have N values to insert this is O(N).

Getting faster than O(N) should not be possible since you have to visit each value in the list at least once.

EDD
  • 2,070
  • 1
  • 10
  • 23