TIP102 Unit 7 Session 1 Standard (Click for link to problem statements)
In the kingdom of Codepathia, the queen determines how many resources to distribute to each village based on its class. A village's class is equal to the number of digits in its population. Given an integer population
, write a function get_village_class()
that returns the number of digits in population
.
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?
HAPPY CASE
Input: 432
Output: 3
Explanation: The number 432 has 3 digits.
Input: 9
Output: 1
Explanation: The number 9 has 1 digit.
EDGE CASE
Input: 1000
Output: 4
Explanation: The number 1000 has 4 digits.
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 Counting Digits in an Integer, we want to consider the following approaches:
Plan the solution with appropriate visualizations and pseudocode.
General Idea:
Iterative Approach:
1) Initialize a counter `count` to 0.
2) While `population` is greater than 0:
a) Divide `population` by 10.
b) Increment `count`.
3) Return `count` as the number of digits.
Recursive Approach:
1) Base case: If `population` is 0, return 0.
2) Recursive case: Return 1 plus the result of a recursive call with `population // 10`.
⚠️ Common Mistakes
Implement the code to solve the algorithm.
# Iterative Solution
def get_village_class_iterative(population):
count = 0
while population > 0:
population //= 10
count += 1
return count
# Recursive Solution
def get_village_class_recursive(population):
if population == 0:
return 0
return 1 + get_village_class_recursive(population // 10)
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
get_village_class_iterative
function with the input 432
. The function should return 3 after dividing the number by 10 three times.get_village_class_recursive
function with the input 432
. The function should return 3 after recursively dividing the number by 10 three times.Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Space Complexity:
O(1)
because it uses a constant amount of extra space.O(N)
due to the recursion stack, where N
is the number of digits in the population.Performance: The iterative solution is generally preferred for its constant space usage and simplicity in understanding and implementation. The recursive solution, while more elegant and expressive, could be limited by stack size in environments with a large number of digits.