Work in HR? Unlock Free Profile

Google Software Engineer Interview Question (student candidate)

"Design a class to record a lot of ints, and make it efficient to retrieve the median."
Add Tags [?]

Part of a Software Engineer Interview Review - one of 3,031 Google Interview Reviews

Answers & Comments

of 2
class EffMed {
    void add(int n) {
        vector<int>::iterator it = els.begin();
        while(it != els.end() && *it < n) ++it;
        els.insert(it, n);

    void remove(int index) {
        els.erase(els.begin() + index);

    float median() {
        int medIndex = els.size() >> 1;
        if(medIndex << 1 == els.size())
            return (els[medIndex - 1] + els[medIndex]) / 2.0;
            return els[medIndex];

    vector<int> els;
- Asa on Jul 9, 2012
of 0
Use two heaps (min and max) and maintain equal number of elements in it (at most one more element). Median will be always on top of one of heap or average of two top elements. So request will be O(1) time and insertion will be O(logN)
- Konstantin on Aug 14, 2012

To comment on this question, Sign In with Facebook or Sign Up

Tags are like keywords that help categorize interview questions that have something in common.