For a programming class a while ago we were given a relatively simple task, the essence of which can be boiled down to:
Store an array (not a List) of n Strings where n is always <= m, allowing new strings to be added and old ones to be removed. (In this instance, m was 50)
When discussing this with my friends afterwards, we realised that all three of us had solved it in a different way. My question (out of mere curiosity) is which one of us had the best answer (all things being equal) and why.
Friend A went for implementing what was essentially an ArrayList; creating a new array with a different size and putting all the elements from the original array into the new one with a for loop(plus or minus the one he was adding/removing).
Friend B simply created an array of length m, removing elements by setting their value to null (e.g. array[13] = null), and adding elements by scrubbing forward from index 0 until an empty spot was found (this was a for loop).
Friend C [Me] also created an array of length m, but shifted every following value forward (i.e. reduced their index by 1 with a for loop) when a string was removed so that n-1 was always the index of the last value (when n > 0), and n was also the index to add new values at (eliminating the for loop for adding strings).
It’s a fairly basic class and they don’t care how we did it as long as we did, but we’re curious.
edit: I just realised that I left out something which may be important. The problem specified removing strings by value (e.g. removeString("someString")) rather than index, which made finding the value (and its index) a requirement as well.
There might not be correct answer, because the arrays you create are in the end going the implemented for a system. So it depends on the system requirements. But generally considering efficiency:
Friend A’s solution, seems nasty to me. Creating a new array, for
adding/removing an element is waste of memory and cpu cycles. And
also I believe that is not how the ArrayList is implemented in Java.
Friend B’s solution, has the same worst case time complexity as
friend C’s however, it may possibly perform much better. Since the
ordering of strings is not important, this looks the best.
Friend C’s
solution, is actually quite efficient as well. As for adding a
elemnt, you already have the index i.e. n. Hence it should perform
well as well.
However as I said before it actually depends upon the system one is implementing.
But just to wrap it up I should say A < B = C.
Digvijay