rewritten for arrays, unit tests not yet passing
uses mutable data structures