Python | The Right Way during Interview | Comparators
Although, this ways works, ie by directly converting all string to integer. Then sort and reverse.\n\n\nclass Solution:\n    def kthLargestNumber(self, nums: Li
Although, this ways works, ie by directly converting all string to integer. Then sort and reverse.\n\n```\nclass Solution:\n    def kthLargestNumber(self, nums: List[str], k: int) -> str:\n        nums = sorted(map(int, nums), reverse=True)\n        return str(nums[k-1])\n```\n\nThis works because there is no limit to size of int in Python, here 100 digits. So it works, but it only works in Python, not in any other. And it may not work if the length of string is much larger or even if work ,can take large memory. So you can\'t risk using this method in actual interview. This is the correct way.\n\nBy sorting based on customize sort function, which sorts x and y like\n1. when left is smaller, then -1, to keep left on left, \n2. when left is larger, then +1, to put on right\n\n\'4\', \'33\' - len of 4 is smaller, so left smaller, -1\n\'555\', \'66\' - len of 555 is larger, so right larger, +1\n\'342\', \'312\' - left if larger, so +1\n\'11\', \'11\', - both same, so 0\n\ncmp_to_key - is an comparator in python, used to create customized sort based on compare conditions (x, y for eg, in default sort, if x < y then x stays on left, else x goes on right of y).\n\n```\nfrom functools import cmp_to_key\nclass Solution:\n    def kthLargestNumber(self, nums: List[str], k: int) -> str:\n        def sorter(x, y):\n            n, m = len(x), len(y)\n            if n < m: # if you want to keep x in left of y, return -1, here if len(x) is shorter, so it is smaller, so left # [\'33\', \'4\'], 4 to left\n                return -1\n            elif n > m: # +1, if to keep in right of y\n                return 1\n            else:\n                for i in range(n):\n                    if x[i] < y[i]: # if x[i] smaller, then left\n                        return -1\n                    elif x[i] > y[i]: # else in right \n                        return 1\n                    else:\n                        continue\n            return 0 # if both same, x==y\n            \n        key = cmp_to_key(sorter)\n        nums.sort(key=key, reverse=True)\n        # print(nums)\n        return nums[k-1]\n```\n\nUpper Code in more concise form -\n\n```\nfrom functools import cmp_to_key\nclass Solution:\n    def kthLargestNumber(self, nums: List[str], k: int) -> str:\n        def sorter(x, y):\n            n, m = len(x), len(y)\n            if n != m:\n                return -1 if n < m else 1 # when n > m\n            else:\n                return -1 if x < y else 1 if x > y else 0\n            \n        key = cmp_to_key(sorter)\n        nums.sort(key=key, reverse=True)\n        return nums[k-1]\n```\n\n**Please give this a Upvote if you liked my effort.**
['Python', 'Python3']