I have an array containing element names. I want to give the user the ability to create items without specifying their name, so my program will have to provide a unique name by default, for example "Item 1".
The problem is that the name must be unique, so I have to check the whole array for this name by default, and if there is an element with the same name, I have to change the name as "Item 2" and so on until I find an available name.
The obvious solution would be:
String name = "Item ";
for (int i = 0; !isAvailable(name + i) ; i++);
My problem with this algorithm is that it works in O (N ^ 2).
I wonder if there is a well-known (or new) more efficient algorithm for solving this case.
In other words, my question is this: is there any algorithm that finds the first greater number, nonzero, which does not exist in this array, and works with less than N ^ 2?
source
share