> For the complete documentation index, see [llms.txt](https://docs-57.gitbook.io/data-structure-and-algorithms/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs-57.gitbook.io/data-structure-and-algorithms/problems/sorting/order-colors-string.md).

# 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

```csharp
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)
