Unit 10 Session 2 (Click for link to problem statements)
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?
n
is less than or equal to zero?
False
, since a power of four must be a positive integer.HAPPY CASE
Input: n = 16
Output: True
Explanation: 16 is 4^2.
HAPPY CASE
Input: n = 5
Output: False
Explanation: 5 is not a power of four.
EDGE CASE
Input: n = 1
Output: True
Explanation: 1 is 4^0.
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.
For problems involving powers, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Continuously divide the number by 4 and check if it eventually reduces to 1.
1) If n is less than or equal to 0, return False.
2) While n is divisible by 4, divide n by 4.
3) If n is equal to 1 after the loop, return True.
4) Otherwise, return False.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
def is_power_of_four(n):
if n <= 0:
return False
while n % 4 == 0:
n //= 4
return n == 1
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.
Assume N
represents the value of the integer.
O(log N)
because we repeatedly divide the number by 4.O(1)
because we only use a constant amount of extra space.