'C# - Modify an array in place, without creating another array in memory

In C#, is it possible to remove an element from an array in place?

Of course, there are a ton of questions on SO about removing items from an array. Every answer either uses a List or creates another array with the new values. However, I'd like to know if it's even possible to modify an array in place (deleting or adding elements) in C#.

In the easy LeetCode question "Remove Duplicates from Sorted Array", you are restricted to the same array, you cannot create a new array in memory (O(1) space in memory). Is this possible using C#? I can't come up with a solution that does not create another array.



Solution 1:[1]

In C#, is it possible to remove an element from an array in place?

No, by definition of array. Arrays are fixed-length. You can, however, track the number of "elements you care about" within the array (an integer) and remove elements by copying following elements down to their prior index & decrementing this counter.

You'd then have derived an Array List (List<T> in .NET).

In the easy LeetCode question "Remove Duplicates from Sorted Array", you are restricted to the same array, you cannot create a new array in memory (O(1) space in memory). Is this possible using C#? I can't come up with a solution that does not create another array.

The question wants you to modify the provided array with your solution, then return the length of the subset of the array (starting at index 0) filled with unique values.

A solution in Java is available here: https://leetcode.com/problems/remove-duplicates-from-sorted-array/solution/ - you can change two letters (length to Length twice) to get it compiling in C#.

I'll paste that here anyway:

int RemoveDuplicates(int[] nums) {
    if (nums.Length == 0) return 0;
    int i = 0;
    for (int j = 1; j < nums.Length; j++) {
        if (nums[j] != nums[i]) {
            i++;
            nums[i] = nums[j];
        }
    }
    return i + 1;
}

Solution 2:[2]

Here is a sample of using two arrays and in-place changes:

public static int[] MoveZeros(int[] arr){
    //int[] nonZeros = new int[arr.Length];
    int forwardArrow = 0;
    for(int i=0; i< arr.Length; i++){
      if(arr[i] != 0){
        //Two arrays approach
        //nonZeros[forwardSecoundArrow] = arr[i];
        //forwardSecoundArrow++;
                
        //in-place approach
        var temp = arr[i];
        arr[i] = arr[forwardArrow];
        arr[forwardArrow] = temp;
        forwardArrow++;
      }
    }
    
     //Two arrays approach
    /*
      for(int i=0; i < nonZeros.Length; i++){
        arr[i] = nonZeros[i];
        }
    */
    
    return arr;
  }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Alireza Ali