Any data structure with direct indexed access and length (arrays, lists, strings, file streams) allow representation of completing "reverse" in O(1) time (note that it's reverse itself, obviously iterating all items will still be O(n).
There are several examples in Possible to iterate backwards through a foreach? with "yield return" suggested by Jon Skeet is the most flexible way (likely a bit less performant that just backward for
):
public static IEnumerable<T> FastReverse<T>(this IList<T> items)
{
for (int i = items.Count-1; i >= 0; i--)
{
yield return items[i];
}
}
As Patrick Roberts commented you can also use other data structure that looks like array - i.e. dictionary with sequential int
keys and known high/low boundaries would work (which is roughly how JavaScript arrays work).
Indeed double-linked-list (LinkedList
in C#) is the data structure of choice when only forward and reverse iterations are needed... but converting array/list (that already give you O(1) way to represent reverse iteration) is not worth it. Depending on other requirements switching to linked list completely may be an option.
Note that from theoretical point of view if you need to iterate through all elements anyway then spending O(n) on reverse does not change overall complexity.