BackmediumLinked ListGoogleAmazon

Tome Cache Optimizer 6 Solution

Problem Statement

You are tasked with optimizing the memory allocation for a distributed caching system that stores 'tome' metadata. The system maintains a doubly linked list of cache nodes, where each node holds a specific weight representing its data size. To prevent memory overflow, the system must identify the top K heaviest nodes to offload to secondary storage. However, the offloading mechanism operates on a sliding window basis defined by the linked list structure. Your goal is to compute the sum of the K largest weights in the list. If K exceeds the total number of nodes, the system must return the sum of all available node weights. The input is provided as a head pointer to a singly linked list of integers and an integer K. You must return the computed sum as a long integer to handle potential overflow.

Example 1
Input
head = [3, 1, 4, 1, 5], K = 2
Output
9

Explanation: The linked list contains values [3, 1, 4, 1, 5]. The two largest values are 5 and 4. Their sum is 5 + 4 = 9.

Example 2
Input
head = [10, 20, 30], K = 5
Output
60

Explanation: The linked list contains values [10, 20, 30]. Since K (5) is greater than the number of nodes (3), we sum all values: 10 + 20 + 30 = 60.

Example 3
Input
head = [7, 7, 7, 7], K = 2
Output
14

Explanation: The linked list contains values [7, 7, 7, 7]. The two largest values are 7 and 7. Their sum is 7 + 7 = 14.

Example 4
Input
head = [100, 50, 25, 10], K = 1
Output
100

Explanation: The linked list contains values [100, 50, 25, 10]. The single largest value is 100. The sum is 100.

Constraints

  • 1 <= number of nodes in linked list <= 10^5
  • 1 <= K <= 10^5
  • -10^9 <= node.val <= 10^9
  • The linked list is non-circular and singly linked.
Live Compiler1 Free Run Available
Loading Editor...
Test Cases & Output
Click "Run" to test your 1 free compile trial!

🚀 Practice this problem

Run code, get AI hints & track streak

Sign Up Free

Tome Cache Optimizer 6 — Problem Statement & Solution Guide

Linked ListMediumInward Pointers
TimeO(N log K)
|
SpaceO(K)

Problem Description

You are tasked with optimizing the memory allocation for a distributed caching system that stores 'tome' metadata. The system maintains a doubly linked list of cache nodes, where each node holds a specific weight representing its data size. To prevent memory overflow, the system must identify the top K heaviest nodes to offload to secondary storage. However, the offloading mechanism operates on a sliding window basis defined by the linked list structure. Your goal is to compute the sum of the K largest weights in the list. If K exceeds the total number of nodes, the system must return the sum of all available node weights. The input is provided as a head pointer to a singly linked list of integers and an integer K. You must return the computed sum as a long integer to handle potential overflow.

DSA Pattern Breakdown

DSA Pattern Breakdown

"Tome Cache Optimizer 6"

medium

WHY DOES IT MATTER?

Selecting top‑K elements is a classic selection problem that appears in caching, recommendation engines, and streaming analytics. Mastering the min‑heap pattern equips engineers to handle large data streams where only a small subset matters.

OPTIMIZATION CHALLENGE

The key insight is to keep only the K most promising candidates during a single pass, discarding smaller weights immediately. This bounded‑size heap prevents the algorithm from ever storing more than K elements, turning a potentially O(N log N) problem into O(N log K).

REAL-WORLD CONNECTION

Think of a CDN that must evict the K largest objects to free up space. The eviction policy needs to quickly identify those objects without scanning the entire catalog repeatedly, mirroring the min‑heap selection over a linked list of cached items.

When coding, initialize the heap with the first K nodes to avoid unnecessary pushes/pops, then iterate from the (K+1)‑th node onward, comparing each weight to the heap's root. This reduces constant factors and makes the solution cleaner.

COMPLEXITY AT A GLANCE

⏱ Time:O(N log K)
💾 Space:O(K)

Core Theory — Why This Approach?

The problem reduces to selecting the K largest weight values from a doubly linked list. A naive scan that stores every node weight and then sorts would be O(N log N) time and O(N) extra space, which quickly becomes prohibitive for massive caches where N can be in the millions. The optimal paradigm leverages a min‑heap (priority queue) of fixed capacity K. As we traverse the list once, we push each node's weight onto the heap; if the heap exceeds K we pop the smallest element, guaranteeing that after the full pass the heap contains exactly the K heaviest nodes. This yields O(N log K) time and O(K) auxiliary space, a dramatic improvement when K << N. An alternative average‑case O(N) solution uses the Quickselect algorithm after copying the list into an array, but it incurs O(N) extra memory and loses the deterministic guarantee of the heap approach, making the min‑heap the preferred deterministic solution for interview settings.

Interview Questions on This Problem

Q1How would you find the top K heaviest nodes in a doubly linked list without converting it to an array?

Traverse the list once while maintaining a min‑heap of size K. Insert each node's weight; if the heap size exceeds K, remove the smallest element. After the traversal, the heap holds the K largest weights, which can be extracted in descending order.

Q2Explain why sorting the entire list of N nodes is sub‑optimal for this problem, especially when K is much smaller than N.

Sorting requires O(N log N) time and O(N) extra space (or in‑place O(1) but still O(N log N) time). When K << N, we waste effort sorting elements that will never be part of the answer. A min‑heap limits work to O(N log K), dramatically reducing runtime and memory usage.

Q3Can you achieve O(N) time for this problem? If so, describe the trade‑offs involved.

Yes, by copying the list into an array and applying Quickselect to partition around the K‑th largest element, achieving average O(N) time. The trade‑off is O(N) additional space and non‑deterministic worst‑case O(N^2) time, plus extra code complexity, which often makes the heap solution preferable in interviews.

Examples

Example 1

Input

head = [3, 1, 4, 1, 5], K = 2

Output

9

Explanation: The linked list contains values [3, 1, 4, 1, 5]. The two largest values are 5 and 4. Their sum is 5 + 4 = 9.

Example 2

Input

head = [10, 20, 30], K = 5

Output

60

Explanation: The linked list contains values [10, 20, 30]. Since K (5) is greater than the number of nodes (3), we sum all values: 10 + 20 + 30 = 60.

Example 3

Input

head = [7, 7, 7, 7], K = 2

Output

14

Explanation: The linked list contains values [7, 7, 7, 7]. The two largest values are 7 and 7. Their sum is 7 + 7 = 14.

Example 4

Input

head = [100, 50, 25, 10], K = 1

Output

100

Explanation: The linked list contains values [100, 50, 25, 10]. The single largest value is 100. The sum is 100.

Constraints

  • 1 <= number of nodes in linked list <= 10^5
  • 1 <= K <= 10^5
  • -10^9 <= node.val <= 10^9
  • The linked list is non-circular and singly linked.

Optimal Approach & Strategy

Traverse the list once with a size‑K min‑heap, pushing each weight and popping the smallest when the heap exceeds K.

Brute Force Approach

Collect all node weights, sort them descending, and take the first K elements.

Verified Code Solutions

JavaScript Solution
Time: O(N log K)
function solution(nums, k) {
   if (k === 0 || k > nums.length) return 0;
   nums = nums.filter(x => typeof x === 'number');
   nums.sort((a, b) => b - a);
   let sum = 0;
   for (let i = 0; i < Math.min(k, nums.length); i++) {
       sum += nums[i];
   }
   return sum;
}

Asked in Top Tech Interviews

GoogleAmazonMicrosoft

Solve in Interative Editor

Ready to test your code? Open our built-in compiler, run custom test suites, and see detailed complexity analysis reports instantly.