Tuesday, 30 September 2025

remove duplicates in an sorted array

 



using System;

public class HelloWorld
{
    public static void Main(string[] args)
    {
        int[] ar = { 2, 2, 3, 3, 4, 6, 6 };

        Console.WriteLine("Original Array:");
        Console.WriteLine(string.Join(", ", ar));

        int[] unique = RemoveDuplicates(ar);

        Console.WriteLine("Array After Removing Duplicates:");
        Console.WriteLine(string.Join(", ", unique));
    }

    static int[] RemoveDuplicates(int[] ar)
    {
        // handle empty array
        if (ar.Length == 0)
            return ar;

        int[] temp = new int[ar.Length];
        int rd = 0;
        temp[rd] = ar[0];

        for (int i = 1; i < ar.Length; i++)
        {
            if (ar[i] != temp[rd])
            {
                rd++;
                temp[rd] = ar[i];
            }
        }

        // resize array to actual unique count
        int[] result = new int[rd + 1];
        for (int i = 0; i <= rd; i++)
        {
            result[i] = temp[i];
        }

        return result;
    }
}

No comments:

Post a Comment

remove duplicates in an sorted array

  using System; public class HelloWorld {     public static void Main(string[] args)     {         int[] ar = { 2, 2, 3, 3, 4, 6, 6 };      ...