Final code. Verified on small and large inputs.