-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathArithmeticProgression.cs
More file actions
101 lines (86 loc) · 2.59 KB
/
ArithmeticProgression.cs
File metadata and controls
101 lines (86 loc) · 2.59 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DA.Algorithms.Problems
{
public static class ArithmeticProgression
{
/// <summary>
/// Find if array elements can form an Arithmetic progression.
/// <para>Time Complexity - O(n.logn)</para>
/// </summary>
///
/// <exception cref="System.ArgumentNullException" />
public static bool IsArithmeticProgression (int[] array)
{
if (array == null)
{
throw new System.ArgumentNullException ();
}
if (array.Length <= 1)
{
return true;
}
Array.Sort (array);
int difference = array[1] - array[0];
for (int i = 2; i < array.Length; i++)
{
if (array[i] - array[i - 1] != difference)
{
return false;
}
}
return true;
}
/// <summary>
/// Find if array elements can form an Arithmetic progression.
/// <para>Time Complexity - O(n.logn)</para>
/// </summary>
///
/// <exception cref="System.ArgumentNullException" />
public static bool IsArithmeticProgressionUsingHash (int[] array)
{
if (array == null)
{
throw new System.ArgumentNullException ();
}
int first = int.MaxValue;
int second = int.MaxValue;
int value = 0;
HashSet<int> hashSet = new HashSet<int> ();
for (int i = 0; i < array.Length; i++)
{
if (array[i] < first)
{
second = first;
first = array[i];
}
else if (array[i] < second)
{
second = array[i];
}
}
int difference = second - first;
for (int i = 0; i < array.Length; i++)
{
// If value is duplicate return false
if (hashSet.Contains (array[i]))
{
return false;
}
hashSet.Add (array[i]);
}
for (int i = 0; i < array.Length; i++)
{
value = first + i * difference;
if (!hashSet.Contains(value))
{
return false;
}
}
return true;
}
}
}