{ "data": { "question": { "questionId": "295", "questionFrontendId": "295", "boundTopicId": null, "title": "Find Median from Data Stream", "titleSlug": "find-median-from-data-stream", "content": "

The median is the middle value in an ordered integer list. If the size of the list is even, there is no middle value and the median is the mean of the two middle values.

\n\n\n\n

Implement the MedianFinder class:

\n\n\n\n

 

\n

Example 1:

\n\n
\nInput\n["MedianFinder", "addNum", "addNum", "findMedian", "addNum", "findMedian"]\n[[], [1], [2], [], [3], []]\nOutput\n[null, null, null, 1.5, null, 2.0]\n\nExplanation\nMedianFinder medianFinder = new MedianFinder();\nmedianFinder.addNum(1);    // arr = [1]\nmedianFinder.addNum(2);    // arr = [1, 2]\nmedianFinder.findMedian(); // return 1.5 (i.e., (1 + 2) / 2)\nmedianFinder.addNum(3);    // arr[1, 2, 3]\nmedianFinder.findMedian(); // return 2.0\n
\n\n

 

\n

Constraints:

\n\n\n\n

 

\n

Follow up:

\n\n\n", "translatedTitle": null, "translatedContent": null, "isPaidOnly": false, "difficulty": "Hard", "likes": 6692, "dislikes": 123, "isLiked": null, "similarQuestions": "[{\"title\": \"Sliding Window Median\", \"titleSlug\": \"sliding-window-median\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Finding MK Average\", \"titleSlug\": \"finding-mk-average\", \"difficulty\": \"Hard\", \"translatedTitle\": null}, {\"title\": \"Sequentially Ordinal Rank Tracker\", \"titleSlug\": \"sequentially-ordinal-rank-tracker\", \"difficulty\": \"Hard\", \"translatedTitle\": null}]", "exampleTestcases": "[\"MedianFinder\",\"addNum\",\"addNum\",\"findMedian\",\"addNum\",\"findMedian\"]\n[[],[1],[2],[],[3],[]]", "categoryTitle": "Algorithms", "contributors": [], "topicTags": [ { "name": "Two Pointers", "slug": "two-pointers", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Design", "slug": "design", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Sorting", "slug": "sorting", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Heap (Priority Queue)", "slug": "heap-priority-queue", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Data Stream", "slug": "data-stream", "translatedName": null, "__typename": "TopicTagNode" } ], "companyTagStats": null, "codeSnippets": [ { "lang": "C++", "langSlug": "cpp", "code": "class MedianFinder {\npublic:\n MedianFinder() {\n \n }\n \n void addNum(int num) {\n \n }\n \n double findMedian() {\n \n }\n};\n\n/**\n * Your MedianFinder object will be instantiated and called as such:\n * MedianFinder* obj = new MedianFinder();\n * obj->addNum(num);\n * double param_2 = obj->findMedian();\n */", "__typename": "CodeSnippetNode" }, { "lang": "Java", "langSlug": "java", "code": "class MedianFinder {\n\n public MedianFinder() {\n \n }\n \n public void addNum(int num) {\n \n }\n \n public double findMedian() {\n \n }\n}\n\n/**\n * Your MedianFinder object will be instantiated and called as such:\n * MedianFinder obj = new MedianFinder();\n * obj.addNum(num);\n * double param_2 = obj.findMedian();\n */", "__typename": "CodeSnippetNode" }, { "lang": "Python", "langSlug": "python", "code": "class MedianFinder(object):\n\n def __init__(self):\n \n\n def addNum(self, num):\n \"\"\"\n :type num: int\n :rtype: None\n \"\"\"\n \n\n def findMedian(self):\n \"\"\"\n :rtype: float\n \"\"\"\n \n\n\n# Your MedianFinder object will be instantiated and called as such:\n# obj = MedianFinder()\n# obj.addNum(num)\n# param_2 = obj.findMedian()", "__typename": "CodeSnippetNode" }, { "lang": "Python3", "langSlug": "python3", "code": "class MedianFinder:\n\n def __init__(self):\n \n\n def addNum(self, num: int) -> None:\n \n\n def findMedian(self) -> float:\n \n\n\n# Your MedianFinder object will be instantiated and called as such:\n# obj = MedianFinder()\n# obj.addNum(num)\n# param_2 = obj.findMedian()", "__typename": "CodeSnippetNode" }, { "lang": "C", "langSlug": "c", "code": "\n\n\ntypedef struct {\n \n} MedianFinder;\n\n\nMedianFinder* medianFinderCreate() {\n \n}\n\nvoid medianFinderAddNum(MedianFinder* obj, int num) {\n \n}\n\ndouble medianFinderFindMedian(MedianFinder* obj) {\n \n}\n\nvoid medianFinderFree(MedianFinder* obj) {\n \n}\n\n/**\n * Your MedianFinder struct will be instantiated and called as such:\n * MedianFinder* obj = medianFinderCreate();\n * medianFinderAddNum(obj, num);\n \n * double param_2 = medianFinderFindMedian(obj);\n \n * medianFinderFree(obj);\n*/", "__typename": "CodeSnippetNode" }, { "lang": "C#", "langSlug": "csharp", "code": "public class MedianFinder {\n\n public MedianFinder() {\n \n }\n \n public void AddNum(int num) {\n \n }\n \n public double FindMedian() {\n \n }\n}\n\n/**\n * Your MedianFinder object will be instantiated and called as such:\n * MedianFinder obj = new MedianFinder();\n * obj.AddNum(num);\n * double param_2 = obj.FindMedian();\n */", "__typename": "CodeSnippetNode" }, { "lang": "JavaScript", "langSlug": "javascript", "code": "\nvar MedianFinder = function() {\n \n};\n\n/** \n * @param {number} num\n * @return {void}\n */\nMedianFinder.prototype.addNum = function(num) {\n \n};\n\n/**\n * @return {number}\n */\nMedianFinder.prototype.findMedian = function() {\n \n};\n\n/** \n * Your MedianFinder object will be instantiated and called as such:\n * var obj = new MedianFinder()\n * obj.addNum(num)\n * var param_2 = obj.findMedian()\n */", "__typename": "CodeSnippetNode" }, { "lang": "Ruby", "langSlug": "ruby", "code": "class MedianFinder\n def initialize()\n \n end\n\n\n=begin\n :type num: Integer\n :rtype: Void\n=end\n def add_num(num)\n \n end\n\n\n=begin\n :rtype: Float\n=end\n def find_median()\n \n end\n\n\nend\n\n# Your MedianFinder object will be instantiated and called as such:\n# obj = MedianFinder.new()\n# obj.add_num(num)\n# param_2 = obj.find_median()", "__typename": "CodeSnippetNode" }, { "lang": "Swift", "langSlug": "swift", "code": "\nclass MedianFinder {\n\n init() {\n \n }\n \n func addNum(_ num: Int) {\n \n }\n \n func findMedian() -> Double {\n \n }\n}\n\n/**\n * Your MedianFinder object will be instantiated and called as such:\n * let obj = MedianFinder()\n * obj.addNum(num)\n * let ret_2: Double = obj.findMedian()\n */", "__typename": "CodeSnippetNode" }, { "lang": "Go", "langSlug": "golang", "code": "type MedianFinder struct {\n \n}\n\n\nfunc Constructor() MedianFinder {\n \n}\n\n\nfunc (this *MedianFinder) AddNum(num int) {\n \n}\n\n\nfunc (this *MedianFinder) FindMedian() float64 {\n \n}\n\n\n/**\n * Your MedianFinder object will be instantiated and called as such:\n * obj := Constructor();\n * obj.AddNum(num);\n * param_2 := obj.FindMedian();\n */", "__typename": "CodeSnippetNode" }, { "lang": "Scala", "langSlug": "scala", "code": "class MedianFinder() {\n\n def addNum(num: Int) {\n \n }\n\n def findMedian(): Double = {\n \n }\n\n}\n\n/**\n * Your MedianFinder object will be instantiated and called as such:\n * var obj = new MedianFinder()\n * obj.addNum(num)\n * var param_2 = obj.findMedian()\n */", "__typename": "CodeSnippetNode" }, { "lang": "Kotlin", "langSlug": "kotlin", "code": "class MedianFinder() {\n\n fun addNum(num: Int) {\n \n }\n\n fun findMedian(): Double {\n \n }\n\n}\n\n/**\n * Your MedianFinder object will be instantiated and called as such:\n * var obj = MedianFinder()\n * obj.addNum(num)\n * var param_2 = obj.findMedian()\n */", "__typename": "CodeSnippetNode" }, { "lang": "Rust", "langSlug": "rust", "code": "struct MedianFinder {\n\n}\n\n\n/** \n * `&self` means the method takes an immutable reference.\n * If you need a mutable reference, change it to `&mut self` instead.\n */\nimpl MedianFinder {\n\n fn new() -> Self {\n \n }\n \n fn add_num(&self, num: i32) {\n \n }\n \n fn find_median(&self) -> f64 {\n \n }\n}\n\n/**\n * Your MedianFinder object will be instantiated and called as such:\n * let obj = MedianFinder::new();\n * obj.add_num(num);\n * let ret_2: f64 = obj.find_median();\n */", "__typename": "CodeSnippetNode" }, { "lang": "PHP", "langSlug": "php", "code": "class MedianFinder {\n /**\n */\n function __construct() {\n \n }\n \n /**\n * @param Integer $num\n * @return NULL\n */\n function addNum($num) {\n \n }\n \n /**\n * @return Float\n */\n function findMedian() {\n \n }\n}\n\n/**\n * Your MedianFinder object will be instantiated and called as such:\n * $obj = MedianFinder();\n * $obj->addNum($num);\n * $ret_2 = $obj->findMedian();\n */", "__typename": "CodeSnippetNode" }, { "lang": "TypeScript", "langSlug": "typescript", "code": "class MedianFinder {\n constructor() {\n\n }\n\n addNum(num: number): void {\n\n }\n\n findMedian(): number {\n\n }\n}\n\n/**\n * Your MedianFinder object will be instantiated and called as such:\n * var obj = new MedianFinder()\n * obj.addNum(num)\n * var param_2 = obj.findMedian()\n */", "__typename": "CodeSnippetNode" }, { "lang": "Racket", "langSlug": "racket", "code": "(define median-finder%\n (class object%\n (super-new)\n (init-field)\n \n ; add-num : exact-integer? -> void?\n (define/public (add-num num)\n\n )\n ; find-median : -> flonum?\n (define/public (find-median)\n\n )))\n\n;; Your median-finder% object will be instantiated and called as such:\n;; (define obj (new median-finder%))\n;; (send obj add-num num)\n;; (define param_2 (send obj find-median))", "__typename": "CodeSnippetNode" }, { "lang": "Erlang", "langSlug": "erlang", "code": "-spec median_finder_init_() -> any().\nmedian_finder_init_() ->\n .\n\n-spec median_finder_add_num(Num :: integer()) -> any().\nmedian_finder_add_num(Num) ->\n .\n\n-spec median_finder_find_median() -> float().\nmedian_finder_find_median() ->\n .\n\n\n%% Your functions will be called as such:\n%% median_finder_init_(),\n%% median_finder_add_num(Num),\n%% Param_2 = median_finder_find_median(),\n\n%% median_finder_init_ will be called before every test case, in which you can do some necessary initializations.", "__typename": "CodeSnippetNode" }, { "lang": "Elixir", "langSlug": "elixir", "code": "defmodule MedianFinder do\n @spec init_() :: any\n def init_() do\n\n end\n\n @spec add_num(num :: integer) :: any\n def add_num(num) do\n\n end\n\n @spec find_median() :: float\n def find_median() do\n\n end\nend\n\n# Your functions will be called as such:\n# MedianFinder.init_()\n# MedianFinder.add_num(num)\n# param_2 = MedianFinder.find_median()\n\n# MedianFinder.init_ will be called before every test case, in which you can do some necessary initializations.", "__typename": "CodeSnippetNode" } ], "stats": "{\"totalAccepted\": \"448.7K\", \"totalSubmission\": \"892.3K\", \"totalAcceptedRaw\": 448670, \"totalSubmissionRaw\": 892313, \"acRate\": \"50.3%\"}", "hints": [], "solution": { "id": "85", "canSeeDetail": false, "paidOnly": true, "hasVideoSolution": false, "paidOnlyVideo": true, "__typename": "ArticleNode" }, "status": null, "sampleTestCase": "[\"MedianFinder\",\"addNum\",\"addNum\",\"findMedian\",\"addNum\",\"findMedian\"]\n[[],[1],[2],[],[3],[]]", "metaData": "{\n \"classname\": \"MedianFinder\",\n \"constructor\": {\n \"params\": []\n },\n \"methods\": [\n {\n \"params\": [\n {\n \"type\": \"integer\",\n \"name\": \"num\"\n }\n ],\n \"name\": \"addNum\",\n \"return\": {\n \"type\": \"void\"\n }\n },\n {\n \"params\": [],\n \"name\": \"findMedian\",\n \"return\": {\n \"type\": \"double\"\n }\n }\n ],\n \"return\": {\n \"type\": \"boolean\"\n },\n \"systemdesign\": true\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "enableTestMode": false, "enableDebugger": true, "envInfo": "{\"cpp\": [\"C++\", \"

Compiled with clang 11 using the latest C++ 17 standard.

\\r\\n\\r\\n

Your code is compiled with level two optimization (-O2). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\"], \"java\": [\"Java\", \"

OpenJDK 17 . Java 8 features such as lambda expressions and stream API can be used.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n

Includes Pair class from https://docs.oracle.com/javase/8/javafx/api/javafx/util/Pair.html.

\"], \"python\": [\"Python\", \"

Python 2.7.12.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\\r\\n\\r\\n

Note that Python 2.7 will not be maintained past 2020. For the latest Python, please choose Python3 instead.

\"], \"c\": [\"C\", \"

Compiled with gcc 8.2 using the gnu99 standard.

\\r\\n\\r\\n

Your code is compiled with level one optimization (-O1). AddressSanitizer is also enabled to help detect out-of-bounds and use-after-free bugs.

\\r\\n\\r\\n

Most standard library headers are already included automatically for your convenience.

\\r\\n\\r\\n

For hash table operations, you may use uthash. \\\"uthash.h\\\" is included by default. Below are some examples:

\\r\\n\\r\\n

1. Adding an item to a hash.\\r\\n

\\r\\nstruct hash_entry {\\r\\n    int id;            /* we'll use this field as the key */\\r\\n    char name[10];\\r\\n    UT_hash_handle hh; /* makes this structure hashable */\\r\\n};\\r\\n\\r\\nstruct hash_entry *users = NULL;\\r\\n\\r\\nvoid add_user(struct hash_entry *s) {\\r\\n    HASH_ADD_INT(users, id, s);\\r\\n}\\r\\n
\\r\\n

\\r\\n\\r\\n

2. Looking up an item in a hash:\\r\\n

\\r\\nstruct hash_entry *find_user(int user_id) {\\r\\n    struct hash_entry *s;\\r\\n    HASH_FIND_INT(users, &user_id, s);\\r\\n    return s;\\r\\n}\\r\\n
\\r\\n

\\r\\n\\r\\n

3. Deleting an item in a hash:\\r\\n

\\r\\nvoid delete_user(struct hash_entry *user) {\\r\\n    HASH_DEL(users, user);  \\r\\n}\\r\\n
\\r\\n

\"], \"csharp\": [\"C#\", \"

C# 10 with .NET 6 runtime

\\r\\n\\r\\n

Your code is compiled with debug flag enabled (/debug).

\"], \"javascript\": [\"JavaScript\", \"

Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES6 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\\r\\n\\r\\n

For Priority Queue / Queue data structures, you may use datastructures-js/priority-queue and datastructures-js/queue.

\"], \"ruby\": [\"Ruby\", \"

Ruby 3.1

\\r\\n\\r\\n

Some common data structure implementations are provided in the Algorithms module: https://www.rubydoc.info/github/kanwei/algorithms/Algorithms

\"], \"swift\": [\"Swift\", \"

Swift 5.5.2.

\"], \"golang\": [\"Go\", \"

Go 1.17.6.

\\r\\n\\r\\n

Support https://godoc.org/github.com/emirpasic/gods library.

\"], \"python3\": [\"Python3\", \"

Python 3.10.

\\r\\n\\r\\n

Most libraries are already imported automatically for your convenience, such as array, bisect, collections. If you need more libraries, you can import it yourself.

\\r\\n\\r\\n

For Map/TreeMap data structure, you may use sortedcontainers library.

\"], \"scala\": [\"Scala\", \"

Scala 2.13.7.

\"], \"kotlin\": [\"Kotlin\", \"

Kotlin 1.3.10.

\"], \"rust\": [\"Rust\", \"

Rust 1.58.1

\\r\\n\\r\\n

Supports rand v0.6\\u00a0from crates.io

\"], \"php\": [\"PHP\", \"

PHP 8.1.

\\r\\n

With bcmath module

\"], \"typescript\": [\"Typescript\", \"

TypeScript 4.5.4, Node.js 16.13.2.

\\r\\n\\r\\n

Your code is run with --harmony flag, enabling new ES2020 features.

\\r\\n\\r\\n

lodash.js library is included by default.

\"], \"racket\": [\"Racket\", \"

Run with Racket 8.3.

\"], \"erlang\": [\"Erlang\", \"Erlang/OTP 24.2\"], \"elixir\": [\"Elixir\", \"Elixir 1.13.0 with Erlang/OTP 24.2\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": null, "__typename": "QuestionNode" } } }