Date: 2024-07-26
Problem
- In this problem you are given an array with a target element that you must move to the end. This means if you are given an array with multiple ‘2’ elements and target is 2. Then you will need to mutate the array in place and make sure that the end part of the array solely consists of the target element
- The order of the other elements doesn’t matter, just as long as the target is at the end of the array
Solution
- Naively a solution that comes to mind is to simply sort the array and swap until all the same elements are at the end of the array. While this will work it is not the most optimal solution since on average sorting an array costs us
O(nlogn)
time. Its important to first think about the different methods we can use. If you move past this sorting option, you will realize that this problem can be solved in linear timeO(n)
. - To solve this in linear time we start by creating two pointers. One at the beginning
i
and one at the end of the arrayj
. We will be stepping through the array checking ifi
is the target element and if so can it be replaced with the current position ofj
if not then we know that the target element and we don’t want to move it from its place. Therefore, we must movej
by one index until we’ve reached an element that is not our target and can be swapped withi
. - Once this swap is done, we can move our initial index
i
by one and repeat the same process. This will continue until both pointers have crossed each other meaning we’ve checked all elements in the array. - Time Complexity: - Space Complexity: