ℹ️ Select 'Choose Exercise', or randomize 'Next Random Exercise' in selected language.

Choose Exercise:
Timer 00:00
WPM --
Score --
Acc --
Correct chars --

R: Remove Duplicates from Sorted Array

R

Goal -- WPM

Ready
Exercise Algorithm Area
1remove_duplicates <- function(nums) {
2n <- length(nums)
3
4# Handle edge cases: empty or single-element array
5if (n == 0) {
6return(0)
7}
8if (n == 1) {
9return(1)
10}
11
12# Pointer for the position of the next unique element
13# Starts at 1 because the first element is always unique in a non-empty array
14unique_idx <- 1
15
16# Iterate through the array starting from the second element
17for (i in 2:n) {
18# If the current element is different from the last unique element found
19if (nums[i] != nums[unique_idx]) {
20# Increment the unique index
21unique_idx <- unique_idx + 1
22# Place the current element at the new unique index
23nums[unique_idx] <- nums[i]
24}
25}
26
27# The new length of the array with unique elements is unique_idx
28# The function modifies the array in-place, but returns the new length
29return(unique_idx)
30}
Algorithm description viewbox

R: Remove Duplicates from Sorted Array

Algorithm description:

This R function removes duplicate elements from a sorted array in-place. It iterates through the array using two pointers: one (`i`) to scan through all elements and another (`unique_idx`) to keep track of the position where the next unique element should be placed. The function modifies the original array and returns the new length of the array containing only unique elements. This is a common operation in data processing and algorithm optimization.

Algorithm explanation:

The `remove_duplicates` function has a time complexity of O(n) because it iterates through the array once. The space complexity is O(1) as it modifies the array in-place without using any significant auxiliary data structures. The `unique_idx` pointer effectively partitions the array: elements from index 1 to `unique_idx` are unique, while elements beyond `unique_idx` are either duplicates or unprocessed. When `nums[i]` is found to be different from `nums[unique_idx]`, it means `nums[i]` is a new unique element. We then increment `unique_idx` and copy `nums[i]` to `nums[unique_idx]`. Edge cases include empty arrays (returning 0) and arrays with a single element (returning 1). The invariant is that the subarray `nums[1...unique_idx]` always contains unique elements in their original relative order.

Pseudocode:

function remove_duplicates(array):
  n = length of array
  if n == 0:
    return 0
  if n == 1:
    return 1

  unique_idx = 1

  for i from 2 to n:
    if array[i] != array[unique_idx]:
      unique_idx = unique_idx + 1
      array[unique_idx] = array[i]

  return unique_idx