{ "data": { "question": { "questionId": "789", "questionFrontendId": "703", "boundTopicId": null, "title": "Kth Largest Element in a Stream", "titleSlug": "kth-largest-element-in-a-stream", "content": "

Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element.

\n\n

Implement KthLargest class:

\n\n\n\n

 

\n

Example 1:

\n\n
\nInput\n["KthLargest", "add", "add", "add", "add", "add"]\n[[3, [4, 5, 8, 2]], [3], [5], [10], [9], [4]]\nOutput\n[null, 4, 5, 5, 8, 8]\n\nExplanation\nKthLargest kthLargest = new KthLargest(3, [4, 5, 8, 2]);\nkthLargest.add(3);   // return 4\nkthLargest.add(5);   // return 5\nkthLargest.add(10);  // return 5\nkthLargest.add(9);   // return 8\nkthLargest.add(4);   // return 8\n
\n\n

 

\n

Constraints:

\n\n\n", "translatedTitle": null, "translatedContent": null, "isPaidOnly": false, "difficulty": "Easy", "likes": 5193, "dislikes": 3251, "isLiked": null, "similarQuestions": "[{\"title\": \"Kth Largest Element in an Array\", \"titleSlug\": \"kth-largest-element-in-an-array\", \"difficulty\": \"Medium\", \"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": "[\"KthLargest\",\"add\",\"add\",\"add\",\"add\",\"add\"]\n[[3,[4,5,8,2]],[3],[5],[10],[9],[4]]", "categoryTitle": "Algorithms", "contributors": [], "topicTags": [ { "name": "Tree", "slug": "tree", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Design", "slug": "design", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Binary Search Tree", "slug": "binary-search-tree", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Heap (Priority Queue)", "slug": "heap-priority-queue", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Binary Tree", "slug": "binary-tree", "translatedName": null, "__typename": "TopicTagNode" }, { "name": "Data Stream", "slug": "data-stream", "translatedName": null, "__typename": "TopicTagNode" } ], "companyTagStats": null, "codeSnippets": [ { "lang": "C++", "langSlug": "cpp", "code": "class KthLargest {\npublic:\n KthLargest(int k, vector& nums) {\n \n }\n \n int add(int val) {\n \n }\n};\n\n/**\n * Your KthLargest object will be instantiated and called as such:\n * KthLargest* obj = new KthLargest(k, nums);\n * int param_1 = obj->add(val);\n */", "__typename": "CodeSnippetNode" }, { "lang": "Java", "langSlug": "java", "code": "class KthLargest {\n\n public KthLargest(int k, int[] nums) {\n \n }\n \n public int add(int val) {\n \n }\n}\n\n/**\n * Your KthLargest object will be instantiated and called as such:\n * KthLargest obj = new KthLargest(k, nums);\n * int param_1 = obj.add(val);\n */", "__typename": "CodeSnippetNode" }, { "lang": "Python", "langSlug": "python", "code": "class KthLargest(object):\n\n def __init__(self, k, nums):\n \"\"\"\n :type k: int\n :type nums: List[int]\n \"\"\"\n \n\n def add(self, val):\n \"\"\"\n :type val: int\n :rtype: int\n \"\"\"\n \n\n\n# Your KthLargest object will be instantiated and called as such:\n# obj = KthLargest(k, nums)\n# param_1 = obj.add(val)", "__typename": "CodeSnippetNode" }, { "lang": "Python3", "langSlug": "python3", "code": "class KthLargest:\n\n def __init__(self, k: int, nums: List[int]):\n \n\n def add(self, val: int) -> int:\n \n\n\n# Your KthLargest object will be instantiated and called as such:\n# obj = KthLargest(k, nums)\n# param_1 = obj.add(val)", "__typename": "CodeSnippetNode" }, { "lang": "C", "langSlug": "c", "code": "\n\n\ntypedef struct {\n \n} KthLargest;\n\n\nKthLargest* kthLargestCreate(int k, int* nums, int numsSize) {\n \n}\n\nint kthLargestAdd(KthLargest* obj, int val) {\n \n}\n\nvoid kthLargestFree(KthLargest* obj) {\n \n}\n\n/**\n * Your KthLargest struct will be instantiated and called as such:\n * KthLargest* obj = kthLargestCreate(k, nums, numsSize);\n * int param_1 = kthLargestAdd(obj, val);\n \n * kthLargestFree(obj);\n*/", "__typename": "CodeSnippetNode" }, { "lang": "C#", "langSlug": "csharp", "code": "public class KthLargest {\n\n public KthLargest(int k, int[] nums) {\n \n }\n \n public int Add(int val) {\n \n }\n}\n\n/**\n * Your KthLargest object will be instantiated and called as such:\n * KthLargest obj = new KthLargest(k, nums);\n * int param_1 = obj.Add(val);\n */", "__typename": "CodeSnippetNode" }, { "lang": "JavaScript", "langSlug": "javascript", "code": "/**\n * @param {number} k\n * @param {number[]} nums\n */\nvar KthLargest = function(k, nums) {\n \n};\n\n/** \n * @param {number} val\n * @return {number}\n */\nKthLargest.prototype.add = function(val) {\n \n};\n\n/** \n * Your KthLargest object will be instantiated and called as such:\n * var obj = new KthLargest(k, nums)\n * var param_1 = obj.add(val)\n */", "__typename": "CodeSnippetNode" }, { "lang": "TypeScript", "langSlug": "typescript", "code": "class KthLargest {\n constructor(k: number, nums: number[]) {\n \n }\n\n add(val: number): number {\n \n }\n}\n\n/**\n * Your KthLargest object will be instantiated and called as such:\n * var obj = new KthLargest(k, nums)\n * var param_1 = obj.add(val)\n */", "__typename": "CodeSnippetNode" }, { "lang": "PHP", "langSlug": "php", "code": "class KthLargest {\n /**\n * @param Integer $k\n * @param Integer[] $nums\n */\n function __construct($k, $nums) {\n \n }\n \n /**\n * @param Integer $val\n * @return Integer\n */\n function add($val) {\n \n }\n}\n\n/**\n * Your KthLargest object will be instantiated and called as such:\n * $obj = KthLargest($k, $nums);\n * $ret_1 = $obj->add($val);\n */", "__typename": "CodeSnippetNode" }, { "lang": "Swift", "langSlug": "swift", "code": "\nclass KthLargest {\n\n init(_ k: Int, _ nums: [Int]) {\n \n }\n \n func add(_ val: Int) -> Int {\n \n }\n}\n\n/**\n * Your KthLargest object will be instantiated and called as such:\n * let obj = KthLargest(k, nums)\n * let ret_1: Int = obj.add(val)\n */", "__typename": "CodeSnippetNode" }, { "lang": "Kotlin", "langSlug": "kotlin", "code": "class KthLargest(k: Int, nums: IntArray) {\n\n fun add(`val`: Int): Int {\n \n }\n\n}\n\n/**\n * Your KthLargest object will be instantiated and called as such:\n * var obj = KthLargest(k, nums)\n * var param_1 = obj.add(`val`)\n */", "__typename": "CodeSnippetNode" }, { "lang": "Dart", "langSlug": "dart", "code": "class KthLargest {\n\n KthLargest(int k, List nums) {\n \n }\n \n int add(int val) {\n \n }\n}\n\n/**\n * Your KthLargest object will be instantiated and called as such:\n * KthLargest obj = KthLargest(k, nums);\n * int param1 = obj.add(val);\n */", "__typename": "CodeSnippetNode" }, { "lang": "Go", "langSlug": "golang", "code": "type KthLargest struct {\n \n}\n\n\nfunc Constructor(k int, nums []int) KthLargest {\n \n}\n\n\nfunc (this *KthLargest) Add(val int) int {\n \n}\n\n\n/**\n * Your KthLargest object will be instantiated and called as such:\n * obj := Constructor(k, nums);\n * param_1 := obj.Add(val);\n */", "__typename": "CodeSnippetNode" }, { "lang": "Ruby", "langSlug": "ruby", "code": "class KthLargest\n\n=begin\n :type k: Integer\n :type nums: Integer[]\n=end\n def initialize(k, nums)\n \n end\n\n\n=begin\n :type val: Integer\n :rtype: Integer\n=end\n def add(val)\n \n end\n\n\nend\n\n# Your KthLargest object will be instantiated and called as such:\n# obj = KthLargest.new(k, nums)\n# param_1 = obj.add(val)", "__typename": "CodeSnippetNode" }, { "lang": "Scala", "langSlug": "scala", "code": "class KthLargest(_k: Int, _nums: Array[Int]) {\n\n def add(`val`: Int): Int = {\n \n }\n\n}\n\n/**\n * Your KthLargest object will be instantiated and called as such:\n * var obj = new KthLargest(k, nums)\n * var param_1 = obj.add(`val`)\n */", "__typename": "CodeSnippetNode" }, { "lang": "Rust", "langSlug": "rust", "code": "struct KthLargest {\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 KthLargest {\n\n fn new(k: i32, nums: Vec) -> Self {\n \n }\n \n fn add(&self, val: i32) -> i32 {\n \n }\n}\n\n/**\n * Your KthLargest object will be instantiated and called as such:\n * let obj = KthLargest::new(k, nums);\n * let ret_1: i32 = obj.add(val);\n */", "__typename": "CodeSnippetNode" }, { "lang": "Racket", "langSlug": "racket", "code": "(define kth-largest%\n (class object%\n (super-new)\n \n ; k : exact-integer?\n ; nums : (listof exact-integer?)\n (init-field\n k\n nums)\n \n ; add : exact-integer? -> exact-integer?\n (define/public (add val)\n )))\n\n;; Your kth-largest% object will be instantiated and called as such:\n;; (define obj (new kth-largest% [k k] [nums nums]))\n;; (define param_1 (send obj add val))", "__typename": "CodeSnippetNode" }, { "lang": "Erlang", "langSlug": "erlang", "code": "-spec kth_largest_init_(K :: integer(), Nums :: [integer()]) -> any().\nkth_largest_init_(K, Nums) ->\n .\n\n-spec kth_largest_add(Val :: integer()) -> integer().\nkth_largest_add(Val) ->\n .\n\n\n%% Your functions will be called as such:\n%% kth_largest_init_(K, Nums),\n%% Param_1 = kth_largest_add(Val),\n\n%% kth_largest_init_ will be called before every test case, in which you can do some necessary initializations.", "__typename": "CodeSnippetNode" }, { "lang": "Elixir", "langSlug": "elixir", "code": "defmodule KthLargest do\n @spec init_(k :: integer, nums :: [integer]) :: any\n def init_(k, nums) do\n \n end\n\n @spec add(val :: integer) :: integer\n def add(val) do\n \n end\nend\n\n# Your functions will be called as such:\n# KthLargest.init_(k, nums)\n# param_1 = KthLargest.add(val)\n\n# KthLargest.init_ will be called before every test case, in which you can do some necessary initializations.", "__typename": "CodeSnippetNode" } ], "stats": "{\"totalAccepted\": \"481.7K\", \"totalSubmission\": \"851K\", \"totalAcceptedRaw\": 481664, \"totalSubmissionRaw\": 850979, \"acRate\": \"56.6%\"}", "hints": [], "solution": { "id": "1163", "canSeeDetail": true, "paidOnly": false, "hasVideoSolution": false, "paidOnlyVideo": true, "__typename": "ArticleNode" }, "status": null, "sampleTestCase": "[\"KthLargest\",\"add\",\"add\",\"add\",\"add\",\"add\"]\n[[3,[4,5,8,2]],[3],[5],[10],[9],[4]]", "metaData": "{\n \"classname\": \"KthLargest\",\n \"constructor\": {\n \"params\": [\n {\n \"type\": \"integer\",\n \"name\": \"k\"\n },\n {\n \"type\": \"integer[]\",\n \"name\": \"nums\"\n },\n {\n \"type\": \"integer\",\n \"name\": \"numsSize\",\n \"lang\": \"c\",\n \"value\": \"size_2\"\n }\n ]\n },\n \"methods\": [\n {\n \"name\": \"add\",\n \"params\": [\n {\n \"type\": \"integer\",\n \"name\": \"val\"\n }\n ],\n \"return\": {\n \"type\": \"integer\"\n }\n }\n ],\n \"systemdesign\": true,\n \"params\": [\n {\n \"name\": \"starts\",\n \"type\": \"integer[]\"\n },\n {\n \"name\": \"ends\",\n \"type\": \"integer[]\"\n }\n ],\n \"return\": {\n \"type\": \"list\",\n \"dealloc\": true\n },\n \"manual\": false\n}", "judgerAvailable": true, "judgeType": "large", "mysqlSchemas": [], "enableRunCode": true, "enableTestMode": false, "enableDebugger": true, "envInfo": "{\"cpp\": [\"C++\", \"

Compiled with clang 11 using the latest C++ 20 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 gnu11 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

\"], \"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 5.3.0 version of datastructures-js/priority-queue and 4.2.1 version of 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.21

\\r\\n

Support https://godoc.org/github.com/emirpasic/gods@v1.18.1 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.9.0.

\"], \"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 5.1.6, Node.js 16.13.2.

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

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

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

lodash.js library is included by default.

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

Run with Racket 8.3.

\"], \"erlang\": [\"Erlang\", \"Erlang/OTP 25.0\"], \"elixir\": [\"Elixir\", \"Elixir 1.13.4 with Erlang/OTP 25.0\"], \"dart\": [\"Dart\", \"

Dart 2.17.3

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

Your code will be run directly without compiling

\"]}", "libraryUrl": null, "adminUrl": null, "challengeQuestion": { "id": "1346", "date": "2023-05-23", "incompleteChallengeCount": 0, "streakCount": 0, "type": "DAILY", "__typename": "ChallengeQuestionNode" }, "__typename": "QuestionNode" } } }