The type of values stored in the map
Finds the key-value pair with the largest key that is less than or equal to the target.
This method uses binary search to efficiently locate the closest match. If no key is less than or equal to the target, it returns undefined.
Time complexity: O(log n)
The number to search for
The key-value pair with the largest key ≤ target, or undefined if none exists
const map = new SortedNumberMap<string>();
map.set(10, 'ten');
map.set(20, 'twenty');
map.set(30, 'thirty');
// Exact match
map.findClosestLessThanOrEqual(20); // { key: 20, value: 'twenty' }
// Closest less than
map.findClosestLessThanOrEqual(25); // { key: 20, value: 'twenty' }
// No match (target too small)
map.findClosestLessThanOrEqual(5); // undefined
Sets a key-value pair in the map. If the key already exists, its value is updated. If the key is new, it's inserted in the correct sorted position.
Time complexity: O(log n) for new keys (due to binary search and array insertion), O(1) for existing keys.
The numeric key to set
The value to associate with the key
A map-like data structure that maintains numeric keys in sorted order and provides efficient operations for finding the closest key-value pair less than or equal to a target.
This class combines the benefits of a Map (O(1) key-value lookups) with sorted key access (O(log n) binary search operations). It's particularly useful when you need to frequently find the "closest" entry to a given numeric key.
Example