Trie in a Google Interview

The problem comes from Daily Coding Problem, here it is:

Good morning! Here's your coding interview problem for today.
This problem was asked by Google.
Implement a PrefixMapSum class with the following methods:
  • insert(key: str, value: int): Set a given key's value in the map. If the key already exists, overwrite the value.
  • sum(prefix: str): Return the sum of all values of keys that begin with a given prefix.
For example, you should be able to run the following code:
mapsum.insert("columnar", 3)
assert mapsum.sum("col") == 3
mapsum.insert("column", 2)
assert mapsum.sum("col") == 5

One way to solve this is to build a prefix trie in the following way:
  1. Start with a simple trie implementation: hash table for the children nodes, the cumulative val, whether the node is a word, and the value of the word
  2. When adding the word, set the cumulative along the way and check whether the current node is a word
  3. If it is, make sure to return the word value in a ref variable to be dealt with later
  4. In the outer code, when you're adding the word, if the word already exists (see #3), remove it from cumulative
  5. The prefix cumulative call becomes straightforward
This leads to a O(2*Len(word))-time insert cost, and O(Len(prefix))-time cumulative cost. Code is below and right here on Git: https://github.com/marcelodebarros/dailycodingproblem/blob/master/DailyCodingProbem05042019.cs

Cheers, ACC.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Collections;
namespace DailyCodingProblem
{
 class DailyCodingProbem05042019
 {
 public void Process()
 {
 PrefixSumTrie pst = new PrefixSumTrie();
 pst.AddWord("foo", 5);
 pst.AddWord("foobar", 15);
 string prefix = "foo";
 Console.WriteLine("Cummulative for {0}: {1}", prefix, pst.Cummulative(prefix));
 pst.AddWord("foo", 15);
 Console.WriteLine("Cummulative for {0}: {1}", prefix, pst.Cummulative(prefix));
 pst.AddWord("foofighters", 100);
 Console.WriteLine("Cummulative for {0}: {1}", prefix, pst.Cummulative(prefix));
 }
 }
 class PrefixSumTrie
 {
 private Hashtable children = null;
 private bool isWord = false;
 private int cummulative = 0;
 private int wordVal = 0;
 public PrefixSumTrie()
 {
 children = new Hashtable();
 isWord = false;
 cummulative = 0;
 wordVal = 0;
 }
 public void AddWord(string word, int val)
 {
 int previousVal = -1;
 AddWord(word, val, ref previousVal);
 if (previousVal> 0)
 {
 RemoveWord(word, previousVal);
 }
 }
 public int Cummulative(string prefix)
 {
 if (String.IsNullOrEmpty(prefix))
 {
 return cummulative;
 }
 if (children.ContainsKey(prefix[0]))
 {
 return ((PrefixSumTrie)children[prefix[0]]).Cummulative(prefix.Substring(1));
 }
 return 0;
 }
 private void AddWord(string word, int val, ref int previousVal)
 {
 cummulative += val;
 if (String.IsNullOrEmpty(word))
 {
 if (isWord)
 {
 previousVal = wordVal;
 }
 isWord = true;
 wordVal = val;
 }
 else
 {
 if (!children.ContainsKey(word[0]))
 {
 children.Add(word[0], new PrefixSumTrie());
 }
 PrefixSumTrie child = (PrefixSumTrie)children[word[0]];
 child.AddWord(word.Substring(1), val, ref previousVal);
 }
 }
 private void RemoveWord(string word, int val)
 {
 if (cummulative> 0)
 {
 cummulative -= val;
 }
 if (!String.IsNullOrEmpty(word) && children.ContainsKey(word[0]))
 {
 ((PrefixSumTrie)children[word[0]]).RemoveWord(word.Substring(1), val);
 }
 }
 }
}

Comments

Post a Comment

[フレーム]

Popular posts from this blog

Quasi FSM (Finite State Machine) problem + Vibe

Not really an FSM problem since the state isn't changing, it is just defined by the current input. Simply following the instructions should do it. Using VSCode IDE you can also engage the help of Cline or Copilot for a combo of coding and vibe coding, see below screenshot. Cheers, ACC. Process String with Special Operations I - LeetCode You are given a string  s  consisting of lowercase English letters and the special characters:  * ,  # , and  % . Build a new string  result  by processing  s  according to the following rules from left to right: If the letter is a  lowercase  English letter append it to  result . A  '*'   removes  the last character from  result , if it exists. A  '#'   duplicates  the current  result  and  appends  it to itself. A  '%'   reverses  the current  result . Return the final string  result  after processing all char...

Shortest Bridge – A BFS Story (with a Twist)

Here's another one from the Google 30 Days challenge on LeetCode — 934. Shortest Bridge . The goal? Given a 2D binary grid where two islands (groups of 1s) are separated by water (0s), flip the fewest number of 0s to 1s to connect them. Easy to describe. Sneaky to implement well. 🧭 My Approach My solution follows a two-phase Breadth-First Search (BFS) strategy: Find and mark one island : I start by scanning the grid until I find the first 1 , then use BFS to mark all connected land cells as 2 . I store their positions for later use. Bridge-building BFS : For each cell in the marked island, I run a BFS looking for the second island. Each BFS stops as soon as it hits a cell with value 1 . The minimum distance across all these searches gives the shortest bridge. πŸ” Code Snippet Here's the core logic simplified: public int ShortestBridge(int[][] grid) { // 1. Mark one island as '2' and gather its coordinates List<int> island = FindAndMark...

Classic Dynamic Programming IX

A bit of vibe code together with OpenAI O3. I asked O3 to just generate the sieve due to laziness. Sieve is used to calculate the first M primes (when I was using Miller-Rabin, was giving me TLE). The DP follows from that in a straightforward way: calculate the numbers from i..n-1, then n follows by calculating the min over all M primes. Notice that I made use of Goldbach's Conjecture as a way to optimize the code too. Goldbach's Conjecture estates that any even number greater than 2 is the sum of 2 primes. The conjecture is applied in the highlighted line. Cheers, ACC. PS: the prompt for the sieve was the following, again using Open AI O3 Advanced Reasoning: " give me a sieve to find the first M prime numbers in C#. The code should produce a List<int> with the first M primes " Minimum Number of Primes to Sum to Target - LeetCode You are given two integers  n  and  m . You have to select a multiset of  prime numbers  from the  first   m  pri...