Reputation: 47
Given login/logout time of all users for a particular website in the form: (userId, login time, logout time). Store this data, to query the total number of users who logged in and logged out in a given time range.
What data structure should I use? and how to implement it?
Upvotes: 0
Views: 1375
Reputation: 4410
The data structure you're looking for is called an interval tree and it basically has a binary-search tree like format with the start of the interval (login time) as the values (ordering as in BST).
This DS has the following time complexities:
Upvotes: 2
Reputation: 10733
I don't think there is any single data structure which would give you better complexities than below mentioned approach :-
Upvotes: 0
Reputation: 1038
If you want to do this within a program:
Just create a simple array containing class User type variable.
User class should have attributes: userId, loginTime, logoutTime.
Checking the total number of users who logged in and logged out in a given time range will be something like:
for (user in userArray)
if (user.loginTime > inputLoginTime && user.logoutTime < inputLogoutTime)
count++;
You can check for the total number of users in O(n) time.
If you want to do it in Server, eg. MySQL.
Create a table User with userId, loginTime, logoutTime as column.
SELECT COUNT(*) FROM User WHERE User.loginTime > inputLoginTime AND User.logoutTime < inputLogoutTime;
Upvotes: 0