Friday, January 8, 2021

Sort integers in lexicographical order

Problem: Given an integer n, return 1 - n in lexicographical order.

Example:

n = 15
Output = [1,10,11,12,13,14,15,2,3,4,5,6,7,8,9]


Approach: We will use string comparison instead of integer comparison to sort the array of [1...n] using comparer.


Implementation in C#:

        public static List<int> LexicalOrder(int n)

        {

            int[] result = Enumerable.Range(1, n).ToArray();

            Array.Sort(result, (x, y) =>

            {

                return x.ToString().CompareTo(y.ToString());

            });

            return result.ToList();

        }


Complexity: O(nlogn)

No comments:

Post a Comment