Skip to content

Total Honey

Raymond Chen edited this page Aug 1, 2024 · 4 revisions

TIP102 Unit 1 Session 1 Standard (Click for link to problem statements)

Problem Highlights

  • 💡 Difficulty: Easy
  • Time to complete: 5 mins
  • 🛠️ Topics: List Iterations, Loops

1: U-nderstand

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 sum_honey() should take a list of integers, hunny_jars, and return the sum of all the elements in the list without using the built-in sum() function.
HAPPY CASE
Input: [2, 3, 4, 5]
Expected Output: 14

Input: [10, 20, 30]
Expected Output: 60

EDGE CASE
Input: []
Expected Output: 0

2: M-atch

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: List Iteration and Summation

3: P-lan

Plan the solution with appropriate visualizations and pseudocode.

General Idea: Define a function that initializes a sum variable to 0, iterates through the list, adds each element to the sum variable, and returns the sum.

1. Define the function `sum_honey(hunny_jars)`.
2. Initialize a variable `total_honey` to 0.
3. Iterate through each element in `hunny_jars`.
4. Add each element to `total_honey`.
5. Return `total_honey`

⚠️ Common Mistakes

  • Forgetting to initialize the sum variable.
  • Not correctly iterating through the list.

4: I-mplement

Implement the code to solve the algorithm.

def sum_honey(hunny_jars):
    # Initialize the sum variable to 0
    total_honey = 0
    
    # Iterate through each element in the list
    for jar in hunny_jars:
        # Add the element to the total sum
        total_honey += jar
    
    # Return the total sum
    return total_honey

5: R-eview

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(sum_honey([2, 3, 4, 5]))  # Expected Output: 14
print(sum_honey([]))            # Expected Output: 0
print(sum_honey([10, 20, 30]))  # Expected Output: 60
print(sum_honey([0, 0, 0]))     # Expected Output: 0

Expected outputs:

14
0
60
0

6: E-valuate

Evaluate the performance of your algorithm and state any strong/weak or future potential work.

  • Time Complexity: O(n) where n is the number of elements in the list since we need to iterate through all elements.
  • Space Complexity: O(1) as no additional data structures are used beyond the sum variable.
Clone this wiki locally