Generalised and simplified solution for SnapperChain. The solution now works with the large input