# Leetcode 1905 Solution

This article provides solution to leetcode question 1905 (design-authentication-manager)

https://leetcode.com/problems/design-authentication-manager

## Solution

``````class AuthenticationManager {
int m_timeToLive;
unordered_map<string, int> m_expireTimes;
set<pair<int, string> > m_tokens;
public:
AuthenticationManager(int timeToLive) {
m_timeToLive = timeToLive;
}

void generate(string tokenId, int currentTime) {
m_expireTimes[tokenId] = currentTime + m_timeToLive;
m_tokens.insert(make_pair(currentTime + m_timeToLive, tokenId));
}

void renew(string tokenId, int currentTime) {
expireTokens(currentTime);

if (m_expireTimes.find(tokenId) == m_expireTimes.end())
return;

m_tokens.erase(make_pair(m_expireTimes[tokenId], tokenId));

m_expireTimes[tokenId] = currentTime + m_timeToLive;
m_tokens.insert(make_pair(currentTime + m_timeToLive, tokenId));
}

int countUnexpiredTokens(int currentTime) {
expireTokens(currentTime);
return m_tokens.size();
}

void expireTokens(int currentTime) {
std::vector<set<pair<int, string>>::iterator> items_to_delete;

for (auto it = m_tokens.begin(); it != m_tokens.end(); it++)
{
if (it->first <= currentTime)
items_to_delete.push_back(it);
else
break;
}

for (auto it = items_to_delete.begin(); it != items_to_delete.end(); it++)
{
m_expireTimes.erase((*it)->second);
m_tokens.erase(*it);
}
}
};

/**
* Your AuthenticationManager object will be instantiated and called as such:
* AuthenticationManager* obj = new AuthenticationManager(timeToLive);
* obj->generate(tokenId,currentTime);
* obj->renew(tokenId,currentTime);
* int param_3 = obj->countUnexpiredTokens(currentTime);
*/
``````