JPMORGAN Coding Question – Solved

7 Live
Stacey is coordinating a beach clean-up event with her university's Women in STEM Charity branch. The beach is covered with tin cans of varying weights arranged in a single line, indexed from 0 to n-1. Stacey uses a scooper that can pick up three adjacent cans at a time. For each selection: 1. She identifies the lightest remaining can, with weight w 2. She uses the scooper to pick up that can along with its two adjacent cans (or fewer if at the edge) 3. She continues this process until there are no cans left on the beach If multiple cans have the lightest weight, Stacey selects the one with the smallest index. If a can has fewer than two adjacent cans, she removes the available adjacent cans. Determine the sum of the weights of the lightest cans she picks in each selection. Example Let there be n = 5 cans on the beach with weights represented by cans = [5, 4, 1, 3, 2]. - First, choose the minimum weight, i.e., 1, and add that weight to the total. The cans with weights 4, 1, and 3 are removed. The array of cans is now [5, 2]. - Then, choose the minimum weight, i.e., 2, and add that weight to the total. The cans with weights 2 and 5 are removed. There are no more cans left. Hence, the total is 1 + 2 = 3. Function Description Complete the function findTotalWeight in the editor with the following parameter: int cans[n]: the weights of the cans on the beach Returns int: the sum of the minimum-weight cans at each selection Constraints · 3 ≤ length of cans ≤ 2000 · 1 ≤ cans[i] ≤ 10^5 Sample Case 0 Input cans = [6, 4, 9, 10, 34, 56, 54] Output 68 Explanation - First, select the minimum weight, 4. Its adjacent cans (6 and 9) are also removed → [10, 34, 56, 54] - Next, select 10. Its adjacent (34) is also removed → [56, 54] - Finally, select 54. Its adjacent (56) is removed → [] Sum = 4 + 10 + 54 = 68 Sample Case 1 Input cans = [132, 45, 65, 765, 345, 243, 75, 67] Output 1120 Explanation - Select 45 → remove 132, 45, 65 → [765, 345, 243, 75, 67] - Select 67 → remove 75, 67 → [765, 345, 243] - Select 243 → remove 345, 243 → [765] - Select 765 → remove 765 → [] Sum = 45 + 67 + 243 + 765 = 1120

Asked in: JPMORGAN

Image of the Question

Question Image Question Image Question Image Question Image

All Testcases Passed ✔



Passcode Image

Solution


import heapq
def findTotalWeight(cans):
    q = [(i, index) for index,i in enumerate(cans)]
    heapq.heapify(q)
// ... rest of solution available after purchase

🔒 Please login to view the solution

Explanation


```
To approach this problem, start by understanding the process and constraints clearly. You have a line of cans with given weights, and you repeatedly select the lightest can remaining, along with its immediate neighbors, and remove them all. You continue until no cans remain, and you need to sum the weights of all the cans chosen as the "lightest" in each step.

Here is how to think about the problem step-by-step:

1. **Identify the Core Action**
Each selection is centered on the lightest can currently available. This can might be anywhere in the list, and if there are multiple cans with the same minimum weight, the one with the smallest index is chosen. Once that can is picked, the can itself plus its adjacent neighbors (one on the left and one on the right, if they exist) are removed from the line.

2. **Maintaining the Current State of Cans**
Since cans are removed after each selection, the arrangement of cans changes dynamically. You need a data structure or a way to efficiently represent the current lineup of cans after removals. A simple array may become tricky since removing elements shifts indices, and you must keep track of neighbors.

3. **Finding the Minimum Weight Can Efficiently**
The operation of selecting the lightest can is repeated after every removal. You could scan the entire current array to find the minimum each time, but that could be inefficient if done naively (O(n) per step leading to O(n²) overall). To optimize, think about data structures that support quick retrieval of minimum elements along with efficient removal. However, since constraints allow up to 2000 cans, a well-implemented straightforward method may suffice.

4. **Removing the Chosen Can and Its Neighbors**
Once you find the minimum can and its position, remove it and its neighbors:
- If the can is at an edge, fewer than two neighbors might exist.
- Remove the can on the left if it exists.
- Remove the can on the right if it exists.
- Update the current state to reflect these removals.

5. **Handling Index Adjustments Post-Removal**
After removing cans, indices shift in a typical array structure, which can cause confusion when accessing neighbors next time. To avoid complexity, consider using a linked structure or a boolean mask indicating which cans are still present. This approach lets you skip removed cans and find neighbors without shifting the array physically.

6. **Iterative Process**
Repeat the steps:
- Identify the lightest remaining can by checking all cans still present.
- Add its weight to the running sum.
- Remove it and its neighbors.
- Continue until no cans remain.

7. **Edge Cases and Validation**
- Make sure to handle the first and last cans properly since they may have only one neighbor.
- If only one can remains at some point, selecting it removes just itself.
- Multiple cans with the same minimum weight should trigger selection of the one with the smallest index.

8. **Example to Clarify**
Take the example `[5, 4, 1, 3, 2]`:
- Minimum is 1 at index 2. Remove cans at indices 1, 2, and 3 → cans left: `[5, 2]`
- Next minimum is 2 at index 4 (adjusted index after removals). Remove cans at indices 0 and 1 of the reduced array → empty.
- Sum the minimums selected: 1 + 2 = 3.

9. **Data Structures and Implementation Thoughts**
- An array with a parallel boolean array to mark removed cans can simplify neighbor lookup.
- Alternatively, a doubly linked list or using arrays to keep track of "next" and "previous" available cans can help quickly find neighbors after removals.
- Since operations require frequent minimum searches and removals, balance simplicity and efficiency based on constraints.

10. **Summary**
The problem is about simulating a process of repeatedly picking the minimum-weight can (with tie-breaking by index), removing it and its immediate neighbors, and summing the weights of chosen cans. The key challenge lies in efficiently maintaining the state of which cans remain and quickly finding neighbors for removal after each iteration.
By carefully updating the data structure representing the cans and repeating this process until all cans are removed, you can compute the desired sum of weights.
This method is clear, manageable, and within reasonable computational limits given the problem constraints.
```


Related Questions