Python Challenge - Find Xth Number In Order

def getX(x, nums): if not nums or len(nums) < x: return 0 nums.sort() return nums[x-1] print(getX(2, [6, 3, -1, 5]))
def getX(x, nums): if len(nums) == 0: return 0 if x > len(nums): return 0 nums.sort() return nums[x-1] print(getX(2, [6, 3, -1, 5])) print(getX(2, [5, 10, -3, -3, 7, 9])) print(getX(4, [5, 10, -3 , -3, 7, 9]))

def getX(x, nums):

write your code here

if x > len(nums) or len(nums) == 0:
return 0
return sorted(nums)[x-1]

print(getX(2, [6, 3, -1, 5]))

def getX(x, nums): # write your code here nums.sort() try: return nums[x-1] except: return 0 print(getX(4, [6, 3, -1, 5]))

tried to do 1 line

def getX(x, nums):
  return sorted(nums)[x - 1] if x in range(1, len(nums) + 1) else 0

print(getX(3, [1, 2, 4, 3, 5]))
def getX(x, nums):
    sorted_list = sorted(nums)
    if len(sorted_list) >= x and len(sorted_list) != 0:
        return sorted_list[x-1]
    else:
        return 0
print(getX(4, [5, 10, -3 , -3, 7, 9]))
def getX(x, nums): # write your code here nums_sorted = sorted(nums) if x > len(nums) or len(nums) == 0 : return 0 else: return nums_sorted[x-1] print(getX(5, [5, 10, -3 , -3, 7, 9]))

Almost every solution here uses sort which is average O(nlogn).

I don’t see anyone posting the better solution (and the one the problem hints at) that is O(n) by keeping track of the x smallest values and doing one pass of the nums. For example:

def getX(x, nums): # Special cases (min and max are O(N)) if not nums or x > len(nums): return 0 elif x == len(nums): return max(nums) elif x == 1: return min(nums) # Scan nums maintaining smallest 'x' of them # Always note the 'largest of the smallest' and replace it when needed # A max-heap would be even better smallest = nums[0:x] largest_smallest = max(smallest) for i in nums[x:]: if i < largest_smallest: smallest[smallest.index(largest_smallest)] = i largest_smallest = max(smallest) return largest_smallest print(getX(2, [6, 3, -1, 5]))

As it says in the comment there are better ways of managing the “smallest” items, a max heap being probably the best. Note you can’t use a set in case of non-unique numbers. Could use a dict of num->count though.