adding an element to a linked list is known to be O(1).
However, adding it in position X is O(X)
and if i want to add R elements in this position the total running time would be O(R*X).
but there must be an O(X+R) solution.
And the question is how to do the O(R+X) in java?
You have a list of pairs
(element, X)whereXis an index andelementis the item you want to put under that index. Sort this list byXand add elements one after another using anIterator. Here is an example:Your input is:
[(E1, 5), (E2, 3), (E3, 7)].Sort it by index:
[(E2, 3), (E1, 5), (E3, 7)]Create an iterator and advance it by
3.Add
E2using an iterator.Advance the same iterator by
2(5 - 3).Add
E1.…
Notice that this algorithm has an of-by-one bug. It should be relatively easy to fix it.
UPDATE: just noticed that your problem is much simpler. In your case just create an iterator, advance it
Xtimes and add elements one by one using that iterator.