Katkat

Minimize reduction cost and validate equal-sum pairs

MathWorksSoftware Engineer · Onsite

Last updated

This problem tests your ability to use greedy strategies with priority queues to minimize reduction costs and use hash-based frequency mapping to identify valid pairs that satisfy specific sum conditions.

Part 1: Minimum Cost Reduction

You are given an array of integers nums. In one operation, you can pick any two elements a and b, remove them, and replace them with a + b. The cost of this operation is a + b. Your goal is to minimize the total cost of reducing the entire array to a single element.

def min_reduction_cost(nums: List[int]) -> int:
    # Returns the minimum cost to reduce the array to a single element

Part 2: Equal-Sum Pair Products

Given an integer target_sum, identify all unique pairs (nums[i], nums[j]) (where `i int: # Returns the sum of products of all pairs that add up to target_sum


## Constraints
- `1 <= nums.length <= 10^5`
- `1 <= nums[i] <= 10^6`

## Examples
**Part 1 Example:**
Input: `[1, 2, 3]`
Output: `9`
Explanation: Merge 1 and 2 (cost 3, array becomes `[3, 3]`), then merge 3 and 3 (cost 6, total 3+6=9).

**Part 2 Example:**
Input: `nums = [1, 5, 3, 3]`, `target_sum = 6`
Output: `14`
Explanation: Pairs are `(1, 5)` and `(3, 3)`. Products are `5` and `9`. Total = 14.

## Edge Cases
- Empty array or single-element array (cost 0).
- No pairs satisfying `target_sum`.

Hints

Hint 1

For Part 1, consider using a Min-Heap to always combine the two smallest available numbers, similar to building a Huffman tree.

Hint 2

For Part 2, a hash map (dictionary) can store the frequency of numbers seen so far to find the complement `target_sum - current_val` in O(1) time.

Hint 3

Ensure you handle cases where `nums[i]` equals the complement, counting occurrences correctly so that pairs aren't duplicated or missed.

Follow-up questions

  • How does the time complexity change for Part 1 if we use a sorted list instead of a heap?
  • If the array contained negative numbers, how would that affect the greedy strategy in Part 1?
  • How would you modify Part 2 to return the count of distinct pairs that satisfy the condition rather than the sum of their products?