Skip to content

Commit 37c7ad8

Browse files
committed
[Anagram] - Optimize method to detect anagram string.
1 parent 28930f5 commit 37c7ad8

File tree

1 file changed

+17
-21
lines changed

1 file changed

+17
-21
lines changed

Algorithms/Strings/Permutations.cs

Lines changed: 17 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -66,32 +66,28 @@ public static HashSet<string> ComputeDistinct(string Source)
6666
/// <summary>
6767
/// Determines if the Other string is an anargram of the Source string.
6868
/// </summary>
69-
public static bool IsAnargram(string Source, string Other)
69+
public static bool IsAnargram(string source, string other)
7070
{
71-
if (string.IsNullOrEmpty(Source) || string.IsNullOrEmpty(Other))
71+
if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(other))
7272
return false;
73-
else if (Source.Length != Other.Length)
73+
else if (source.Length != other.Length)
7474
return false;
75-
else if (Source == Other)
75+
else if (source.Equals(other, StringComparison.Ordinal))
7676
return true;
7777

78-
// Begin the Anagram check
79-
// Covnert strings to character arrays
80-
// O(N) space complexity
81-
var sourceCharArray = Source.ToCharArray();
82-
var otherCharArray = Other.ToCharArray();
83-
84-
// Sort both character arrays in place using heapsort
85-
// O(N log N) operation
86-
sourceCharArray.HeapSort<char>(Comparer<char>.Default);
87-
otherCharArray.HeapSort<char>(Comparer<char>.Default);
88-
89-
// One pass scan
90-
// O(N) operation
91-
for (int i = 0; i < sourceCharArray.Length; ++i)
92-
if (sourceCharArray[i] != otherCharArray[i])
93-
return false;
94-
78+
int len = source.Length;
79+
// Hash set which will contains all the characters present in input souce.
80+
var hashSetSourceChars = new HashSet<char>();
81+
for (int i = 0; i < len; i++)
82+
{
83+
hashSetSourceChars.Add(source[i]);
84+
}
85+
for (int i = 0; i < len; i++)
86+
{
87+
// Inputs are not Anargram if characers from *other are not present in *source.
88+
if (!hashSetSourceChars.Contains(other[i])) return false;
89+
//if (!hashSetOther.Contains(source[i])) return false;
90+
}
9591
return true;
9692
}
9793
}

0 commit comments

Comments
 (0)