# Reversing an array

**URL:** <https://forum.dfinity.org/t/reversing-an-array/12724>\
**Category:** Language Support\
**Tags:** Motoko\
**Created:** [May 4, 2022, 6:33pm UTC](https://forum.dfinity.org/t/reversing-an-array/12724 "2022-05-04T18:33:33Z")\
**Posts on this page:** 1\
**Showing post:** 9

<div class="post-metadata">

**Author:** ![icme](https://sea1.discourse-cdn.com/flex023/user_avatar/forum.dfinity.org/icme/32/4327_2.png) [@icme](https://forum.dfinity.org/u/icme)\
**Post date:** [May 5, 2022, 8:00am UTC](https://forum.dfinity.org/t/reversing-an-array/12724/9 "2022-05-05T08:00:47Z")

</div>

Yea you’re looking at O(n^2) right there.

Depends on the size of your array, but if you want uniqueness, or a lookup check I think you’re using the wrong data structure here if you want to check key uniqueness. I’d recommend using a HashMap or a Red-Black Tree and storing the data in there in the first place.

I’ll give you an example of how you can use this stable Red-Black Tree library to improve your runtime to O(n) [StableRBTree/StableRBTree.mo at main · canscale/StableRBTree · GitHub](https://github.com/canscale/StableRBTree/blob/main/src/StableRBTree.mo)

```auto

type Item = {
  name: Text;
  damage: Nat;
};

type Count = Nat;

let itemBackpack = RBTree.init<Item, Count>();

// this is how you seed a Red-Black Tree with your existing array of items to have an item count key value store
for (item in yourCurrentItemArray.vals()) {
  switch(RBTree.get<Item, Count>(itemBackpack, itemCompareTo, item)) {
    case null { RBTree.put<Item, Count>(item, 1) };
    case (?count) { RBTree.put<Item, Count>(item, count + 1 };
  }
};

// get unique items
let uniqueItems = Iter.filter<(Item, Count)>(
  RBTree.entries<Item, Count>(itemBackpack),
  func((item, count)) { count == 1 }
);

```

Another approach would be to just use a HashMap for even quicker lookups. Keep in mind that HashMaps are O(1), but aren’t nearly as memory efficient as Red-Black Trees. [The Motoko HashMap implementation has been rumored to take up 28X the size](https://forum.dfinity.org/t/nftanvil-ic-network-tests-report/11001)

---

_[View the full topic](https://forum.dfinity.org/t/reversing-an-array/12724)._
