Bird
Raised Fist0
Interview PreptriesmediumGoogleAmazon

Map Sum Pairs

Choose your preparation mode4 modes available
▶
Steps
setup

Initialize MapSum and Trie Root

Create the MapSum object with an empty root TrieNode and an empty map for key-value pairs.

💡 Initialization sets up the data structures needed for insertions and prefix sum queries.
Line:ms = MapSum()
💡 The root node starts with sum 0 and no children, ready to build the trie.
📊
Map Sum Pairs - Watch the Algorithm Execute, Step by Step
Watching the algorithm step-by-step reveals how the trie accumulates sums for prefixes, which is hard to grasp from code alone.
Step 1/15
·Active fill★Answer cell
insert
insert
apple
insert
apple
a
insert
apple
ap
insert
apple
app
insert
apple
appl
insert
apple
apple
sum
ap
apple
sum
ap
apple
Search: true
insert
app
apple
insert
app
apple
insert
app
apple
insert
app
apple
sum
ap
apple
sum
ap
apple
Search: true

Key Takeaways

✓ Trie nodes store cumulative sums of all keys passing through, enabling efficient prefix sum queries.

This is hard to see from code alone because the sum updates happen incrementally along the path.

✓ Insertions update sums along existing paths without rebuilding the entire trie.

Watching the incremental sum updates clarifies how overlapping prefixes share nodes.

✓ Sum queries traverse only the prefix path and return the stored sum, avoiding scanning all keys.

This efficiency is clear when seeing traversal stop at prefix end and directly read sum.

Practice

(1/5)
1. Given the following Trie implementation, after inserting the words ['cat', 'car', 'dog'], what is the value of node.isEnd after processing the last character of 'car' in the insert method?
easy
A. false, because 'car' shares prefix with 'cat' and 'dog'
B. true, but only if 'car' was inserted before 'cat'
C. false, because isEnd is only set after inserting all words
D. true, because 'car' is a complete inserted word

Solution

  1. Step 1: Trace insertion of 'car'

    For each character 'c', 'a', 'r', nodes are created or reused. After last character 'r', node.isEnd is set to true.
  2. Step 2: Confirm isEnd flag meaning

    isEnd marks the end of a complete word. Since 'car' was inserted, node.isEnd after 'r' is true.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    isEnd is true after inserting 'car' [OK]
Hint: isEnd is set true after inserting each complete word [OK]
Common Mistakes:
  • Assuming isEnd is false if prefix overlaps with other words
2. Consider the following Python code implementing the optimal StreamChecker. Given the words ["cd", "f", "kl"], what is the return value of the query sequence: query('a'), query('b'), query('c'), query('d')? Specifically, what does query('d') return?
class TrieNode:
    def __init__(self):
        self.children = {}
        self.is_word = False

class StreamChecker:
    def __init__(self, words):
        self.root = TrieNode()
        self.max_len = max(len(w) for w in words)
        self.stream = []
        for word in words:
            node = self.root
            for ch in reversed(word):
                if ch not in node.children:
                    node.children[ch] = TrieNode()
                node = node.children[ch]
            node.is_word = True

    def query(self, letter):
        self.stream.append(letter)
        if len(self.stream) > self.max_len:
            self.stream.pop(0)
        node = self.root
        for ch in reversed(self.stream):
            if ch not in node.children:
                return False
            node = node.children[ch]
            if node.is_word:
                return True
        return False

sc = StreamChecker(["cd", "f", "kl"])
print(sc.query('a'))
print(sc.query('b'))
print(sc.query('c'))
print(sc.query('d'))
easy
A. False
B. True
C. Raises an exception
D. None

Solution

  1. Step 1: Trace the stream buffer after queries

    After queries 'a', 'b', 'c', 'd', the stream buffer contains ['a','b','c','d'], but max_len=2, so oldest letters are popped. After 'c', stream=['b','c'], after 'd', stream=['c','d'].
  2. Step 2: Traverse trie with reversed stream

    For query('d'), reversed stream is ['d','c']. Trie has reversed words: 'dc' for 'cd'. Traversing 'd' then 'c' hits is_word=True at 'c' node, so returns True. However, the query sequence is query('a'), query('b'), query('c'), query('d'). The query('c') returns False because 'c' alone is not a word. The query('d') returns True because 'cd' is in the dictionary and the stream buffer contains ['c','d'].
  3. Step 3: Check query('d') return value

    Since the query('d') returns True, the correct answer is True.
  4. Final Answer:

    Option B -> Option B
  5. Quick Check:

    Stream buffer limited to max word length matches 'cd' suffix [OK]
Hint: Stream buffer limited to max word length [OK]
Common Mistakes:
  • Not limiting stream buffer size
  • Not reversing words in trie
  • Returning false too early
3. What is the time complexity of the optimal bitwise trie approach to count pairs with XOR in a range for an input array of size n and maximum number M (max element)?
medium
A. O(n * log M)
B. O(n^2)
C. O(n * M)
D. O(n * log n)

Solution

  1. Step 1: Identify operations per element

    Each number is inserted into the trie in O(log M) time, where M is the max number (bit length).
  2. Step 2: Query per element also takes O(log M)

    For each number, querying the trie for counts less than a limit also takes O(log M).
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    Overall complexity is O(n * log M) due to insert and query per element [OK]
Hint: Trie operations scale with bit length, not array size squared [OK]
Common Mistakes:
  • Assuming O(n^2) due to pairs
  • Confusing M with n in complexity
  • Ignoring log factor from bit length
4. What is the time complexity of the optimal bitwise trie approach to find the maximum XOR of two numbers in an array of size n, assuming 32-bit integers?
medium
A. O(n^2)
B. O(n * log n)
C. O(32^2 * n)
D. O(n * 32)

Solution

  1. Step 1: Identify loops in the algorithm

    We insert each of the n numbers into the trie, iterating over 32 bits each time -> O(n * 32).
  2. Step 2: Find max XOR by traversing trie for each number

    Again, for each number, we traverse 32 bits -> O(n * 32).
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    32 is constant, so complexity is linear in n times 32 bits [OK]
Hint: Each number processed over fixed 32 bits [OK]
Common Mistakes:
  • Mistaking complexity as O(n^2) due to pairwise XOR
5. What is the time complexity of processing Q queries using the optimal StreamChecker approach that builds a trie of reversed words and maintains a stream buffer limited to the maximum word length L? Assume W words with maximum length L. Choose the most accurate complexity.
medium
A. O(Q * W * L)
B. O(Q * L^2)
C. O(Q * L)
D. O(Q + W * L)

Solution

  1. Step 1: Identify operations per query

    Each query appends a letter and traverses at most L nodes in the trie (limited by max word length).
  2. Step 2: Calculate total complexity

    Building the trie takes O(W * L) once. Each query takes O(L) time. Total is O(Q * L) for queries plus O(W * L) for setup, dominated by O(Q * L) for large Q.
  3. Final Answer:

    Option C -> Option C
  4. Quick Check:

    Traversal limited to max word length L per query [OK]
Hint: Traversal limited to max word length L per query [OK]
Common Mistakes:
  • Confusing brute force O(Q*W*L) with trie approach
  • Assuming quadratic in L
  • Ignoring trie build cost
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard