In computer science, while coding, it is one thing to learn the language. Learning the language involves remembering the basic syntax and forming a “Hello World” code. After that comes solving problems. A good programmer is one who can solve a problem by multiple methods, pun intended. Some of them are easy to understand but tardy and time-consuming while others are simple two-liners but with an implementation that is very difficult to comprehend.
At the end of the day, our aim is to solve a problem and find the simplest way to do it, but in order to reach that level, one has to do it through the long way. Each difficult problem can be divided into sub-problems. Finding distinct objects is also a kind of sub-problem that we usually come across while solving programming questions in placement exams.
C# provides a very sleek feature for this functionality, which we will discuss later. Firstly solving this issue with the tedious approach will help us understand coding at a deeper level.
The Long Way
So, when removing duplicates we assume that we have an empty box and we go through all the items in the group sequentially. There is one condition to enter the box, that is if the box has anything like you, it won’t let you in. Iterating this alogrithm will simply provide us all the distinct elements in any data structure.
For Numbers,
- using System;
- using System.Collections;
- public class Program{
- public static void Main(){
- int[] arr = {1,3,1,4,7,4,2,1,5,5,3};
- //Find only Unique Elements
- //Declaring the Empty Box
- ArrayList sol = new ArrayList();
- for(int i=0;i<arr.Length;i++){
- //Mandatory Entry Condition
- if(sol.Contains(arr[i])==false){
- sol.Add(arr[i]);
- }
- }
- //ONLY FOR DISPLAYING OUTPUT
- Console.Write("Original Array : ");
- foreach(var a in arr){
- Console.Write("{0} ",a);
- }
- Console.Write("\n");
- Console.Write("Modified Array : ");
- //Checking the Output
- foreach(var j in sol){
- Console.Write(j+ " ");
- }
- }
- }




Shimon GolanPosted May 1, 2021, 8:10 PM
IN the first solution , it would be more efficient to use a HashSet, ( insertions are amortized to be O(1) instead of O(N) for the list ).