Search⌘ K
AI Features

Solution Review: Remove Even Integers From an Array

Learn how to implement and understand a C# solution to remove even integers from an array. This lesson guides you through iterating over the array, selecting odd numbers, and managing memory effectively. You will understand the solution's process and its linear time complexity, helping you enhance your array manipulation skills for coding interviews.

We'll cover the following...

Solution

C#
namespace chapter_2
{
class Solution
{
static int [] removeEven(int[]Arr, int size)
{
int m = 0;
for (int i = 0; i < size; i++)
{
if (Arr[i] % 2 != 0) // if odd number found
{
Arr[m] = Arr[i]; //inserting odd values in the array
++m;
}
}
int[] temp = new int[m];
for (int i = 0; i < m; i++)
temp[i] = Arr[i];
Arr = temp;
return Arr; // returning the array after removing the odd numbers
}
//Remove Event Integers from an Array:
static void Main(string[] args)
{
int[] arr = null; // declaring array
arr = new int[10]; // memory allocation
Console.Write("Before remove even: ");
for (int i = 0; i < 10; i++)
{
arr[i] = i; // assigning values
Console.Write(arr[i] + " ");
}
Console.WriteLine("");
arr = removeEven(arr, 10); // calling removeEven
Console.Write("After remove even: ");
for (int i = 0; i < 5; i++)
{
Console.Write( arr[i] + " "); // prinitng array
}
Console.WriteLine("");
return ;
}
}
}

Explanation

This solution starts with the first element of the given array: Arr checks if it is odd. Then it moves this element to the start of the array Arr if it is odd; otherwise, it jumps to the next element. This repeats until the end of the array Arr is reached while keeping the count of total odd numbers m in Arr. Next, make a temporary array to store all odd numbers in: temp. Point Arr to the temp array. No variable is referencing to the array that Arr was previously referencing, so the Garbage collector will collect that array later in time, freeing up the memory. Lastly, return the array Arr, that is, containing only odd elements only.

Time complexity

Since the entire array has to be iterated over, this solution works in O(n)O(n).