-
Notifications
You must be signed in to change notification settings - Fork 0
/
Sherlock_And_Valid_String.cs
50 lines (43 loc) · 1.48 KB
/
Sherlock_And_Valid_String.cs
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
using System;
using System.Collections.Generic;
using System.Linq;
namespace HackerRank.Algorithms.Strings
{
class Program
{
static void Main(string[] args)
{
var inputDictionary = Console.ReadLine().GroupBy(l => l).ToDictionary(l => l.Key, l => l.Count());
Console.WriteLine(TryToMakeValid(inputDictionary) ? "YES" : "NO");
}
private static bool TryToMakeValid(Dictionary<char, int> charFreqs)
{
var attempts = 0;
var averageFreq = charFreqs.GroupBy(l => l.Value)
.OrderByDescending(p => p.Count())
.ThenByDescending(l => l.Key)
.First().Key; // find most used frequencies, if there are two character with same frequency, select higher one.
foreach (var charFreq in charFreqs)
{
var freqDiff = Math.Abs(charFreq.Value - averageFreq);
if (freqDiff > 1 && charFreq.Value != 1) // if the difference higher than 1, we can not make valid this string in one step
{
return false;
}
if (charFreq.Value == 1 && freqDiff != charFreq.Value) // if the frequency of a character is equal to 1, lets remove it to make string valid. make sure the average frequency is not equal to 1.
{
attempts++;
}
else if(freqDiff == 1) // if the difference is equal to 1, attempt to make string valid.
{
attempts++;
}
if (attempts > 1)
{
return false; // it seems we have tried two or more times to make this string valid, so return false.
}
}
return true;
}
}
}