How to check if an array contain consecutive integers in C#

1 Answer

0 votes
using System;
using System.Linq;
using System.Collections.Generic;

public class MyClass
{
	public static bool array_contain_consecutive_integers(int[] arr) {
		if (arr.Length <= 1) {
			return true;
		}

		int min = arr.Min();
		int max = arr.Max();

		if (max - min != arr.Length - 1) {
			return false;
		}

		ISet<int> st = new HashSet<int>();

		foreach (int val in arr) {
			if (st.Contains(val)) {
				return false;
			}
			st.Add(val);
		}
		return true;
	}

	public static void Main(string[] args)
	{
		int[] arr = new int[] {-2, 3, 0, -1, 4, 2, 1};

		if (array_contain_consecutive_integers(arr)) {
			Console.Write("Yes");
		}
		else {
			Console.Write("No");
		}
	}
}




/*
run:
  
Yes
  
*/

 



answered Aug 19, 2022 by avibootz

Related questions

1 answer 122 views
1 answer 109 views
1 answer 130 views
2 answers 159 views
1 answer 106 views
...