Skip to content

Instantly share code, notes, and snippets.

@kristianjaeger
Created October 26, 2025 22:37
Show Gist options
  • Select an option

  • Save kristianjaeger/c309a5ac4319b7b4ab3c4c8f9ceec372 to your computer and use it in GitHub Desktop.

Select an option

Save kristianjaeger/c309a5ac4319b7b4ab3c4c8f9ceec372 to your computer and use it in GitHub Desktop.
Remove element from array example C#
using System;
// this is inspired by question 27 - https://leetcode.com/problems/remove-element/
// I could not get their c# website runner / compiler to work. I used https://dotnetfiddle.net/ instead.
public class Solution
{
public static int RemoveElement(int[] nums, int val)
{
int k = 0;
for (int i = 0; i < nums.Length; i++)
{
if (nums[i] != val)
{
nums[k] = nums[i];
k++;
}
}
return k;
}
static void Main(string[] args)
{
int[] nums = { 3, 2, 2, 3, 4, 2, 5 };
int val = 2;
int k = RemoveElement(nums, val);
Console.WriteLine("Number of elements not equal to " + val + ": " + k);
Console.WriteLine("Modified array length " + nums.Length);
Console.WriteLine("Modified array (first k elements):");
for (int i = 0; i < k; i++)
{
Console.Write(nums[i] + " ");
}
Console.WriteLine();
Console.WriteLine("Full modified array");
for (int i = 0; i < nums.Length; i++)
{
Console.Write(nums[i] + " ");
}
Console.WriteLine();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment