Given a number, return the next smallest prime number
Note: A prime number is greater than one and has no other factors other than 1 and itself.
Understand what the interviewer is asking for by using test cases and questions about the problem.
- Established a set (2-3) of test cases to verify their own solution later.
- Established a set (1-2) of edge cases to verify their solution handles complexities.
- Have fully understood the problem and have no clarifying questions.
- Have you verified any Time/Space Constraints for this problem?
Be sure that you clarify the input and output parameters of the problem:
Run through a set of example cases:
HAPPY CASE
Input: 5
Output: 7
Input: 1
Output: 2
EDGE CASE:
Input: -10
Output: 2
The smallest prime number is 2, so any input less than 2 should return 2
Match what this problem looks like to known categories of problems, e.g. Linked List or Dynamic Programming, and strategies or patterns in those categories.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Infinitely loop above the input value and check every value after that if it is prime or not.
1) Iterate from N+1 to INF
2) If the current number is prime, return this number
3) Else, continue to increment and re-evaluate the next number
4) Repeat until we find the next largest prime number, since it is guaranteed to exist
⚠️ Common Mistakes
Watch out for edges cases such as:
Negative Case, Example: next_prime(-10) --> 2
Zero Case, Example: next_prime(0) --> 2
What is the time complexity of your plan? Is it O(n)? There is actually an even optimal solution with a time complexity of O(√n)!
What the largest factor of any number? Think of a few examples and write out the factors of those numbers.
Implement the code to solve the algorithm.
class Solution:
def next_prime(n):
if n <= 1:
return 2
n += 1
# Iterate from N+1 to INF
while True:
# If the current number is prime, return this number
if is_prime(n):
return n
# Else, continue to increment and re-evaluate the next number
n += 1
# Repeat until we find the next largest prime number, since it is guaranteed to exist
# Helper method
def is_prime(n):
if n < 2:
return False
if n < 4:
return True
for i in range(4, int(math.sqrt(n))):
if n % i == 0:
return False
return True
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
is_prime
is O(√n)