<!-- canonical: https://0xsimao.com/findings/nftperp-ii-trim-expensive-complexity-simplified -->

# trimDuplicatePools() is very expensive, having O(n^2) complexity and could be simplified

Low/Info · Three Sigma · NFT perpetuals · 29th January, 2024

Finding 3S-NFTPerp-N06 of the Nftperp Matching Engine security review.

- Report: /reports/nftperp-ii
- Source: https://cdn.sanity.io/files/qoqld077/production/87f617e82d5468500e950a669f30607376b37c32.pdf

---

### Description

[ammRouter:trimDuplicatePools()](https://github.com/nftperp/NFTPerp-V2-Contracts/blob/8ea05fc0ecf299ca8374b571486846652c8725f8/src/AMMRouter.sol#L848) eliminates duplicate pools in the input by comparing
every element of the array for duplicates, which is very expensive.
Note: the function is actually useless as it is impossible to add liquidity in duplicate pools. It
would [revert](https://github.com/nftperp/NFTPerp-V2-Contracts/blob/8ea05fc0ecf299ca8374b571486846652c8725f8/src/AMM.sol#L412) with error "SANDWICH".

### Recommendation

Force the user to input pool indexes ordered and if there are duplicates, revert. [Here](https://github.com/safe-global/safe-smart-account/blob/main/contracts/Safe.sol#L312) is an
example of safe using this technique.

### Status

Addressed in [#8c1e930](https://github.com/nftperp/NFTPerp-V2-Contracts/commit/8c1e930c1dac8cc4f79b1ea22b30a5b92b62c52f)
