Tech Point Fundamentals

Wednesday, January 12, 2022

C# Program to Check for Duplicate Array Element

C# Program to Check for Duplicate Array Element

coding-interview-question-csharp

Most of the IT companies check the coding skills and problem-solving skills as well along with the theoretical interview questions. Sometimes you are free to write the pseudo code and sometimes you are asked to write the complete program either on any paper or any editor. 


This question is asked in the coding interview to write the program. Here you can find the program as well as a live running program so that you can test the program immediately.


Watch our videos here





Question: 


How can you check whether an array contains duplicate values or not? Write a program to check if an array contains duplicates.









C# Program to Check for Duplicate Array Element


       
 

// Author 	: Tech Point Fundamentals
// Website 	: www.techpointfunda.com
// Channel	: https://www.youtube.com/c/TechPointFundamentals
// Demo		: Checking Array Duplicate Element

using System;
using System.Collections.Generic;

public class Program
{
public static void Main()
{
	int[] unsortedArray = new int[8] {1, 2, 6, 4, 3, 4, 2, 4};			
			
	Console.WriteLine("Input Array: ");	
	Console.WriteLine("------------------------------------------------ ");	
	for( int i = 0; i < unsortedArray.Length; i++)
	{
		Console.WriteLine(unsortedArray[i]);
	}				
	
	Console.WriteLine("\n\nIs Array Contains Duplicate Elements : " + IsArrayContainsDuplicates(unsortedArray));						
}	 
	
public static bool IsArrayContainsDuplicates(int[] inputArray)    
{    
	Dictionary<int, int> d = new Dictionary<int, int>();
	foreach (int i in inputArray)
	{
		if (d.ContainsKey(i))
			return true;
		else
			d.Add(i, 1);
	}
	return false;		
} 
}





Output: 



               Input Array: ------------------------------------------------ 1 2 6 4 3 4 2 4 Is Array Contains Duplicate Elements : True


Live Demo






No comments:

Post a Comment

Please do not enter any HTML. JavaScript or spam link in the comment box.