Skip to content

Create: 981-Time-Based-Key-Value-Store.ts #1027

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Sep 5, 2022
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 44 additions & 0 deletions typescript/981-Time-Based-Key-Value-Store.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
//use an hashmap for keys, then each key will have an array (increasing order because of problem rules) of timestamps with values (represented as javascript objects {key, value})
class TimeMap {
public hash: {};

constructor() {
this.hash = {};
}

set(key: string, value: string, timestamp: number): void {
if (key in this.hash) {
this.hash[key].push({ timestamp, value });
} else this.hash[key] = [{ timestamp, value }];
}

get(key: string, timestamp: number): string {
//if key is not in the hashmap there are no timestamps nor values, return ""
if (!(key in this.hash)) return '';
let timestamps = this.hash[key];
//if there are no timestamps or the first timestamp is already bigger than target timestamp(they are sorted so all next ones will big too), return ""
if (timestamps.length === 0 || timestamps[0].timestamp > timestamp)
return '';

//starts from the first timestamp as closest
let closest = timestamps[0];

let [l, r] = [0, timestamps.length - 1];

//binary search, but
while (l <= r) {
let mid = Math.floor((l + r) / 2);

if (timestamps[mid].timestamp === timestamp)
return timestamps[mid].value;
//update closest if mid element's timestamp is still less than target timestamp
if (timestamps[mid].timestamp < timestamp)
closest = timestamps[mid];

if (timestamps[mid].timestamp < timestamp) l = mid + 1;
if (timestamps[mid].timestamp > timestamp) r = mid - 1;
}

return closest.value;
}
}