KatInterview

677. Map Sum Pairs

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Trie (Prefix Tree)

The problem requires us to store key-value pairs and calculate the sum of values for keys that share a common prefix. This is a classic use case for a Trie (Prefix Tree) data structure.

Solution

Map Sum Pairs in Python

class TrieNode:
    def __init__(self):
        # Dictionary for child nodes.
        self.children = {}
        # Sum of values of all keys that pass through this node.
        self.sum = 0

class MapSum:

    def __init__(self):
        """
        Initialize your data structure here.
        """
        self.root = TrieNode()
        # A hash map to store the actual value of each key.
        # This helps in calculating the difference when a key's value is updated.
        self.key_to_val = {}

    def insert(self, key: str, val: int) -> None:
        # Calculate the difference between the new value and the old value.
        # If the key is new, get() returns 0.
        diff = val - self.key_to_val.get(key, 0)
        self.key_to_val[key] = val
        
        # Traverse the Trie, updating the sum of each node on the path.
        curr = self.root
        for char in key:
            if char not in curr.children:
                curr.children[char] = TrieNode()
            curr = curr.children[char]
            curr.sum += diff

    def sum(self, prefix: str) -> int:
        # Traverse the Trie to find the node corresponding to the prefix.
        curr = self.root
        for char in prefix:
            if char not in curr.children:
                # If prefix does not exist, no keys start with it.
                return 0
            curr = curr.children[char]
        # The sum at this node is the sum of all keys with this prefix.
        return curr.sum


# Your MapSum object will be instantiated and called as such:
# obj = MapSum()
# obj.insert(key,val)
# param_2 = obj.sum(prefix)

Map Sum Pairs in Java

class MapSum {

    private class TrieNode {
        // Map for child nodes.
        Map<Character, TrieNode> children;
        // Sum of values of all keys that pass through this node.
        int sum;

        TrieNode() {
            children = new HashMap<>();
            sum = 0;
        }
    }

    private TrieNode root;
    // A hash map to store the actual value of each key.
    // This helps in calculating the difference when a key's value is updated.
    private Map<String, Integer> keyToVal;

    /** Initialize your data structure here. */
    public MapSum() {
        root = new TrieNode();
        keyToVal = new HashMap<>();
    }
    
    public void insert(String key, int val) {
        // Calculate the difference between the new value and the old value.
        // If the key is new, getOrDefault returns 0.
        int diff = val - keyToVal.getOrDefault(key, 0);
        keyToVal.put(key, val);
        
        // Traverse the Trie, updating the sum of each node on the path.
        TrieNode curr = root;
        for (char c : key.toCharArray()) {
            // If a child node for the character doesn't exist, create it.
            curr.children.putIfAbsent(c, new TrieNode());
            curr = curr.children.get(c);
            curr.sum += diff;
        }
    }
    
    public int sum(String prefix) {
        // Traverse the Trie to find the node corresponding to the prefix.
        TrieNode curr = root;
        for (char c : prefix.toCharArray()) {
            curr = curr.children.get(c);
            if (curr == null) {
                // If prefix does not exist, no keys start with it.
                return 0;
            }
        }
        // The sum at this node is the sum of all keys with this prefix.
        return curr.sum;
    }
}

/**
 * Your MapSum object will be instantiated and called as such:
 * MapSum obj = new MapSum();
 * obj.insert(key,val);
 * int param_2 = obj.sum(prefix);
 */

Map Sum Pairs in C++

class MapSum {
private:
    // Trie node structure
    struct TrieNode {
        // Using a map for children for flexibility, could be an array of 26 for lowercase English letters
        std::unordered_map<char, TrieNode*> children;
        // Sum of values of all keys that pass through this node
        int sum = 0;
    };

    TrieNode* root;
    // A hash map to store the actual value of each key
    // This helps in calculating the difference when a key's value is updated
    std::unordered_map<std::string, int> keyToVal;

public:
    /** Initialize your data structure here. */
    MapSum() {
        root = new TrieNode();
    }
    
    void insert(string key, int val) {
        // Calculate the difference between the new value and the old value.
        // If the key is new, its old value is 0.
        int diff = val - keyToVal[key]; // unordered_map::operator[] default-constructs to 0 if key not found
        keyToVal[key] = val;
        
        // Traverse the Trie, updating the sum of each node on the path.
        TrieNode* curr = root;
        for (char c : key) {
            if (curr->children.find(c) == curr->children.end()) {
                curr->children[c] = new TrieNode();
            }
            curr = curr->children[c];
            curr->sum += diff;
        }
    }
    
    int sum(string prefix) {
        // Traverse the Trie to find the node corresponding to the prefix.
        TrieNode* curr = root;
        for (char c : prefix) {
            if (curr->children.find(c) == curr->children.end()) {
                // If prefix does not exist, no keys start with it.
                return 0;
            }
            curr = curr->children[c];
        }
        // The sum at this node is the sum of all keys with this prefix.
        return curr->sum;
    }
};

/**
 * Your MapSum object will be instantiated and called as such:
 * MapSum* obj = new MapSum();
 * obj->insert(key,val);
 * int param_2 = obj->sum(prefix);
 */

Map Sum Pairs in TypeScript

class TrieNode {
    children: Map<string, TrieNode>;
    sum: number;

    constructor() {
        // Map for child nodes.
        this.children = new Map<string, TrieNode>();
        // Sum of values of all keys that pass through this node.
        this.sum = 0;
    }
}

class MapSum {
    private root: TrieNode;
    // A hash map to store the actual value of each key.
    // This helps in calculating the difference when a key's value is updated.
    private keyToVal: Map<string, number>;

    constructor() {
        this.root = new TrieNode();
        this.keyToVal = new Map<string, number>();
    }

    insert(key: string, val: number): void {
        // Calculate the difference between the new value and the old value.
        // If the key is new, get() returns undefined, so we default to 0.
        const diff = val - (this.keyToVal.get(key) || 0);
        this.keyToVal.set(key, val);

        // Traverse the Trie, updating the sum of each node on the path.
        let curr = this.root;
        for (const char of key) {
            if (!curr.children.has(char)) {
                curr.children.set(char, new TrieNode());
            }
            // The '!' non-null assertion is safe because we just ensured the entry exists.
            curr = curr.children.get(char)!;
            curr.sum += diff;
        }
    }

    sum(prefix: string): number {
        // Traverse the Trie to find the node corresponding to the prefix.
        let curr: TrieNode | undefined = this.root;
        for (const char of prefix) {
            if (!curr || !curr.children.has(char)) {
                // If prefix does not exist, no keys start with it.
                return 0;
            }
            curr = curr.children.get(char);
        }
        // The sum at this node is the sum of all keys with this prefix.
        return curr ? curr.sum : 0;
    }
}

/**
 * Your MapSum object will be instantiated and called as such:
 * var obj = new MapSum()
 * obj.insert(key,val)
 * var param_2 = obj.sum(prefix)
 */

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.