Sorting The Array
When you receive an unsorted array and decide to sort it before applying the two-pointer technique, the overall time complexity is dominated by the sorting step.
- Sorting: This typically takes O(n log n) time.
- Two Pointer Traversal: Once sorted, scanning the array with two pointers takes O(n) time.
Thus, the overall time complexity becomes:
O(n log n) + O(n) = O(n log n)
If the array is already sorted, then you only pay the O(n) cost for the two-pointer traversal, without the additional O(n log n) sorting cost.
No Comments