-
Notifications
You must be signed in to change notification settings - Fork 265
Split Haycorns
TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 5 mins
- 🛠️ Topics: Divisors, Loops
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?
- The function
split_haycorns()
should take a positive integerquantity
and return a list of all divisors ofquantity
.
HAPPY CASE
Input: 6
Expected Output: [1, 2, 3, 6]
EDGE CASE
Input: 1
Expected Output: [1]
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.
This problem falls under: Divisors Calculation.
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Define a function that iterates through numbers from 1 to quantity
and checks if they are divisors of quantity
.
1. Define the function `split_haycorns(quantity)`.
2. Initialize an empty list `divisors` to store the divisors.
3. Iterate through all numbers from 1 to `quantity` (inclusive).
4. For each number, check if it is a divisor of `quantity` using the modulo operator (`quantity % i == 0`).
5. If it is a divisor, add it to the `divisors` list.
6. Return the `divisors` list.
- Not handling the case where quantity is 1, which should correctly return [1].
Implement the code to solve the algorithm.
def split_haycorns(quantity):
# Initialize an empty list to store the divisors
divisors = []
# Iterate through all numbers from 1 to quantity (inclusive)
for i in range(1, quantity + 1):
# If i is a divisor of quantity, add it to the list
if quantity % i == 0:
divisors.append(i)
# Return the list of divisors
return divisors
Review the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Call the function with the provided examples:
print(split_haycorns(6)) # Expected Output: [1, 2, 3, 6]
print(split_haycorns(1)) # Expected Output: [1]
Expected outputs:
[1, 2, 3, 6]
[1]
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
- Time Complexity: O(n) where n is the value of quantity since we need to check all numbers from 1 to quantity.
- Space Complexity: O(n) for storing the divisors.