Monday, May 16, 2022

Leet Code 677. Map Sum Pairs

Example 1:

Input
["MapSum", "insert", "sum", "insert", "sum"]
[[], ["apple", 3], ["ap"], ["app", 2], ["ap"]]
Output
[null, null, 3, null, 5]

Explanation
MapSum mapSum = new MapSum();
mapSum.insert("apple", 3);  
mapSum.sum("ap");           // return 3 (apple = 3)
mapSum.insert("app", 2);    
mapSum.sum("ap");  





package pep.Day80;

import java.util.HashMap;

public class LeetCode_677_Map_Sum_Pairs {
public static void main(String[] args) {

insert("car", 1);
insert("card", 4);
insert("cards", 5);
insert("carts", 6);
insert("cars", 7);
System.out.println(sum("ca"));
}

static class Node {
Node[] children = new Node[26];
int score = 0;
}

static Node root = new Node();
static HashMap<String, Integer> map = new HashMap<>();

public static void insert(String word, int val) {
int diff = val - map.getOrDefault(word, 0);
map.put(word, val);

Node curr = root;
for (int i = 0; i < word.length(); i++) {
char ch = word.charAt(i);

// alphabet exist nhi krta trie me to nae node bnaenge
if (curr.children[ch - 'a'] == null) {
curr.children[ch - 'a'] = new Node();

}
curr.children[ch - 'a'].score += diff;
curr = curr.children[ch - 'a'];
}

}

public static int sum(String prefix) {
int sum = 0;
Node curr = root;
for (int i = 0; i < prefix.length(); i++) {
char ch = prefix.charAt(i);
if (curr.children[ch - 'a'] == null)
return 0;
curr = curr.children[ch - 'a'];
}

return curr.score;
}
}

No comments:

Post a Comment

Diagonal Traversal

 eg.  1       2       3       4 5      6       7       8 9    10    11     12 13  14   15    16 Output: 1 6 11 16 2 7 12 3 8 4  Approach:...