-
Notifications
You must be signed in to change notification settings - Fork 254
HulkSmash
Raymond Chen edited this page Aug 1, 2024
·
5 revisions
TIP102 Unit 1 Session 1 Advanced (Click for link to problem statements)
- 💡 Difficulty: Easy
- ⏰ Time to complete: 10 mins
- 🛠️ Topics: Arrays, Conditionals, Iteration
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 hulk_smash()
should take an integer n
and return a 1-indexed string array answer
where:
answer[i] == ""HulkSmash""
if i
is divisible by 3 and 5.
answer[i] == ""Hulk""
if i
is divisible by 3.
answer[i] == ""Smash""
if i
is divisible by 5.
answer[i] == i (as a string)
if none of the above conditions are true.
HAPPY CASE
Input: 3
Expected Output: [""1"", ""2"", ""Hulk""]
Input: 5
Expected Output: [""1"", ""2"", ""Hulk"", ""4"", ""Smash""]
Input: 15
Expected Output: [""1"", ""2"", ""Hulk"", ""4"", ""Smash"", ""Hulk"", ""7"", ""8"", ""Hulk"", ""Smash"", ""11"", ""Hulk"", ""13"", ""14"", ""HulkSmash""]
EDGE CASE
Input: 1
Expected Output: [""1""]
Input: 0
Expected Output: []
Plan the solution with appropriate visualizations and pseudocode.
General Idea: Iterate from 1 to n, applying the given rules to determine the string to append to the result list.
1. Initialize an empty list `answer`.
2. Iterate through the range from 1 to `n` (inclusive).
a. If the current number is divisible by 3 and 5, append ""HulkSmash"" to `answer`.
b. If the current number is divisible by 3, append ""Hulk"" to `answer`.
c. If the current number is divisible by 5, append ""Smash"" to `answer`.
d. If none of the above conditions are true, append the current number (as a string) to `answer`.
3. Return `answer`.
- Forgetting to handle the case where n is 0.
- Incorrectly checking divisibility conditions.
Implement the code to solve the algorithm.
def hulk_smash(n):
answer = []
for i in range(1, n + 1):
if i % 3 == 0 and i % 5 == 0:
answer.append(""HulkSmash"")
elif i % 3 == 0:
answer.append(""Hulk"")
elif i % 5 == 0:
answer.append(""Smash"")
else:
answer.append(str(i))
return answer