Min Heap (PriorityQueue) and Ordered Set (TreeSet) in Kotlin
Improved version of my basic solution. Using an ordered set to store only the available servers and a priority queue to keep end times cuts down run time and st
Improved version of my [basic solution](https://leetcode.com/problems/find-servers-that-handled-most-number-of-requests/solutions/3928920/basic-brute-force-style-approach-in-kotlin-o-n-k-and-o-k/). Using an ordered set to store only the available servers and a priority queue to keep end times cuts down run time and storage significantly.\n# Intuition\nStore available servers in an ordered set, since the requests come in order. Keep a min heap of times when servers are going to become available again. Loop through requests and add servers to available/busy according to the time.\n\n# Approach\n- Add all servers to available set.\n- Loop through requests.\n- If the current time is greater than the available times of servers in the busy server heap, add them to the available server set.\n- Check if the k % i server, or the next one is available. If it is not then take the first available server. **Bonus of using ordered set**.\n- Increment requests taken counter for the server and add it to the busy heap.\n- Loop through requests taken and return the servers with the most.\n\n\n# Complexity\n- Time complexity: $$O(n*log(n))$$\n\n- Space complexity: $$O(maxOf(n, k))$$ worst case (full set/heap)\n\n# Code\n```\nclass Solution {\n    fun busiestServers(k: Int, arrival: IntArray, load: IntArray): List<Int> {\n        val availableServers = TreeSet<Int>() { a, b -> a - b }\n        val busyServers = PriorityQueue<Pair<Int, Int>>() { a, b -> a.second - b.second } // Pair of (server, availableTime)\n        val requestsTaken = IntArray(k) { 0 }\n\n        for (i in 0 until k) {\n            availableServers.add(i)\n        }\n\n        for (requestNumber in 0 until arrival.size) {\n            while (busyServers.isNotEmpty() && busyServers.peek().second <= arrival[requestNumber]) {\n                availableServers.add(busyServers.poll().first)\n            }\n\n            if (availableServers.isNotEmpty()) {\n                val server = availableServers.ceiling(requestNumber % k) ?: availableServers.first()\n                requestsTaken[server]++\n                availableServers.remove(server)\n                busyServers.offer(Pair(server, arrival[requestNumber] + load[requestNumber]))\n            }\n        }\n\n        var maxLoad = 0\n        var result = mutableListOf<Int>()\n        for ((server, load) in requestsTaken.withIndex()) {\n            if (load > maxLoad) {\n                maxLoad = load\n                result = mutableListOf(server)\n            } else if (load == maxLoad) {\n                result.add(server)\n            }\n        }\n\n        return result\n    }\n}\n```
['Kotlin']