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 and j, respectively.
  • The input array will be scanned till j< length of nums.
  • 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, and j will be incremented by 1. Likewise, we will identify the unique element using this condition, nums[i]!=nums[j], if the above condition matches, then i will be incremented by 1.
  • Lastly, we will copy nums[j] to nums[i] and increase j by 1.
  • We will repeat the above steps till j arrives at the end of the array, and the resultant output would be i+1 and the resultant array by eliminating the duplicated element.

Two Pointers Approach