Map Sum Pairs in JavaScript

The MapSum data structure allows you to store key-value pairs and efficiently calculate the sum of all values whose keys start with a given prefix. This problem is commonly solved using a Trie (prefix tree) data structure.

Problem Overview

We need to implement a MapSum class with two methods:

  • insert(key, value): Stores a key-value pair. If the key already exists, it updates the value.
  • sum(prefix): Returns the sum of all values whose keys start with the given prefix.

Solution Using Trie Structure

The solution uses a Trie where each node can store a value. When we insert a key, we traverse the Trie creating nodes as needed, and store the value at the final node.

class Node {
    constructor(val) {
        this.num = 0;          // Value stored at this node
        this.val = val;        // Character value
        this.children = {};    // Child nodes
    }
}

class MapSum {
    constructor() {
        this.root = new Node('');
    }
    
    insert(key, val) {
        let node = this.root;
        for (const char of key) {
            if (!node.children[char]) {
                node.children[char] = new Node(char);
            }
            node = node.children[char];
        }
        node.num = val;  // Store value at the end node
    }
    
    sum(prefix) {
        let sum = 0;
        let node = this.root;
        
        // Navigate to the prefix node
        for (const char of prefix) {
            if (!node.children[char]) {
                return 0;  // Prefix not found
            }
            node = node.children[char];
        }
        
        // Helper function to sum all values in subtree
        const helper = (node) => {
            sum += node.num;
            const { children } = node;
            Object.keys(children).forEach((key) => {
                helper(children[key]);
            });
        };
        
        helper(node);
        return sum;
    }
}

// Example usage
const mapSum = new MapSum();
mapSum.insert('apple', 3);
mapSum.insert('app', 2);
mapSum.insert('application', 5);

console.log("Sum of keys with prefix 'app':", mapSum.sum('app'));
console.log("Sum of keys with prefix 'apple':", mapSum.sum('apple'));
console.log("Sum of keys with prefix 'xyz':", mapSum.sum('xyz'));
Sum of keys with prefix 'app': 10
Sum of keys with prefix 'apple': 3
Sum of keys with prefix 'xyz': 0

How It Works

The Trie structure allows efficient prefix-based operations:

  1. Insert: Traverse the Trie character by character, creating nodes as needed, and store the value at the final node.
  2. Sum: Navigate to the prefix node, then recursively sum all values in its subtree.

Testing Key Updates

const mapSum2 = new MapSum();
mapSum2.insert('apple', 3);
console.log("Initial sum for 'app':", mapSum2.sum('app'));

// Update existing key
mapSum2.insert('apple', 7);
console.log("After updating 'apple' to 7:", mapSum2.sum('app'));

mapSum2.insert('app', 2);
console.log("After adding 'app' with value 2:", mapSum2.sum('app'));
Initial sum for 'app': 3
After updating 'apple' to 7: 7
After adding 'app' with value 2: 9

Time Complexity

Operation Time Complexity Description
Insert O(k) k = length of key
Sum O(p + n) p = prefix length, n = nodes in subtree

Conclusion

The MapSum implementation using a Trie provides efficient insertion and prefix-based sum operations. The Trie structure naturally supports prefix queries, making it ideal for this type of problem.

Updated on: 2026-03-15T23:19:00+05:30

372 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements