JCSU Unit 2 Problem Set 1 (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?
HAPPY CASE Input: nums = [ [1, 2, 3], [4, 5], [6] ] Output: 21 Explanation: The sum is calculated as 1 + 2 + 3 + 4 + 5 + 6 = 21.
def nested_sum(nums):
total = 0 # Initialize the total sum
for sublist in nums: # Iterate through each sublist in the list
for num in sublist: # Iterate through each number in the sublist
total += num # Add the number to the total sum
return total # Return the total sum
--##-5:-R-eview----**Review**-the-code-by-running-specific-example(s)-and-recording-values-(watchlist)-of-your-code's-variables-along-the-way.--Example-1:---Input:-nums-=-[-[1,-2,-3],-[4,-5],-[6]-]---Expected-Output:-21---Observed-Output:-21--Example-2:---Input:-nums-=-[[">]]
Output:
0
Explanation:
An empty list of lists results in a sum of 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.
For **nested list summing problems**, we want to consider the following approaches:
- **Nested Loops:** Iterate through each sublist and then through each number in that sublist to calculate the sum.
- **Flattening and Summing:** Flatten the list of lists into a single list and calculate the sum.
## 3: P-lan
> **Plan** the solution with appropriate visualizations and pseudocode.
**General Idea:**
Use nested loops to iterate through each sublist in the main list, then iterate through each element of the sublist and add the values to a running total.
### Steps:
1. Initialize a variable `total` to 0.
2. For each sublist in the input `nums`:
- For each number in the sublist:
- Add the number to `total`.
3. Return the value of `total`.
## 4: I-mplement
> **Implement** the code to solve the algorithm.
def nested_sum(nums):
total = 0 # Initialize the total sum
for sublist in nums: # Iterate through each sublist in the list
for num in sublist: # Iterate through each number in the sublist
total += num # Add the number to the total sum
return total # Return the total sum
## 5: R-eview
> **Review** the code by running specific example(s) and recording values (watchlist) of your code's variables along the way.
Example 1:
- Input: nums = [ [1, 2, 3], [4, 5], [6] ]
- Expected Output: 21
- Observed Output: 21
Example 2:
- Input: nums = [[
Evaluate the performance of your algorithm and state any strong/weak or future potential work.
Assume n is the total number of integers in the nested lists.