Three lessons:
Identify sequence starts to avoid redundant work.
Use sets for $O(1)$ membership checks instead of sorting.
Even though the inner loop looks nested, the total work is linear because each element is processed at most twice.
This problem shows how sets enable algorithms that seem impossible at first. Sorting takes $O(n \log n)$, but clever set usage gets you $O(n)$.