Observable Data Store - Problem

Design and implement an Observable Data Store that allows multiple listeners to be notified whenever data changes. The store should support setting values, getting values, and registering/unregistering listeners.

Your implementation should include:

  • DataStore class with methods to set/get data
  • addListener(key, callback) - register a callback for a specific key
  • removeListener(key, callback) - unregister a callback
  • set(key, value) - update value and notify all listeners for that key
  • get(key) - retrieve current value

When a value changes, all registered listeners for that key should be called with the new value.

Input & Output

Example 1 — Basic Operations
$ Input: operations = [["addListener","temp",1],["addListener","temp",2],["set","temp",25],["get","temp"]]
Output: [null,null,[1,2],25]
💡 Note: Add two listeners for 'temp', then set temp=25 which notifies both listeners [1,2], finally get returns 25
Example 2 — Multiple Keys
$ Input: operations = [["addListener","temp",1],["addListener","light",2],["set","temp",20],["set","light",true]]
Output: [null,null,[1],[2]]
💡 Note: Separate listeners for different keys: temp change notifies [1], light change notifies [2]
Example 3 — Remove Listener
$ Input: operations = [["addListener","temp",1],["addListener","temp",2],["removeListener","temp",1],["set","temp",30]]
Output: [null,null,null,[2]]
💡 Note: After removing listener 1, only listener 2 gets notified when temp changes to 30

Constraints

  • 1 ≤ operations.length ≤ 1000
  • Each operation is valid according to the method signatures
  • Keys are non-empty strings
  • Values can be any type (int, string, boolean, etc.)

Visualization

Tap to expand
Observable Data Store - Observer Pattern ImplementationINPUT: OperationsaddListener('temp', 1)addListener('temp', 2)addListener('light', 3)set('temp', 25)Operations create listenersand trigger notificationsALGORITHM: Hash Map Grouping1Group by key: temp → [1,2]2Store: light → [3]3On set('temp', 25): O(1) lookup4Notify only temp listeners [1,2]Hash Map Structure:temp: [listener1, listener2]light: [listener3]RESULT: Targeted NotificationsNotify: [1, 2]Only temp listeners calledLight listener 3 untouchedTime: O(k) where k=2Efficient & Scalable!No wasted iterationsKey Insight:Hash map grouping enables O(1) key lookup + O(k) targeted notification,eliminating the need to check every single listener for every data change.TutorialsPoint - Observable Data Store | Hash Map Observer Pattern
Asked in
Google 15 Facebook 12 Netflix 8 Uber 6
28.0K Views
Medium Frequency
~25 min Avg. Time
890 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen