# [Go] LeetCode 703. Kth Largest Element in a Stream

Jan 22 · 2 min read

# Description

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.

Your `KthLargest` class will have a constructor which accepts an integer `k` and an integer array `nums`, which contains initial elements from the stream. For each call to the method `KthLargest.add`, return the element representing the kth largest element in the stream.

Example:

`int k = 3;int[] arr = [4,5,8,2];KthLargest kthLargest = new KthLargest(3, arr);kthLargest.add(3);   // returns 4kthLargest.add(5);   // returns 5kthLargest.add(10);  // returns 5kthLargest.add(9);   // returns 8kthLargest.add(4);   // returns 8`

Note:
You may assume that `nums`' length ≥ `k-1` and `k` ≥ 1.

# Solution

`package _703_kth_largest_element_in_a_stream/*  Heap, PriorityQueue */import (   "container/heap")// KthLargest object will be instantiated and called as such:// obj := Constructor(k, nums);// param_1 := obj.Add(val);type KthLargest struct {   k    int   heap intHeap}func Constructor(k int, nums []int) KthLargest {   h := intHeap(nums)   //Convert to heap   heap.Init(&h)   return KthLargest{      k:    k,      heap: h,   }}func (kl *KthLargest) Add(val int) int {   heap.Push(&kl.heap, val)   //Pop minimum element until len(h) = k and kthlargest = h[0]   for len(kl.heap) > kl.k {      heap.Pop(&kl.heap)   }   return kl.heap[0]}type intHeap []intfunc (h intHeap) Len() int {   return len(h)}func (h intHeap) Less(i, j int) bool {   return h[i] < h[j]}func (h intHeap) Swap(i, j int) {   h[i], h[j] = h[j], h[i]}func (h *intHeap) Push(x interface{}) {   *h = append(*h, x.(int))}func (h *intHeap) Pop() interface{} {   res := (*h)[len(*h)-1]   *h = (*h)[:len(*h)-1]   return res}`

## More From Medium

#### Also tagged Go

Feb 18 · 3 min read

#### Top on Medium

Feb 18 · 11 min read

#### Top on Medium

Feb 13 · 6 min read

#### 11.5K

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just \$5/month. Upgrade