Skip to content

Instantly share code, notes, and snippets.

@JustinChristensen
Last active October 11, 2021 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinChristensen/c05a3482fe22687336dbeef378f89076 to your computer and use it in GitHub Desktop.
Save JustinChristensen/c05a3482fe22687336dbeef378f89076 to your computer and use it in GitHub Desktop.
struct tree {
struct tree_node *root, minimum;
size_t size;
};
struct tree ktree = { 0 };
// within the loop
if (size(ktree) < k) {
struct tree_node *n = new_node(arr[i]);
insert(n, ktree);
continue;
}
struct tree_node *min = find_min(ktree);
if (key(min) < arr[i]) {
delete(min, ktree);
struct tree_node *n = min;
set_key(arr[i], n);
insert(n, ktree);
}
// find_min(ktree) O(1), insert and delete maintain a pointer to the minimum element in the ktree to avoid the O (log k) lookup
// insert(n, ktree), delete(n, ktree) O(log k)
// space complexity: k nodes total, k total allocations
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment