Two Pointers Approach:
As we know that the given array is sorted in non-decreasing order, we can have two pointers, i
and j
, where i
and j
represent slow-runner and fast-runner, respectively. On the condition that nums[i] = num[j]
, j
is incremented to skip duplicates. If we find that nums[i]!=nums[j]
then we will conclude the duplicate run and its value must be copied to nums[i + 1]
. we will then increase the i
, and the process is repeated until j
arrives at the end of the array.
Solution steps:
- Initializing slow-runner and fast-runner variables
i
andj
, respectively. - The input array will be scanned till
j< length
ofnums
. - We will identify a duplicate element by using this condition,
nums[i]==nums[j]
; if the above condition matches, then we will skip the duplicate element, andj
will be incremented by1
. Likewise, we will identify the unique element using this condition,nums[i]!=nums[j]
, if the above condition matches, theni
will be incremented by1
. - Lastly, we will copy
nums[j]
tonums[i]
and increasej
by1
. - We will repeat the above steps till
j
arrives at the end of the array, and the resultant output would bei+1
and the resultant array by eliminating the duplicated element.
