Skip to content

added time-based key val leetcode problem in cpp #736

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

Closed
wants to merge 1 commit into from
Closed
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
27 changes: 27 additions & 0 deletions 121 Leetcode/time_based_key_val.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
#include<bits/stdc++.h>
using namespace std;

class TimeMap {
public:
// initialising data structure as string=> {int,string}
unordered_map<string, vector<pair<int, string>>> m;
TimeMap() {
}
void set(string key, string value, int timestamp) {
m[key].push_back({timestamp, value});
}
string get(string key, int timestamp) {
if(!m.count(key))
return "";
// binary search
int start = 0, end = m[key].size();
while(start < end) {
int mid = start + (end-start)/2;
if(m[key][mid].first > timestamp)
end = mid;
else
start = mid + 1;
}
return start > 0 and start <= m[key].size() ? m[key][start-1].second : "";
}
};