Skip to content

Instantly share code, notes, and snippets.

@WennderSantos
Last active July 15, 2019 02:34
Show Gist options
  • Save WennderSantos/2ff881b54bff9f2d56e3bd6362c25d10 to your computer and use it in GitHub Desktop.
Save WennderSantos/2ff881b54bff9f2d56e3bd6362c25d10 to your computer and use it in GitHub Desktop.
Get the smallest string given a weight (all chars have a weight)
//Time: O(n) where n is weight
//Memory: O(1) weights helper with 26 key:value pairs
//In this solution, I am decreasing weights one by one
//and searching its value in the weigths helper.
//As bigger the weight is the longer will take to algorithm execute
//I wrote a better solution using an array instead of a hashmap as a helper
//https://gist.github.com/WennderSantos/2256be4706a4f3cd6121ab322116a918
public static string smallestString(long weight)
{
var weigths = new Dictionary<long, char>();
var prevWeight = 1;
var asciiVal = 65;
weigths.Add(1, 'A');
for (int i = 2; i <= 26; i++)
{
var letter = Convert.ToChar(asciiVal + i -1);
var letterWeight = i * prevWeight + prevWeight;
weigths.Add(letterWeight, letter);
prevWeight = letterWeight;
}
if (weigths.ContainsKey(weight))
return weigths[weight].ToString();
var sb = new StringBuilder();
var j = weight - 1;
var target = weight;
while (j > 0)
{
if (weigths.ContainsKey(j))
{
var count = 1;
while (j * count <= target)
{
sb.Insert(0, weigths[j]);
count++;
}
target -= j * (count - 1);
}
j--;
}
return sb.ToString();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment