Skip to content

Commit

Permalink
Merge pull request neetcode-gh#1294 from voski/patch-9
Browse files Browse the repository at this point in the history
Create 0981-Time-Based-Key-Value-Store.rb
  • Loading branch information
Ahmad-A0 authored Oct 21, 2022
2 parents 6ec4172 + 7fc99fe commit 59bb906
Showing 1 changed file with 54 additions and 0 deletions.
54 changes: 54 additions & 0 deletions ruby/0981-Time-Based-Key-Value-Store.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
class TimeMap
def initialize()
@map = {}
end


=begin
:type key: String
:type value: String
:type timestamp: Integer
:rtype: Void
=end
def set(key, value, timestamp)
@map[key] = [] unless @map.key?(key)

@map[key] << { v: value, t: timestamp }
end


=begin
:type key: String
:type timestamp: Integer
:rtype: String
=end
def get(key, timestamp)
return "" unless @map.key?(key)

entries = @map[key]
return "" if timestamp < entries[0][:t]
return entries[-1][:v] if timestamp >= entries[-1][:t]

l = 0
r = entries.length - 1
max = entries[0]
while l <= r
mid = ( l + r ) / 2
curr = entries[mid]

if curr[:t] < timestamp
max = curr
l = mid + 1
else
r = mid - 1
end
end

max[:v]
end
end

# Your TimeMap object will be instantiated and called as such:
# obj = TimeMap.new()
# obj.set(key, value, timestamp)
# param_2 = obj.get(key, timestamp)

0 comments on commit 59bb906

Please sign in to comment.