Number Stream to Intervals - Amazon Top Interview Questions


Problem Statement :


Implement a data structure with the following methods:

StreamSummary() constructs a new instance.

add(int val) adds the number val to the instance.

int[][] get() returns a sorted list of disjoint intervals summarizing the numbers we've seen so far.

Constraints

n ≤ 10,000 where n is the number of calls to add

m ≤ 10,000 where n is the number of calls to get

Example 1

Input

methods = ["constructor", "add", "add", "add", "add", "get"]

arguments = [[], [1], [3], [2], [9], []]`

Output

[None, None, None, None, None, [
    [1, 3],
    [9, 9]
]]

Explanation

s = StreamSummary()

s.add(1)

s.add(3)

s.add(2)

s.add(9)

s.get() == [[1, 3], [9, 9]]

Example 2

Input

methods = ["constructor", "add", "add", "add", "add", "get"]

arguments = [[], [1], [2], [4], [3], []]`

Output

[None, None, None, None, None, [
    [1, 4]
]]

Explanation

s = StreamSummary()

s.add(1)

s.add(2)

s.add(4)

s.add(3)

s.get() == [[1, 4]]



Solution :



title-img




                        Solution in C++ :

class StreamSummary {
    public:
    map<int, int> s;
    unordered_map<int, int> e;
    void add(int val) {
        if (e.count(val - 1) and s.count(val + 1)) {
            int prevstart = e[val - 1];
            int nextend = s[val + 1];
            s.erase(val + 1);
            e.erase(val - 1);
            s[prevstart] = nextend;
            e[nextend] = prevstart;
        } else if (e.count(val - 1)) {
            int prevstart = e[val - 1];
            e.erase(val - 1);
            s[prevstart] = val;
            e[val] = prevstart;
        } else if (s.count(val + 1)) {
            int nextend = s[val + 1];
            s.erase(val + 1);
            s[val] = nextend;
            e[nextend] = val;
        } else {
            e[val] = val;
            s[val] = val;
        }
    }

    vector<vector<int>> get() {
        vector<vector<int>> ret;
        for (auto [st, en] : s) {
            ret.push_back({st, en});
        }
        return ret;
    }
};
                    


                        Solution in Java :

import java.util.*;

class StreamSummary {
    private TreeMap<Integer, Integer> myMap;

    public StreamSummary() {
        myMap = new TreeMap<>();
    }

    public void add(int val) {
        if (myMap.containsKey(val)) {
            // nothing to do. alreayd covered.
            return;
        }

        Integer lower = myMap.lowerKey(val);
        if (lower == null) {
            // we got a smallest number
            caseSmallest(val);
            return;
        } else {
            caseInsertLower(lower, val);
            return;
        }
    }

    // we got a smallest number
    private void caseSmallest(int key) {
        int nextKey = key + 1;
        Integer value = myMap.get(nextKey);
        if (value != null) {
            // we need to merge
            // delete the old one first
            myMap.remove(nextKey);
            myMap.put(key, value);
        } else {
            // stand-alone key
            myMap.put(key, key);
        }
    }

    // lower < newVal
    // lower: a key
    private void caseInsertLower(int lower, int newVal) {
        Integer val = myMap.get(lower);
        if (newVal <= val) {
            // newVal is already convered
            return;
        }

        Integer higher = myMap.get(newVal + 1);
        if ((((val + 1) == newVal)) && (higher != null)) {
            // merge both. case: (1,1),(3,3), and we are adding 2, we should have (1,3)
            myMap.put(lower, higher);
            myMap.remove(newVal + 1);
        } else if (((val + 1) == newVal) && (higher == null)) {
            // case: (1,1),(4,4) and we are adding 2. we should have (1,2) and (4,4)
            myMap.put(lower, newVal);
        } else if (higher != null) {
            myMap.remove(newVal + 1);
            myMap.put(newVal, higher);
        } else {
            // no need to merge
            myMap.put(newVal, newVal);
        }
    }

    public int[][] get() {
        int[][] array = new int[myMap.size()][2];
        Iterator<Map.Entry<Integer, Integer>> it;
        it = myMap.entrySet().iterator();
        int count = 0;
        while (it.hasNext()) {
            Map.Entry<Integer, Integer> en = it.next();
            array[count][0] = en.getKey();
            array[count][1] = en.getValue();
            count++;
        }
        return (array);
    }
}
                    




View More Similar Problems

Tree: Level Order Traversal

Given a pointer to the root of a binary tree, you need to print the level order traversal of this tree. In level-order traversal, nodes are visited level by level from left to right. Complete the function levelOrder and print the values in a single line separated by a space. For example: 1 \ 2 \ 5 / \ 3 6 \ 4 F

View Solution →

Binary Search Tree : Insertion

You are given a pointer to the root of a binary search tree and values to be inserted into the tree. Insert the values into their appropriate position in the binary search tree and return the root of the updated binary tree. You just have to complete the function. Input Format You are given a function, Node * insert (Node * root ,int data) { } Constraints No. of nodes in the tree <

View Solution →

Tree: Huffman Decoding

Huffman coding assigns variable length codewords to fixed length input characters based on their frequencies. More frequent characters are assigned shorter codewords and less frequent characters are assigned longer codewords. All edges along the path to a character contain a code digit. If they are on the left side of the tree, they will be a 0 (zero). If on the right, they'll be a 1 (one). Only t

View Solution →

Binary Search Tree : Lowest Common Ancestor

You are given pointer to the root of the binary search tree and two values v1 and v2. You need to return the lowest common ancestor (LCA) of v1 and v2 in the binary search tree. In the diagram above, the lowest common ancestor of the nodes 4 and 6 is the node 3. Node 3 is the lowest node which has nodes and as descendants. Function Description Complete the function lca in the editor b

View Solution →

Swap Nodes [Algo]

A binary tree is a tree which is characterized by one of the following properties: It can be empty (null). It contains a root node only. It contains a root node with a left subtree, a right subtree, or both. These subtrees are also binary trees. In-order traversal is performed as Traverse the left subtree. Visit root. Traverse the right subtree. For this in-order traversal, start from

View Solution →

Kitty's Calculations on a Tree

Kitty has a tree, T , consisting of n nodes where each node is uniquely labeled from 1 to n . Her friend Alex gave her q sets, where each set contains k distinct nodes. Kitty needs to calculate the following expression on each set: where: { u ,v } denotes an unordered pair of nodes belonging to the set. dist(u , v) denotes the number of edges on the unique (shortest) path between nodes a

View Solution →