Order Colors String

Given is a s colors string. Each color is separated by space and end with integer number, which represents their order. Return a new string with sorted order of colors.

Example:
Input: "red3 blue2 green4 white1"
Output: "white blue red green"

Solutions

class MyClass
{
    public class LastCharComparer : IComparer<string>
    {
        public int Compare(string? x, string? y)
        {

            if (x is null && y is null)
            {
                return 0;
            }
            if (x is null || y is null)
            {
                return x is null ? -1 : 1;
            }

            var first = x[^1];
            var second = y[^1];

            return first.CompareTo(second);
        }
    }
    public string ColorsNameString(string str)
    {
        var colors = str.Split(' ');
        var orderedColors = new SortedSet<string>(new LastCharComparer());
        StringBuilder sb = new();

        foreach (var item in colors)
        {
            orderedColors.Add(item);
        }

        foreach (var item in orderedColors)
        {
            sb.Append(item[0..(item.Length - 1)]);
            sb.Append(" ");
        }
        return sb.ToString();
    }

}

Time complexity: O(n log n)

Space complexity: O(n)

Last updated