math and geometry May 19, 2023

The kth factor of n

Time O(n) Space O(1) Open original problem

We can iterate through the numbers from 1 to n and check if the number is a factor of n. If it is, we decrement k by 1. If k is 0, we return the number.

class Solution:
    def kthFactor(self, n: int, k: int) -> int:
        for i in range(1, n//2 + 1):
            if n % i == 0:
                k -= 1
                if k == 0:
                    return i

        return n if k == 1 else -1

Time complexity: O(n) where n is the value of n.
Space complexity: O(1)