question_slug stringlengths 3 77 | title stringlengths 1 183 | slug stringlengths 12 45 | summary stringlengths 1 160 ⌀ | author stringlengths 2 30 | certification stringclasses 2
values | created_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | updated_at stringdate 2013-10-25 17:32:12 2025-04-12 09:38:24 | hit_count int64 0 10.6M | has_video bool 2
classes | content stringlengths 4 576k | upvotes int64 0 11.5k | downvotes int64 0 358 | tags stringlengths 2 193 | comments int64 0 2.56k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
find-the-student-that-will-replace-the-chalk | Simple | Short | C++ | O(n) | simple-short-c-on-by-gavnish_kumar-0gcr | Intuition\n Describe your first thoughts on how to solve this problem. \nFirst of all we calculate the sum of chalk used by all students,\nNow if we divide k wi | gavnish_kumar | NORMAL | 2024-09-02T04:14:34.900612+00:00 | 2024-09-02T04:15:48.386510+00:00 | 34 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst of all we calculate the sum of chalk used by all students,\nNow if we divide `k` with sum then we get number of circle formed,\nso `k%sum` will give us the chalk left for last round.\nso we will traverse for last round and whenever our k finishies then we return that index.\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long long int sum=0;\n for(auto it: chalk) sum+= it;\n k= k%sum; // chalk left for last round\n for(int i=0;i<chalk.size();i++){\n if(k<chalk[i]) return i; // chalk finish return the index\n k-= chalk[i]; //student i used chalk[i]\n }\n return 0;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
find-the-student-that-will-replace-the-chalk | C++ || Easy Video Solution || Faster than 98.12% | c-easy-video-solution-faster-than-9812-b-3s52 | The video solution for the below code is\nhttps://youtu.be/mch99mRQUFE\n\n# Code\ncpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, i | __SAI__NIVAS__ | NORMAL | 2024-09-02T02:06:50.751775+00:00 | 2024-09-02T02:06:50.751806+00:00 | 182 | false | The video solution for the below code is\nhttps://youtu.be/mch99mRQUFE\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n ios_base::sync_with_stdio(false);\n cin.tie(NULL);\n cout.tie(NULL);\n // Note points:\n // The number of students in the class are n and they are numbered from 0 to n - 1. \n // Example\n // 5, 1, 5\n // k = 22\n // 1st --> 17 (22 - 5)\n // 2nd --> 16 (17 - 1)\n // 3rd --> 11 (16 - 5)\n // 4th --> 6 (11 - 5)\n // 5th --> 5 (6 - 1)\n // 6th --> 0 (5 - 5)\n // 7th --> \n // In the first go I will just check how many iterations do all the studnets able to solve the problem. Able to use the chalk pieces.\n // Accumulate the pieces that are required by all the students. \n // I will simply divide my k value with this accumulated value. If I divied the k value with the obtained value. The total number of times all the studnets would able to solve the problem without replacing the chalk.\n // 5, 1, 5 --> 11\n // k = 22 --> 22 / 11 -> 2\n // 3 4 1 2 --> 25\n // 25 - (25 / 10) * 10\n // 25 / 10 --> 2 (5 chalk pieces remaining for the third iteration)\n int sz = chalk.size();\n long sum = 0;\n for(auto &ele : chalk) sum += ele*1L;\n int number = k / sum;\n k = k - number * sum;\n for(int i = 0 ; i < sz ; i++){\n if(chalk[i] > k) return i;\n k -= chalk[i];\n }\n return -1;\n }\n};\n``` | 2 | 0 | ['C++'] | 1 |
find-the-student-that-will-replace-the-chalk | O(n) solution | on-solution-by-rgoswami3419-hizt | Intuition\nTo determine which student will be the first to run out of chalk, we need to simulate the distribution of chalk among students. Given a list of chalk | rgoswami3419 | NORMAL | 2024-09-02T02:04:40.924049+00:00 | 2024-09-02T02:04:40.924070+00:00 | 203 | false | # Intuition\nTo determine which student will be the first to run out of chalk, we need to simulate the distribution of chalk among students. Given a list of chalk amounts and a number `k` representing the total chalk pieces, we can optimize the process by calculating the remainder of chalk after a full cycle of all students. This allows us to determine which student will exhaust their chalk first without simulating each individual chalk consumption.\n\n# Approach\n1. **Calculate Total Chalk Consumption**: First, compute the total amount of chalk required for a complete cycle through all students.\n2. **Determine Effective Chalk**: Use the modulo operation to find the effective amount of chalk after completing as many full cycles as possible.\n3. **Simulate Chalk Consumption**: Iterate through the chalk amounts for each student, subtracting from the effective chalk until we find the student whose chalk amount exceeds the remaining effective chalk.\n\n# Complexity\n- Time complexity: $$O(n)$$ \n We go through the list of chalk amounts twice: once to compute the total chalk and once to find the student who runs out of chalk. Here, $$n$$ is the number of students.\n\n- Space complexity: $$O(1)$$ \n We use a constant amount of extra space for variables regardless of the input size.\n\n# Code\n```java\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n long totalChalk = 0;\n for (int amount : chalk) {\n totalChalk += amount;\n }\n \n totalChalk = (int) k % totalChalk;\n \n for (int i = 0; i < chalk.length; i++) {\n if (totalChalk < chalk[i]) {\n return i;\n }\n totalChalk -= chalk[i];\n }\n \n return -1; \n }\n}\n | 2 | 0 | ['Java'] | 0 |
find-the-student-that-will-replace-the-chalk | DCC 2 SEPTEMBER 2024 || Arrays🔥 | dcc-2-september-2024-arrays-by-sajaltiwa-i5li | Approach and Intuition:\n\n1. Understanding the Problem:\n - You have an array chalk where each element represents the amount of chalk a student uses.\n - I | sajaltiwari007 | NORMAL | 2024-09-02T02:03:18.150379+00:00 | 2024-09-02T02:03:18.150410+00:00 | 36 | false | ### Approach and Intuition:\n\n1. **Understanding the Problem:**\n - You have an array `chalk` where each element represents the amount of chalk a student uses.\n - Initially, there are `k` units of chalk available.\n - Starting from the first student, each student uses up the amount of chalk specified by their respective value in the array.\n - Once the chalk runs out (i.e., `k` becomes less than the chalk required by the current student), the process stops, and you need to return the index of that student.\n - If `k` is greater than or equal to the total chalk required for one full cycle through all the students, you repeat the process until `k` is less than the total chalk sum.\n\n2. **Approach:**\n - **Calculate the total sum of the array:** First, sum up all the elements in the `chalk` array, which gives you the total amount of chalk required for one full cycle of all students.\n - **Reduce `k`:** Subtract the total sum from `k` repeatedly until `k` is smaller than the total sum. This reduction is necessary because if `k` is much larger than the total sum, it\'s equivalent to repeatedly cycling through the students.\n - **Identify the student:** Traverse the `chalk` array again, decrementing `k` by the chalk each student uses. When `k` becomes less than the current student\'s chalk usage, that student is the one who will use up the last piece of chalk.\n\n3. **Key Observations:**\n - If `k` is very large, subtracting the total sum repeatedly can help bring `k` down to a more manageable number, directly related to which student will run out of chalk first.\n - The problem essentially reduces to finding out how much `k` is when mapped onto a single cycle of the chalk array.\n\n### Complexity Analysis:\n\n1. **Time Complexity:**\n - **O(n):** Summing up the array takes `O(n)` time.\n - **O(n):** The second loop, which identifies the student who runs out of chalk, also takes `O(n)` time.\n - If the sum is subtracted multiple times, the outer while loop may seem like it adds complexity. However, since `k` is reduced by the total sum, it doesn\'t repeat infinitely; it runs for at most `O(1)` times (since subtracting the sum significantly reduces `k`).\n - Therefore, the overall time complexity is `O(n)`.\n\n2. **Space Complexity:**\n - **O(1):** The algorithm uses a constant amount of extra space, only a few variables, and does not require any additional data structures.\n\n# Code\n```java []\n\n// Time Compexity - : O(N)\n// Space Complexity - : O(Constant)\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n int n = chalk.length;\n long sum =0;\n // Summing the array\n for(int i=0;i<n;i++){\n sum+=(long)chalk[i];\n }\n // Directly reducing K sum times if k>=sum\n while(k>=sum){\n k-=sum;\n }\n // System.out.println(k);\n // Find the Index Linearly\n for(int i=0;i<n;i++){\n\n if(k<chalk[i]) return i;\n else\n k-=chalk[i];\n }\n return -1;\n \n }\n}\n``` | 2 | 0 | ['Array', 'Java'] | 0 |
find-the-student-that-will-replace-the-chalk | Get total sum of chalk, then mod by k O(N) | get-total-sum-of-chalk-then-mod-by-k-on-96bjf | \n# Approach\nGet the total amount of chalk that the students will use. Then take the total MOD k to get the amount of chalk that will be left in the last roun | midnightsimon | NORMAL | 2024-09-02T01:49:50.196179+00:00 | 2024-09-02T01:49:50.196215+00:00 | 33 | false | \n# Approach\nGet the total amount of chalk that the students will use. Then take the total MOD k to get the amount of chalk that will be left in the last round of chalk distribution.\n\n# Complexity\n- Time complexity:\nO(n)\nWe do two passes. The first pass is to get the total sum of chalk, then we iterate over chalk array to find out which index we will run out of chalk.\n\n- Space complexity:\nO(1)\nWe use constant space here, because the memory we need remains constant as the size of n grows. We are only saving a total sum of chalk, which fits in an 64 bit int.\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n long long all = accumulate(chalk.begin(), chalk.end(), 0LL);\n\n k %= all;\n int n = chalk.size();\n for(int i = 0; i < n; i++) {\n if(k < chalk[i]) {\n return i;\n }\n k -= chalk[i];\n }\n\n return n-1;\n }\n};\n``` | 2 | 0 | ['C++'] | 0 |
find-the-student-that-will-replace-the-chalk | Student that will replace chalk -🌟 Unique Solution 🌟 | student-that-will-replace-chalk-unique-s-koiu | Intuition\n1. Find the sum of all elements in the chalk so that we can get the chalk used in the single turn of students from 0 to n-1.\n\n2. Using that,we\'ll | RAJESWARI_P | NORMAL | 2024-09-02T01:41:02.963017+00:00 | 2024-09-02T01:41:02.963047+00:00 | 37 | false | # Intuition\n1. Find the sum of all elements in the chalk so that we can get the chalk used in the single turn of students from 0 to n-1.\n\n2. Using that,we\'ll find the chalk that will remain after the number of full complete turn ends.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n1. Find the sum of all chalks needed in the first term by iterating from 0 to n-1.\n\n1. The k value which is total number of chalks that is available is divided by sum which will give total number of turns can be completed without any incomplete chalk.\n\n1. The k value when taken the modulus with the sum will give the chalk remains after total number of turns completed with enough chalk.\n\n1. with the remaining chalk as modulo (k1 = k%sum) will be used for last turn where one of the student will replace the chalk .Hence in the iteration from 0 to n-1,at each time - the condition is checked as if k1 is less than chalk[i],then that student i will replace the chalk.\n\n1. If the k1 is greater enough,so when the i-th student use that chalk,k1 will be reduced by chalk[i] for i+1 -th student.\n\n1. Return the i-th student.\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:**O(n)**\n n -> number of students \nThe first loop to compute the sum takes **O(n)**.\nThe modulo operation is **O(1)**.\nThe second loop to find index in the worst case takes **O(n)**.\n\nThe overall time complexity: **O(n)+O(1)+O(n) = O(n)**.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:**O(1)**\n No additional datastructure is used in that scale upto input size.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```java []\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n int n=chalk.length;\n long sum=0;\n for(int i=0;i<n;i++)\n {\n sum+=chalk[i];\n }\n //5+1+5=11 22/11 - 22%11=0 -> 0-th\n //3+4+1+2=10 25/10 - 25%10 = 5 -> 5-3=2 2<4 - 1\n int k1=(int)(k%sum);\n if(k1==0)\n {\n return 0;\n }\n for(int i=0;i<n;i++)\n {\n if(k1<chalk[i])\n return i;\n k1=k1-chalk[i];\n }\n\n return -1;\n }\n}\n``` | 2 | 0 | ['Array', 'Java'] | 0 |
find-the-student-that-will-replace-the-chalk | Beginner-level Go code on PrefixSum + BinarySearch | beginner-level-go-code-on-prefixsum-bina-zt42 | Code\ngolang []\nfunc chalkReplacer(chalk []int, k int) int {\n n := len(chalk)\n if n > 0 && chalk[0] > k {\n return 0\n }\n for i := 1; i < | casualcow | NORMAL | 2024-09-02T01:13:06.747682+00:00 | 2024-09-02T01:13:06.747708+00:00 | 44 | false | # Code\n```golang []\nfunc chalkReplacer(chalk []int, k int) int {\n n := len(chalk)\n if n > 0 && chalk[0] > k {\n return 0\n }\n for i := 1; i < n; i++ {\n chalk[i] += chalk[i-1]//in-place modification as prefix sum\n if chalk[i] > k {\n return i\n }\n }\n k %= chalk[n-1]\n ans, _ := slices.BinarySearch(chalk, k+1)//the closest index to reach \'k+1\'\n return ans\n}\n``` | 2 | 0 | ['Binary Search', 'Prefix Sum', 'Go'] | 1 |
find-the-student-that-will-replace-the-chalk | Easy-To-Understand 5-Line and Most Optimal Solution, Beats 95% in Python!! | easy-to-understand-5-line-and-most-optim-vi2f | Intuition\n Describe your first thoughts on how to solve this problem. \nThe trick is to iterate over all of the elements of chalk with each iteration reducing | NickieChmikie | NORMAL | 2024-09-02T01:03:04.949139+00:00 | 2024-09-02T01:06:47.749584+00:00 | 353 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe trick is to iterate over all of the elements of ```chalk``` with each iteration reducing the value of ```k``` by the value of ```chalk[i]```, until the value of ```k``` is negative, meaning that the current element ```chalk[i]``` needs to replace the chalk, returning ```i```.\n\nIf after iterating the entire length of ```chalk```, ```k``` remains non-negative, we simply loop through it again (and again if need be)!\n# Approach\n<!-- Describe your approach to solving the problem. -->\n**But WAIT!! That\'s not optimal!**\n\nSuppose ```chalk = [1, 2, 3]``` and ```k = 100```, this will take a while (and repeats a lot of unnecessary processes)!\n\n| Iteration # | Element of Chalk (```i```) | ```k``` |\n|----------|----------|----------|\n| 1 | 0 | ***100*** --> 99 |\n| 1 | 1 | 99 --> 97 |\n| 1 | 2 | 97 --> ***94*** |\n| 2 | 0 | ***94*** --> 93 |\n| 2 | 1 | 93 --> 91 |\n| 2 | 2 | 91 --> ***88*** |\n| 3 | 0 | ***88*** --> 87 |\n| 3 | 1 | 87 --> 85 |\n| 3 | 2 | 85 --> ***82*** |\n| 4 | 0 | ***82*** --> 81 |\n\nDo you guys notice a pattern of ```k``` related the ```iteration #```? \nEach time, it decreases by 6. \n\nHence at the end of iteration 10 for example, we can expect to see the number ```100 (initial k) - (6 * 10) = 40```.\n\nUsing this, we can actually remove the need to manually loop over all these iterations, and simply jump to the lowest iteration possible, which would be iteration ```16```, since ```k = 100 (initial k) - (6 * 16) = 4``` and because \n\n| Iteration # | Element of Chalk (```i```) | ```k``` |\n|----------|----------|----------|\n| 16 | 0 | 4 --> 3 |\n| 16 | 1 | 3 --> 1 |\n| 16 | 2 | 1 --> -2 |\n**and Break!!**\n\n... would return ```i = 2```, since ```k = -2``` which is the first negative number encountered. \n\nAnyways, how did I know this? Pretty easy math trick:\n\n- How much does the value decrement each iteration? It\'s simply the sum of all elements of ```chalk```. In this example, ```6 = 1 + 2 + 3 = chalk[0] + chalk[1] + chalk[2]```, this makes sense because this is number of total chalk usages.\n- How do you end up on the last iteration? We simply do ```k % decrement per turn = sum(chalk)``` and work with the starting value of k there. If we simply we divide ```k``` by ```decrement per turn ```, we will get the number of max iterations, which is good, we can do ```k - (max iterations * sum(chalk))``` to get the last positive ```k``` value before it becomes negative relative to index ```0```. Modulo ( ```%``` ) is actually more efficient, and does all that for us, since it\'s the remainder operation. \n\nThis derives: ```k = k % sum(chalk)```\n\nNow we loop through, and find the value of ```i``` where ```k``` becomes negative. Easy! \n\nPlease upvote if you found it helpful!\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(1)\n# Code\n```python3 []\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n k, i = k % sum(chalk), 0 # last iterative value of k before negative\n while k > 0:\n k -= chalk[i]\n if k < 0: return i # return i here, since this is who needs to change the chalk\n i += 1\n return i # actually never reaches this step :-), just necessary for syntax\n\n #Technically 6 line solution haha\n \n``` | 2 | 0 | ['Array', 'Binary Search', 'Simulation', 'Prefix Sum', 'Python3'] | 3 |
find-the-student-that-will-replace-the-chalk | [Swift] 1 line, reductions(_:), partitioningIndex(where:) | swift-1-line-reductions_-partitioningind-0kad | \n\n# Code\nswift []\nimport Algorithms\n\nclass Solution {\n func chalkReplacer(_ chalk: [Int], _ k: Int) -> Int {\n chalk.reductions(+).partitioning | iamhands0me | NORMAL | 2024-09-02T00:38:30.057184+00:00 | 2024-09-02T00:38:30.057202+00:00 | 41 | false | \n\n# Code\n```swift []\nimport Algorithms\n\nclass Solution {\n func chalkReplacer(_ chalk: [Int], _ k: Int) -> Int {\n chalk.reductions(+).partitioningIndex { $0 > k % chalk.reduce(into: 0, +=) }\n }\n}\n``` | 2 | 0 | ['Binary Search', 'Swift', 'Prefix Sum'] | 1 |
find-the-student-that-will-replace-the-chalk | Java easy solution || Beats 100% | java-easy-solution-beats-100-by-agrwlaan-bq7t | \nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n\t\t\n\t\t//get prefix sum of the array\n long sum =0;\n for(int i=0;i<cha | agrwlaanchal | NORMAL | 2024-07-06T11:05:37.799457+00:00 | 2024-07-06T11:05:37.799506+00:00 | 145 | false | ```\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n\t\t\n\t\t//get prefix sum of the array\n long sum =0;\n for(int i=0;i<chalk.length;i++){ \n sum+=chalk[i]; \n }\n \n\t\t// count the k based on sum \n\t\t//convert to int\n k = (int)(k % sum);\n \n\t\t// traverse the array with given conditions\n for(int i=0;i<chalk.length;i++){\n if(k<chalk[i]){\n return i;\n }else{\n k=k-chalk[i];\n } \n \n }\n \n return 0; \n \n }\n}\n``` | 2 | 0 | ['Array', 'Prefix Sum', 'Java'] | 2 |
find-the-student-that-will-replace-the-chalk | simple simulation || easy to understand || must see | simple-simulation-easy-to-understand-mus-h2is | Code\n\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& arr, int k) {\n \n //n == chalk.size();\n\n //students numbered fro | akshat0610 | NORMAL | 2024-04-29T07:02:57.942552+00:00 | 2024-04-29T07:02:57.942581+00:00 | 128 | false | # Code\n```\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& arr, int k) {\n \n //n == chalk.size();\n\n //students numbered from 0 to n-1\n //0 1 2 3 4. . . . . . . . . . n-1 \n\n //k peices of chalk \n\n //we need to tell the first index on which on the k <= chalk[i]\n\n //observation --> while(k > (sum(arr))) --> all the students will be able to solve\n // their problem with their respective chalk[i] peices\n\n // -->as the overall chalk peices is greater than the count of \n // individual chalk peices\n\n long long int sum = accumulate(arr.begin(),arr.end(),0LL);\n while(k >= sum){\n //we need to knwo how may complete occurence of sum in k\n k = k - sum;\n }\n\n for(int i = 0 ; i < arr.size() ; i++){\n if((k - arr[i]) < 0) return i;\n k = k - arr[i];\n }\n\n return -1; //unreachable code\n }\n};\n``` | 2 | 0 | ['Array', 'Binary Search', 'Simulation', 'Prefix Sum', 'C++'] | 0 |
find-the-student-that-will-replace-the-chalk | Easy Solution | Java | Python | easy-solution-java-python-by-atharva77-fddm | Python\n\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n sums = sum(chalk)\n div = k // sums\n k = k - (s | atharva77 | NORMAL | 2023-03-24T13:13:24.217107+00:00 | 2023-03-24T13:13:24.217154+00:00 | 337 | false | # Python\n```\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n sums = sum(chalk)\n div = k // sums\n k = k - (sums * div)\n for i in range(len(chalk)):\n if chalk[i] <= k:\n k -= chalk[i]\n else:\n return i\n return -1\n```\n# Java\n```\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) {\n long sum = 0;\n for(int x : chalk) {\n sum += x;\n }\n long div = k / sum;\n k -= (sum * div);\n for(int i=0; i<chalk.length; i++) {\n if(chalk[i] <= k) {\n k -= chalk[i];\n }\n else {\n return i;\n }\n }\n return -1;\n }\n}\n```\nDo upvote if you like the Solution :) | 2 | 0 | ['Java', 'Python3'] | 1 |
find-the-student-that-will-replace-the-chalk | C++ | Binary Search | c-binary-search-by-deepak_2311-v03d | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | godmode_2311 | NORMAL | 2023-03-13T18:09:13.081292+00:00 | 2023-03-13T18:54:40.943900+00:00 | 276 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& ch, int k) {\n\n int n = ch.size();\n\n vector<long long> chalk(ch.begin(),ch.end());\n\n for(int i=1;i<n;i++) chalk[i] += chalk[i-1];\n\n \xA0 \xA0 \xA0 \xA0if(k == chalk[n-1] || k % chalk[n-1] == 0) return 0;\n if(k >= chalk[n-1]) k %= chalk[n-1];\n\n int lo = 0 , hi = n - 1;\n\n while(lo <= hi){\n int mid = lo + (hi - lo) / 2;\n if(chalk[mid] == k) return mid + 1;\n else if(chalk[mid] < k) lo = mid + 1;\n else hi = mid - 1;\n }\n return lo;\n }\n};\n``` | 2 | 0 | ['C'] | 1 |
find-the-student-that-will-replace-the-chalk | cpp easy solution || faster then 100% cpp solution | cpp-easy-solution-faster-then-100-cpp-so-kze4 | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | ankit_kumar12345 | NORMAL | 2023-03-13T17:31:36.165598+00:00 | 2023-03-13T17:37:37.830277+00:00 | 387 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\nO(k)\n\n- Space complexity:\no(1)\n\n# Code\n```\nclass Solution\n{\npublic:\n int chalkReplacer(vector<int> &chalk, int k)\n {\n long long sum = 0, i = 0;\n\n for (auto i : chalk) sum += i;\n\n // first of all count the sum \n\n k %= sum;\n\n if (k == 0) return 0;\n\n // if k == 0 means the sum is equal to k return 0 \n // becouse first student have 0 chalk \n \n else if (k < sum )\n \n while (chalk[i] <= k)\n \n k = k - chalk[i++];\n \n return i;\n }\n};\n``` | 2 | 0 | ['C++'] | 2 |
find-the-student-that-will-replace-the-chalk | [Python3] Prefix Sum + Binary Search - Easy to Understand | python3-prefix-sum-binary-search-easy-to-m91v | Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time | dolong2110 | NORMAL | 2023-02-25T08:27:16.191369+00:00 | 2023-02-25T08:27:16.191422+00:00 | 322 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n + logn) ~ O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def chalkReplacer(self, chalk: List[int], k: int) -> int:\n ps = [0]\n for c in chalk:\n ps.append(ps[-1] + c)\n\n k %= ps[-1]\n l, r = 0, len(chalk) - 1\n while l <= r:\n m = (l + r) >> 1\n if ps[m + 1] > k:\n r = m - 1\n else:\n l = m + 1\n return l\n``` | 2 | 0 | ['Binary Search', 'Prefix Sum', 'Python3'] | 0 |
find-the-student-that-will-replace-the-chalk | C++ CODE || Prefix Sum | c-code-prefix-sum-by-chiikuu-gfzt | Intuition\n *k is remainder of total sum of array.*\n Describe your first thoughts on how to solve this problem. \n# Complexity\n- Time complexity: O(n)\n Add y | CHIIKUU | NORMAL | 2023-02-14T07:07:34.316633+00:00 | 2023-02-14T07:07:34.316669+00:00 | 282 | false | # Intuition\n *********k is remainder of total sum of array.*********\n<!-- Describe your first thoughts on how to solve this problem. -->\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n #define ll long long\npublic:\n int chalkReplacer(vector<int>& c, int k) {\n ll t = 0;\n ll nm = 0;\n vector<ll>v;\n for(int i=0;i<c.size();i++){\n t+=c[i];\n nm+=c[i];\n v.push_back(nm);\n }\n k%=t;\n int in = upper_bound(v.begin(),v.end(),k) - v.begin();\n return in%c.size(); \n }\n};\n``` | 2 | 0 | ['Binary Search', 'Prefix Sum', 'C++'] | 0 |
find-the-student-that-will-replace-the-chalk | Simple Java solution | simple-java-solution-by-abstractconnoiss-9wpq | Code\n\nclass Solution {\n\tpublic int chalkReplacer(int[] chalk, int k) {\n\t\tlong sum = 0;\n\t\tfor (int c : chalk) {\n\t\t\tsum += c;\n\t\t}\n\t\tlong left | abstractConnoisseurs | NORMAL | 2023-01-26T06:37:28.696049+00:00 | 2023-01-26T06:37:28.696090+00:00 | 206 | false | # Code\n```\nclass Solution {\n\tpublic int chalkReplacer(int[] chalk, int k) {\n\t\tlong sum = 0;\n\t\tfor (int c : chalk) {\n\t\t\tsum += c;\n\t\t}\n\t\tlong left = k % sum;\n\t\tfor (int i = 0; i < chalk.length; i++) {\n\t\t\tif(left >= chalk[i]) {\n\t\t\t\tleft -= chalk[i];\n\t\t\t} else {\n\t\t\t\treturn i;\n\t\t\t}\n\t\t}\n\t\treturn -1;\n\t}\n}\n``` | 2 | 0 | ['Array', 'Binary Search', 'Simulation', 'Prefix Sum', 'Java'] | 1 |
find-the-student-that-will-replace-the-chalk | Prefix Array and BinarySearch | prefix-array-and-binarysearch-by-vasakri-u29p | Intuition\nCreate Prefix array and find the student who ran out of chalks\n\n# Approach\n1. Create Prefix Array\n2. Modulo K to find chalks at last loop\n3. Fin | vasakris | NORMAL | 2022-12-11T10:48:37.947690+00:00 | 2022-12-11T10:48:37.947735+00:00 | 265 | false | # Intuition\nCreate Prefix array and find the student who ran out of chalks\n\n# Approach\n1. Create Prefix Array\n2. Modulo K to find chalks at last loop\n3. Find student who rans out of chalk using BinarySearch\n\n# Complexity\n- Time complexity:\nO(n + logn)\n\n- Space complexity:\nO(1), reusing input to construct prefix array\n\n# Code\n```\nfunc chalkReplacer(chalk []int, k int) int {\n for i := 1; i < len(chalk); i++ {\n chalk[i] += chalk[i-1]\n }\n k = k % chalk[len(chalk)-1]\n\n // Find the student who have no chalks to write (k+1)\n left, right := 0, len(chalk)-1\n for left < right {\n mid := (left + right) / 2\n if chalk[mid] >= k+1 {\n right = mid\n } else {\n left = mid+1\n }\n }\n\n return left\n}\n``` | 2 | 0 | ['Binary Search', 'Prefix Sum', 'Go'] | 1 |
find-the-student-that-will-replace-the-chalk | simplest solution for the beginners | simplest-solution-for-the-beginners-by-t-z7tx | class Solution {\npublic:\n int chalkReplacer(vector& chalk, long long int k) {\n long long int tot=0;\n \n for(int i=0;i<chalk.size();i++){\n | tanishqvyas01 | NORMAL | 2022-10-17T10:43:01.862013+00:00 | 2022-10-17T11:58:08.964418+00:00 | 352 | false | class Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, long long int k) {\n long long int tot=0;\n \n for(int i=0;i<chalk.size();i++){\n tot+=chalk[i];\n }\n long long rem = k % tot;\n\n for(int i=0;i<chalk.size();i++){\n if(rem<chalk[i]) return i;\n rem-=chalk[i];\n \n }\n \n \nreturn 0; \n }\n}; | 2 | 0 | [] | 0 |
find-the-student-that-will-replace-the-chalk | c++ | 90% faster than all | easy | c-90-faster-than-all-easy-by-venomhighs7-dtuu | \n# Code\n\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n \n size_t sum=0;\n for(auto &x: chalk)\n | venomhighs7 | NORMAL | 2022-10-16T04:28:31.202385+00:00 | 2022-10-16T04:28:31.202437+00:00 | 607 | false | \n# Code\n```\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n \n size_t sum=0;\n for(auto &x: chalk)\n sum+=x; \n \n k = k%sum; \n for(int i=0;i<chalk.size();i++) \n { if( k-chalk[i] < 0) return i;\n else\n k-=chalk[i];\n }\n return chalk.size()-1;\n }\n};\n\n``` | 2 | 0 | ['C++'] | 0 |
find-the-student-that-will-replace-the-chalk | Simple Java Solution | simple-java-solution-by-nomaanansarii100-2jhq | \nclass Solution {\n public int chalkReplacer(int[] chalk, int k) \n {\n long sum =0;\n \n for(Integer i: chalk)\n sum += | nomaanansarii100 | NORMAL | 2022-10-14T10:55:56.902697+00:00 | 2022-10-14T10:55:56.902732+00:00 | 727 | false | ```\nclass Solution {\n public int chalkReplacer(int[] chalk, int k) \n {\n long sum =0;\n \n for(Integer i: chalk)\n sum += i;\n \n long l = k % sum;\n \n for(int i=0; i<chalk.length;i++)\n {\n if(l >= chalk[i])\n l = l - chalk[i];\n else\n return i;\n }\n return -1;\n }\n}\n``` | 2 | 0 | ['Java'] | 1 |
find-the-student-that-will-replace-the-chalk | C++ || Easy✅ || Binary Search ✅ || Most Optimized Approach 🔥 | c-easy-binary-search-most-optimized-appr-jybx | \nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n int n = chalk.size();\n vector<long long> pref(n);\n \n | UjjwalAgrawal | NORMAL | 2022-09-16T04:48:08.017238+00:00 | 2022-09-16T04:48:08.017282+00:00 | 365 | false | ```\nclass Solution {\npublic:\n int chalkReplacer(vector<int>& chalk, int k) {\n int n = chalk.size();\n vector<long long> pref(n);\n \n pref[0] = chalk[0];\n for(int i = 1; i<n; i++){\n pref[i] = pref[i-1] + chalk[i];\n }\n \n k = k % pref[n-1];\n \n int ans = 0;\n int str = 0, end = n-1;\n while(str <= end){\n int mid = str + (end - str)/2;\n \n if(pref[mid] <= k)\n str = mid+1;\n else{\n ans = mid;\n end = mid-1;\n }\n }\n \n return ans;\n }\n};\n``` | 2 | 0 | ['C', 'Binary Tree', 'Prefix Sum'] | 0 |
find-the-student-that-will-replace-the-chalk | easy method and easy explanation | easy-method-and-easy-explanation-by-devi-4ni2 | So, In this question we follow some steps.\nsteps\n1.first we store sum of given chalk array in sum long variable.\n2.Now we take modulus of k with this sum to | devil_pratihar | NORMAL | 2022-06-19T20:40:41.644880+00:00 | 2022-06-19T20:40:41.644921+00:00 | 195 | false | So, In this question we follow some steps.\n**steps**\n1.first we store sum of given chalk array in sum long variable.\n2.Now we take modulus of k with this sum to avoid repitation of steps.\n3.At last we run loop and substract value of array one by one from k. and when our condition become true we come out from loop.\n\n\t\tclass Solution {\n\t\t\tpublic:\n\t\t\t\t int chalkReplacer(vector<int>& chalk, int k) {\n\t\t\t\t\t\tint n=chalk.size();\n\t\t\t\t\t\tint i=0;\n\t\t\t\t\t\tlong long int sum=0;\n\t\t\t\t\t\tfor(int i=0;i<chalk.size();i++) sum+=chalk[i];\n\t\t\t\t\t\tk=k%sum;\n\t\t\t\t\t\twhile(k){\n\t\t\t\t\t\t\tif(chalk[i]>k){\n\t\t\t\t\t\t\t\treturn i;\n\t\t\t\t\t\t\t\tbreak;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\telse{\n\t\t\t\t\t\t\t\tk=k-chalk[i];\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\treturn i;\n\t\t\t\t\t}\n\t\t\t}; | 2 | 0 | ['C', 'C++'] | 0 |
design-authentication-manager | C++ Time map and Token map | c-time-map-and-token-map-by-votrubac-v179 | A naive single-map solution is accepted (and that\'s why this problem is only 4 points). For an interivew, however, it won\'t cut it. If you add 1000 tokens, an | votrubac | NORMAL | 2021-03-20T16:03:45.300318+00:00 | 2021-03-20T17:43:32.511094+00:00 | 6,142 | false | A naive single-map solution is accepted (and that\'s why this problem is only 4 points). For an interivew, however, it won\'t cut it. If you add 1000 tokens, and query 1000 times, the overal complexity will be quadratic. The test cases here are weak, so the difference between two-map and single-map solution is small (60 ms vs. 78 ms). \n\nYou can make this more efficient by adding `time_map`, where tokens are ordered by time. That way, we can identify expired tokens.\n\nThe `token_map` maps tokens to their current expiration times.\n\n```cpp\nclass AuthenticationManager {\npublic:\n int ttl = 0;\n set<pair<int, string>> time_map;\n unordered_map<string, int> token_map;\n AuthenticationManager(int timeToLive) : ttl(timeToLive) {}\n void clean(int currentTime) {\n while(!time_map.empty() && begin(time_map)->first <= currentTime) {\n token_map.erase(begin(time_map)->second);\n time_map.erase(begin(time_map));\n }\n }\n void generate(string tokenId, int currentTime) {\n token_map[tokenId] = currentTime + ttl;\n time_map.insert({currentTime + ttl, tokenId});\n }\n void renew(string tokenId, int currentTime) {\n clean(currentTime);\n auto it = token_map.find(tokenId);\n if (it != end(token_map)) {\n time_map.erase({it->second, it->first});\n it->second = currentTime + ttl;\n time_map.insert({currentTime + ttl, tokenId});\n }\n }\n int countUnexpiredTokens(int currentTime) {\n clean(currentTime);\n return token_map.size();\n }\n};\n``` | 41 | 5 | [] | 14 |
design-authentication-manager | [Java/Python 3] Two codes: HashMap/dict and LinkedHashMap/OrderedDict. | javapython-3-two-codes-hashmapdict-and-l-dcbb | Method 1: HashMap\n\nUse tailMap to skip expired tokens.\njava\n private TreeMap<Integer, String> tm = new TreeMap<>();\n private Map<String, Integer> exp | rock | NORMAL | 2021-03-20T16:03:36.055348+00:00 | 2022-03-30T18:03:04.079812+00:00 | 5,023 | false | **Method 1: HashMap**\n\nUse `tailMap` to skip expired tokens.\n```java\n private TreeMap<Integer, String> tm = new TreeMap<>();\n private Map<String, Integer> expireTime = new HashMap<>();\n private int life;\n \n public AuthenticationManager(int timeToLive) {\n life = timeToLive;\n }\n \n public void generate(String tokenId, int currentTime) {\n expireTime.put(tokenId, life + currentTime);\n tm.put(life + currentTime, tokenId); \n }\n \n public void renew(String tokenId, int currentTime) {\n int expire = expireTime.getOrDefault(tokenId, -1);\n var tail = tm.tailMap(currentTime + 1);\n if (!tail.isEmpty() && expire >= tail.firstKey()) {\n tm.remove(expire);\n tm.put(life + currentTime, tokenId);\n expireTime.put(tokenId, life + currentTime);\n }\n }\n \n public int countUnexpiredTokens(int currentTime) {\n return tm.tailMap(currentTime + 1).size();\n }\n```\nOr simplified as the following: -- credit to **@OPyrohov**\n```java\n private Map<String, Integer> expiry = new HashMap<>();\n private int life;\n \n public AuthenticationManager(int timeToLive) {\n life = timeToLive;\n }\n \n public void generate(String tokenId, int currentTime) {\n expiry.put(tokenId, life + currentTime);\n }\n \n public void renew(String tokenId, int currentTime) {\n if (expiry.getOrDefault(tokenId, -1) > currentTime) {\n expiry.put(tokenId, life + currentTime);\n }\n }\n \n public int countUnexpiredTokens(int currentTime) {\n expiry.entrySet().removeIf(e -> e.getValue() <= currentTime);\n return expiry.size();\n }\n```\n**Analysis:**\nTime complexity of ` countUnexpiredTokens`: `O(n)`\nOther methods cost time: `O(1)`\n\n----\n\nNot sure if we can use LinkedHashMap/OrderedDict for the problem, ask interviewer first during interview.\n\n**Method 2: LinkedHashMap**\n\n```java\n private Map<String, Integer> expiry = new LinkedHashMap<>(16, 0.75F, true); // here true indicates the map entries are in access order.\n private int life;\n \n public AuthenticationManager(int timeToLive) {\n life = timeToLive;\n }\n \n public void generate(String tokenId, int currentTime) {\n evictExpired(currentTime);\n expiry.put(tokenId, life + currentTime);\n }\n \n public void renew(String tokenId, int currentTime) {\n evictExpired(currentTime);\n if (expiry.containsKey(tokenId)) {\n expiry.put(tokenId, life + currentTime);\n }\n }\n \n public int countUnexpiredTokens(int currentTime) {\n evictExpired(currentTime);\n return expiry.size();\n }\n \n private void evictExpired(int currentTime) {\n var iter = expiry.entrySet().iterator();\n while (iter.hasNext() && iter.next().getValue() <= currentTime) {\n iter.remove();\n }\n }\n```\n```python\n def __init__(self, timeToLive: int):\n self.expiry = OrderedDict()\n self.life = timeToLive\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n self.evict_expired(currentTime)\n self.expiry[tokenId] = self.life + currentTime\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n self.evict_expired(currentTime)\n if tokenId in self.expiry:\n self.expiry.move_to_end(tokenId) # necessary to move to the end to keep expiry time in ascending order.\n self.expiry[tokenId] = self.life + currentTime\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n self.evict_expired(currentTime)\n return len(self.expiry) \n \n def evict_expired(self, currentTime: int) -> None:\n while self.expiry and next(iter(self.expiry.values())) <= currentTime:\n self.expiry.popitem(last=False)\n```\n**Analysis:**\nAll methods cost amortized time `O(1)`. | 30 | 1 | [] | 9 |
design-authentication-manager | ✅Short & Easy w/ Explanation | Clean code with Comments | short-easy-w-explanation-clean-code-with-65u6 | \nclass AuthenticationManager {\npublic:\n\t// used for mapping tokenId with generation time\n unordered_map<string, int >mp;\n int ttl;\n Authenticati | archit91 | NORMAL | 2021-03-20T16:26:23.846953+00:00 | 2021-03-20T16:34:44.366773+00:00 | 1,793 | false | ```\nclass AuthenticationManager {\npublic:\n\t// used for mapping tokenId with generation time\n unordered_map<string, int >mp;\n int ttl;\n AuthenticationManager(int timeToLive) : ttl(timeToLive){}\n \t\n void generate(string tokenId, int currentTime) {\n\t\t// store tokenId mapped with time of generation\n mp[tokenId] = currentTime;\n }\n \n void renew(string tokenId, int currentTime) {\n\t\t// tokenId must be already created and time since generation should be less than TTL\n if(mp.count(tokenId) && currentTime - mp[tokenId] < ttl)\n mp[tokenId] = currentTime; // renew if condition is satisfied\n }\n \n int countUnexpiredTokens(int currentTime) {\n int cnt = 0;\n for(auto& token:mp)\n\t\t\t// count all tokens which time since generation less than TTL\n if(currentTime - token.second < ttl) cnt++;\n return cnt;\n }\n};\n```\n\n**Time Complexity** : **`O(1)`** for generation and renewal and **`O(N)`** for counting unexpired tokens, where `N` is the total number of generated tokens.\n\n**Space Complexity** : **`O(N)`**\n\n\n----------\n---------- | 16 | 1 | ['C'] | 3 |
design-authentication-manager | Clean Python with explanation | clean-python-with-explanation-by-it_bili-by7u | \nclass AuthenticationManager(object):\n\n def __init__(self, timeToLive):\n self.token = dict()\n self.time = timeToLive # store timeToLive | it_bilim | NORMAL | 2021-03-20T16:07:34.222303+00:00 | 2021-03-20T17:13:48.025922+00:00 | 3,178 | false | ```\nclass AuthenticationManager(object):\n\n def __init__(self, timeToLive):\n self.token = dict()\n self.time = timeToLive # store timeToLive and create dictionary\n\n def generate(self, tokenId, currentTime):\n self.token[tokenId] = currentTime # store tokenId with currentTime\n\n def renew(self, tokenId, currentTime):\n limit = currentTime-self.time # calculate limit time to filter unexpired tokens\n if tokenId in self.token and self.token[tokenId]>limit: # filter tokens and renew its time\n self.token[tokenId] = currentTime\n\n def countUnexpiredTokens(self, currentTime):\n limit = currentTime-self.time # calculate limit time to filter unexpired tokens\n c = 0\n for i in self.token:\n if self.token[i]>limit: # count unexpired tokens\n c+=1\n return c\n``` | 16 | 4 | ['Python', 'Python3'] | 2 |
design-authentication-manager | [Java] LinkedHashMap | java-linkedhashmap-by-leonfan-d8yz | Clean expired item for each operation. Use LinkedHashMap to keep the order as also can get item in constant time.\n\nclass AuthenticationManager {\n private | leonfan | NORMAL | 2021-03-20T17:30:53.750857+00:00 | 2021-03-20T17:30:53.750889+00:00 | 1,302 | false | Clean expired item for each operation. Use LinkedHashMap to keep the order as also can get item in constant time.\n```\nclass AuthenticationManager {\n private int timeToLive;\n private Map<String, Integer> map = new LinkedHashMap<String, Integer>(); \n\n public AuthenticationManager(int timeToLive) {\n this.timeToLive = timeToLive;\n }\n \n public void generate(String tokenId, int currentTime) {\n clean(currentTime);\n map.put(tokenId, currentTime + timeToLive);\n }\n \n public void renew(String tokenId, int currentTime) {\n clean(currentTime);\n \n if(map.get(tokenId) != null) {\n map.remove(tokenId);\n map.put(tokenId, currentTime + timeToLive);\n }\n }\n \n public int countUnexpiredTokens(int currentTime) {\n clean(currentTime);\n \n return map.size();\n }\n \n private void clean(int currentTime) {\n for(Iterator<String> it = map.keySet().iterator(); it.hasNext(); ) {\n String key = it.next();\n if(map.get(key) <= currentTime) {\n it.remove();\n }else{\n break;\n }\n }\n }\n}\n``` | 14 | 1 | [] | 2 |
design-authentication-manager | [python3/Java] OrderedDict/LinkedHashMap O(1) with detailed explanation | python3java-ordereddictlinkedhashmap-o1-sfu5m | Suppose we have a dict where the key is tokenId and value is expireTime, how can we know the order of the expireTime such that we can easily remove the outdated | kytabyte | NORMAL | 2021-03-20T16:20:29.632007+00:00 | 2021-03-22T02:36:07.058278+00:00 | 1,139 | false | Suppose we have a dict where the key is `tokenId` and value is `expireTime`, how can we know the order of the `expireTime` such that we can easily remove the outdated entry everytime?\n\nHere is a specific data structure coming to rescue!\n\nPython\'s `OrderedDict` and Java\'s `LinkedHashMap` can preserve the **key insertion order** while keep providing HashMap\'s O(1) insert and delete, and also can move any key to the front or the back of the dict in O(1). \n\nThis data structure is actually a combination of **doubly linked list + hash map** , which is usually used for [LRU cache](https://leetcode.com/problems/lru-cache/) or [LFU cache](https://leetcode.com/problems/lfu-cache/). These two problems are very good use cases for `OrderedDict`\n\nNow we know that the `currentTime` is in strict increasing order! If we use an `OrderedDict` to keep the increasing timestamp order (because we always push new items at tail), we can easily know that every keys we want to remove is at the front of the dict.\n\nPython\n\n```python\nclass AuthenticationManager:\n def __init__(self, timeToLive: int):\n self._time = timeToLive\n self._dict = collections.OrderedDict()\n \n\t# remove all outdated keys if there is any\n def _evict(self, currentTime):\n while self._dict and next(iter(self._dict.values())) <= currentTime:\n self._dict.popitem(last=False)\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n self._evict(currentTime)\n self._dict[tokenId] = currentTime + self._time # put new keys at the tail (the newest)\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n self._evict(currentTime)\n \n if tokenId not in self._dict:\n return\n\t\t# move new item to the end of the OrderedDict\n self._dict.move_to_end(tokenId) # the renew key must be the newest, so move to tail\n self._dict[tokenId] = currentTime + self._time\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n self._evict(currentTime)\n return len(self._dict)\n\n```\n\nJava\n\nNote that Java `LinkedHashMap`\'s constructor has an argument to define whether **access an element causing the element to be put at the tail automatically**, which is the third argument in the constructor. In this case, we want this feature exactly when we are calling `renew`, thus we set it to `true`. More information can be referred to [Java doc](https://docs.oracle.com/javase/8/docs/api/java/util/LinkedHashMap.html)\n\n```java\nclass AuthenticationManager {\n private int time;\n\t// true means accessing an existing element will change the order of that element too\n private Map<String, Integer> dict = new LinkedHashMap<>(16, 0.75f, true);\n\n public AuthenticationManager(int timeToLive) {\n time = timeToLive;\n }\n \n private void evict(int currentTime) {\n Iterator<Map.Entry<String, Integer>> it;\n while (!dict.isEmpty() && (it = dict.entrySet().iterator()).next().getValue() <= currentTime) {\n it.remove();\n }\n }\n \n public void generate(String tokenId, int currentTime) {\n evict(currentTime);\n dict.put(tokenId, currentTime + time);\n }\n \n public void renew(String tokenId, int currentTime) {\n evict(currentTime);\n if (dict.containsKey(tokenId)) {\n dict.put(tokenId, currentTime + time); // entry will be automatically set as the newest one\n }\n }\n \n public int countUnexpiredTokens(int currentTime) {\n evict(currentTime);\n return dict.size();\n }\n}\n```\n\nTime complexity analysis:\n\nAlthough we may need to evict multiple keys during a call, but considered that the every key will only be popped out once, therefore the amortized time complexity of all the three APIs are O(1)\n | 12 | 0 | [] | 1 |
design-authentication-manager | [C++] Clean Code, Single Map Solution Explained | c-clean-code-single-map-solution-explain-xhtf | The problem is pretty straightforward, so the real challenge is just to get things working as efficiently, scalably and cleanly as possible.\n\nI gave it a shot | ajna | NORMAL | 2021-03-20T16:55:50.110738+00:00 | 2021-03-20T16:55:50.110765+00:00 | 2,065 | false | The problem is pretty straightforward, so the real challenge is just to get things working as efficiently, scalably and cleanly as possible.\n\nI gave it a shot by first of all defining to class variables:\n* `ttl` will store the supplied `timeToLive`;\n* `tokens` is a `unordered_map` with the `{tokenId => expiryTime}` logic.\n\nOur constructor will just set `ttl` - nothing more, nothing less.\n\n`generate` is also pretty straightforward, adding a new key => value mapping to `tokens`, with the value (the expiry time) set to be `currentTime + ttl`.\n\n`renew` starts to we a slightly more complex logic: we will first of all try to find if we have already a mapping for that specific `tokenId` and, only if we have it and its expiry time was below `currentTime`, update it to be `currentTime + ttl`.\n\nFinally `countUnexpiredTokens` will trivially iterate through all the current elements of `tokens` and increase the counter `res` for each one that is not expired yet, right before returning `res` itself.\n\nThe code:\n\n```cpp\nclass AuthenticationManager {\n int ttl;\n unordered_map<string, int> tokens;\npublic:\n AuthenticationManager(int timeToLive) {\n ttl = timeToLive;\n }\n \n void generate(string tokenId, int currentTime) {\n tokens[tokenId] = currentTime + ttl;\n }\n \n void renew(string tokenId, int currentTime) {\n auto tokenIt = tokens.find(tokenId);\n if (tokenIt != end(tokens) && tokenIt->second > currentTime) {\n tokenIt->second = currentTime + ttl;\n }\n }\n \n int countUnexpiredTokens(int currentTime) {\n int res = 0;\n for (auto token: tokens) {\n if (token.second > currentTime) res++;\n }\n return res;\n }\n};\n```\n\nI tried to get marginally better performance by removing expired tokens, so to reduce the elements we are going to loop through when counting, with little to no gains:\n\n```cpp\n void renew(string tokenId, int currentTime) {\n auto tokenIt = tokens.find(tokenId);\n if (tokenIt != end(tokens)) {\n // updating if still valid\n if (tokenIt->second > currentTime) tokenIt->second = currentTime + ttl;\n // erasing if expired\n else tokens.erase(tokenIt);\n }\n }\n``` | 8 | 0 | ['C', 'C++'] | 1 |
design-authentication-manager | Python O(1) solution: Doubly Linked List + Dict. Beat 99.7% | python-o1-solution-doubly-linked-list-di-79jz | Intuition\n Describe your first thoughts on how to solve this problem. \n\nBorrow the idea from LRU cache. Maintain a dict and a doubly linked list(dll) to stor | davidyqy | NORMAL | 2024-02-23T04:20:53.797264+00:00 | 2024-02-23T04:20:53.797292+00:00 | 927 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\nBorrow the idea from LRU cache. Maintain a dict and a doubly linked list(dll) to store the existing tokens.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n- generate: add the node to the dict and to the dll.\n- renew: remove the current node and append it to the tail of dll\n- countUnexpiredTokens: check the head of the dll and remove those expired. Return the size of dll\n\n# Complexity\nTime complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- generate: O(1)\n- renew: O(1)\n- countUnexpiredTokens: amortized O(1)\n\nSpace complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- O(n)\n\n# Code\n```\nclass ListNode:\n def __init__(self, token, currentTime):\n self.token = token\n self.insertTime = currentTime\n self.prev = None\n self.next = None\n\nclass DLL:\n def __init__(self):\n self.size = 0\n self.head = ListNode(-1, -1)\n self.tail = ListNode(-1, -1)\n self.head.next = self.tail\n self.tail.prev = self.head\n \n def add(self, node):\n # add to the tail\n prev = self.tail.prev\n prev.next = node\n node.prev = prev\n node.next = self.tail\n self.tail.prev = node\n self.size += 1\n \n def remove(self, node):\n prev, nxt = node.prev, node.next\n prev.next = nxt\n nxt.prev = prev\n self.size -= 1\n \n def print(self):\n node = self.head.next\n while node.token != -1:\n print(node.token, \' ->\', end = \'\')\n node = node.next\n print()\n\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.timeToLive = timeToLive\n self.dll = DLL()\n self.cache = {}\n \n def generate(self, tokenId: str, currentTime: int) -> None:\n node = ListNode(tokenId, currentTime)\n self.dll.add(node)\n self.cache[tokenId] = node\n #print("generate:")\n #self.dll.print()\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n if tokenId not in self.cache:\n return\n \n node = self.cache[tokenId]\n \n if node.insertTime + self.timeToLive <= currentTime:\n # expired\n self.dll.remove(node)\n del self.cache[tokenId]\n else:\n self.dll.remove(node)\n node.insertTime = currentTime\n self.dll.add(node)\n \n def countUnexpiredTokens(self, currentTime: int) -> int:\n node = self.dll.head.next\n while node.insertTime != -1 and node.insertTime + self.timeToLive <= currentTime:\n self.dll.remove(node)\n del self.cache[node.token]\n node = self.dll.head.next\n return self.dll.size\n\n \n\n \n\n\n# Your AuthenticationManager object will be instantiated and called as such:\n# obj = AuthenticationManager(timeToLive)\n# obj.generate(tokenId,currentTime)\n# obj.renew(tokenId,currentTime)\n# param_3 = obj.countUnexpiredTokens(currentTime)\n``` | 7 | 0 | ['Hash Table', 'Doubly-Linked List', 'Python3'] | 0 |
design-authentication-manager | Clean Python 3, hashmap | clean-python-3-hashmap-by-lenchen1112-vo51 | Time: O(max unexpired) for countUnexpiredTokens, O(1) for others\nSpace: O(max unexpired)\n\nclass AuthenticationManager:\n def __init__(self, timeToLive: in | lenchen1112 | NORMAL | 2021-03-20T16:21:06.723896+00:00 | 2021-03-20T16:21:06.723921+00:00 | 561 | false | Time: `O(max unexpired)` for `countUnexpiredTokens`, `O(1)` for others\nSpace: `O(max unexpired)`\n```\nclass AuthenticationManager:\n def __init__(self, timeToLive: int):\n self.time = timeToLive\n self.unexpired = {}\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n self.unexpired[tokenId] = currentTime + self.time\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n if self.unexpired.get(tokenId, 0) > currentTime:\n self.unexpired[tokenId] = currentTime + self.time\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n for token in tuple(self.unexpired.keys()):\n if self.unexpired[token] <= currentTime:\n self.unexpired.pop(token)\n return len(self.unexpired)\n``` | 6 | 0 | [] | 0 |
design-authentication-manager | C++ solution || Hash Map|| Fully commented✅ | c-solution-hash-map-fully-commented-by-n-ux5q | \n# Code\n\nclass AuthenticationManager {\npublic:\n unordered_map<string, int>mp;\n int time= 0;\n AuthenticationManager(int timeToLive) {\n ti | NitinSingh77 | NORMAL | 2023-09-02T18:28:24.176151+00:00 | 2023-09-02T18:28:48.899244+00:00 | 3,616 | false | \n# Code\n```\nclass AuthenticationManager {\npublic:\n unordered_map<string, int>mp;\n int time= 0;\n AuthenticationManager(int timeToLive) {\n time= timeToLive;\n }\n \n void generate(string tokenId, int currentTime) {\n mp[tokenId]= currentTime + time;// This will give you our expiry time at which we will be logged out from the site.\n }\n \n void renew(string tokenId, int currentTime) {\n auto it= mp.find(tokenId); //check if the token is available or not, if it\'s not available return.\n if(it==mp.end())\n return;\n else{\n if(mp[tokenId]>currentTime) // if the token is available and it\'s expiry time is greater than current time renew and update the expiry time\n {\n mp[tokenId]= currentTime + time; // update the expiry time by adding the current time with timeToLive value i.e 5 here.\n }\n }\n }\n \n int countUnexpiredTokens(int currentTime) {\n int total=0;\n for(auto x:mp) // iterate through every token and check if any token has it\'s expiry time greater than currentTime, if yes do total= total+1, it is simply calculating the remaining time here.\n {\n // cout<<x.second<<" ";\n if(x.second>currentTime)\n total++;\n }\n return total;\n }\n};\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * AuthenticationManager* obj = new AuthenticationManager(timeToLive);\n * obj->generate(tokenId,currentTime);\n * obj->renew(tokenId,currentTime);\n * int param_3 = obj->countUnexpiredTokens(currentTime);\n */\n``` | 5 | 0 | ['Hash Table', 'C++'] | 0 |
design-authentication-manager | Python | Beats 99% | Amortized cost explained | python-beats-99-amortized-cost-explained-9l15 | Method 1: Using HashMap\n\n\n# Code\n\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.ttl = timeToLive\n self.ex | saurabhkoshatwar | NORMAL | 2024-04-23T18:00:02.567208+00:00 | 2024-04-23T18:00:02.567239+00:00 | 629 | false | # Method 1: Using HashMap\n\n\n# Code\n```\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.ttl = timeToLive\n self.expiry = {}\n\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n self.expiry[tokenId] = currentTime + self.ttl\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n \n if tokenId in self.expiry and self.expiry[tokenId] > currentTime:\n self.expiry[tokenId] = currentTime + self.ttl\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n count = 0\n for token in self.expiry:\n if self.expiry[token] > currentTime:\n count += 1\n \n return count\n```\n\nThe issue with this approach is that according to the constraints given for the problem, there can be up to 2000 function calls. Consider a scenario where there are 1000 `generate()` calls, each creating a token, followed by 1000 `countUnexpiredTokens()` calls. This would result in quadratic complexity ->1000 * 1000, which could lead to a time limit exceeded (TLE) error, if the constraints were increased slightly.\n\n# Method 2: Using HashMap + deque\n\n# Code\n```\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.ttl = timeToLive\n self.tokens = deque()\n self.expiry = {}\n\n def remove_expired_tokens(self, currentTime):\n while self.tokens and self.tokens[0][1] <= currentTime:\n token, _ = self.tokens.popleft()\n del self.expiry[token]\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n self.expiry[tokenId] = currentTime + self.ttl\n self.tokens.append((tokenId, currentTime + self.ttl))\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n if tokenId in self.expiry and self.expiry[tokenId] > currentTime:\n self.remove_expired_tokens(currentTime)\n idx = 0\n while self.tokens[idx][0] != tokenId:\n idx += 1\n del self.tokens[idx]\n self.generate(tokenId, currentTime)\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n self.remove_expired_tokens(currentTime)\n return len(self.tokens)\n```\n\n- Time Complexity\n - `generate` - O(1)\n - `remove_expired_tokens` - O(1) worst-case scenario, the total number of expired tokens will always remain constant\n - `renew` - O(n) - can be improved check method 3\n - `countUnexpiredTokens`:\n \nIn the same scenario where there are 1000 `generate` calls, each creating a token, followed by 1000 `countUnexpiredTokens` calls, once all the expired tokens are removed in the first call to `remove_expired_tokens`, the time complexity of `countUnexpiredTokens` will indeed be O(1). This is because after the initial removal of expired tokens, subsequent calls to countUnexpiredTokens only need to return the length of the deque, which is a constant-time operation.\n\n# Method 3: Using HashMap + DLL\n\nSimilar to the implementation in method 2, but the queue is implemented using a Doubly Linked List (DLL), which provides constant-time complexity to remove a node.\n\n\n\n\n\n\n | 4 | 0 | ['Python', 'Python3'] | 2 |
design-authentication-manager | Java Solution with Map and PQ , >90% | java-solution-with-map-and-pq-90-by-stil-kzo9 | Intuition\nIteration over map take time to elimate the expired keys\n\n# Approach\nUsed Map and PQ together to improve the performance\n\n# Complexity\n- Time c | StillCoder | NORMAL | 2024-03-06T12:30:37.369110+00:00 | 2024-03-10T10:51:48.784533+00:00 | 804 | false | # Intuition\nIteration over map take time to elimate the expired keys\n\n# Approach\nUsed Map and PQ together to improve the performance\n\n# Complexity\n- Time complexity:\nO(nLogn)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass AuthenticationManager {\n int timeToLive;\n class Pair{\n String tokenId;\n int expireTime;\n\n public Pair(String tokenId,int expireTime){\n this.tokenId=tokenId;\n this.expireTime=expireTime;\n\n } \n }\n Queue<Pair> q = new PriorityQueue<>((Pair p1,Pair p2)->p1.expireTime-p2.expireTime);\n\n Map<String,Integer> map = new HashMap<>(); \n public AuthenticationManager(int timeToLive) {\n this.timeToLive=timeToLive;\n }\n \n public void generate(String tokenId, int currentTime) {\n if(!map.containsKey(tokenId)){\n q.offer(new Pair(tokenId,currentTime+timeToLive));\n }\n map.put(tokenId,currentTime+timeToLive);\n }\n \n public void renew(String tokenId, int currentTime) {\n if(map.containsKey(tokenId) && map.get(tokenId)>currentTime){\n map.put(tokenId,currentTime+timeToLive);\n } \n\n }\n \n public int countUnexpiredTokens(int currentTime) {\n while(!q.isEmpty() && q.peek().expireTime<=currentTime){\n Pair p = q.poll();\n if(map.get(p.tokenId)>p.expireTime){\n q.offer(new Pair(p.tokenId,map.get(p.tokenId)));\n }else{\n map.remove(p.tokenId);\n }\n }\n return q.size();\n }\n}\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * AuthenticationManager obj = new AuthenticationManager(timeToLive);\n * obj.generate(tokenId,currentTime);\n * obj.renew(tokenId,currentTime);\n * int param_3 = obj.countUnexpiredTokens(currentTime);\n */\n``` | 4 | 0 | ['Java'] | 1 |
design-authentication-manager | Python3: Dictionary + Deque = beat 98% runtime | python3-dictionary-deque-beat-98-runtime-7jzn | Intuition\n The problem has an inherent FIFO nature - tokens are added with strictly increasing timestamps, and the tokens which are added first will also expir | conquerworld | NORMAL | 2023-08-23T10:46:18.005130+00:00 | 2023-08-23T10:46:18.005159+00:00 | 1,104 | false | # Intuition\n* The problem has an inherent FIFO nature - tokens are added with strictly increasing timestamps, and the tokens which are added first will also expire first since TTL is the same for all tokens. This should inspire using a queue. \n* I used a hashmap with the queue just to keep track of the tokenids, but it turned out to be redundant.\n* When you get a call to renew or count unexpired tokens, look at the queue and start popping tokens one by one until the head of the queue is an unexpired token. This is amortized O(1) - you do a constant amount of work (queue.popleft()) per expired token. \n\n\n# Complexity\n- Time complexity:\n- Generate: O(1)\n- Renew: O(n)\n- Processing expiry: Amortized O(1)\n- CountUnexpiredTokens: O(1) (once expiry is processed, just get the length of the queue)\n\n- Space complexity: O(n) for queue. \n\n# Code\n```\nfrom collections import deque\n\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.tokens = {} # Dictionary from tokenId to expiry time.\n self.token_queue = deque() # helps keep track of which tokens to expire next. \n self.ttl = timeToLive\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n expiry = currentTime + self.ttl\n self.tokens[tokenId] = expiry\n self.token_queue.append((expiry, tokenId))\n\n\n def process_expiry(self, currentTime: int) -> int:\n count = 0\n while self.token_queue and self.token_queue[0][0] <= currentTime:\n exp, tok = self.token_queue.popleft()\n del self.tokens[tok]\n count += 1\n return count\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n if tokenId not in self.tokens:\n return\n if currentTime >= self.tokens[tokenId]:\n # token is already expired. \n # process expiry\n num_expired = self.process_expiry(currentTime)\n return\n # token not expired, process renewal\n idx = 0\n while self.token_queue[idx][1] != tokenId:\n idx += 1\n del self.token_queue[idx]\n del self.tokens[tokenId]\n self.generate(tokenId, currentTime)\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n self.process_expiry(currentTime)\n return len(self.token_queue)\n\n\n# Your AuthenticationManager object will be instantiated and called as such:\n# obj = AuthenticationManager(timeToLive)\n# obj.generate(tokenId,currentTime)\n# obj.renew(tokenId,currentTime)\n# param_3 = obj.countUnexpiredTokens(currentTime)\n``` | 4 | 0 | ['Python3'] | 3 |
design-authentication-manager | Java Using HashMap | java-using-hashmap-by-tbekpro-tqdk | Code\n\nclass AuthenticationManager {\n\n HashMap<String, Integer> map;\n int time;\n public AuthenticationManager(int timeToLive) {\n map = new | tbekpro | NORMAL | 2023-06-24T15:54:33.450601+00:00 | 2023-06-24T15:54:33.450625+00:00 | 1,216 | false | # Code\n```\nclass AuthenticationManager {\n\n HashMap<String, Integer> map;\n int time;\n public AuthenticationManager(int timeToLive) {\n map = new HashMap<>();\n time = timeToLive;\n }\n\n public void generate(String tokenId, int currentTime) {\n map.put(tokenId, currentTime + time);\n }\n\n public void renew(String tokenId, int currentTime) {\n int expires = map.getOrDefault(tokenId, 0);\n if (expires > currentTime) map.put(tokenId, currentTime + time);\n }\n\n public int countUnexpiredTokens(int currentTime) {\n int count = 0;\n for (String key : map.keySet()) if (map.get(key) > currentTime) count++;\n return count;\n }\n}\n``` | 4 | 0 | ['Java'] | 0 |
design-authentication-manager | 🔥🔥Easiest Java Solution For Beginners🔥🔥 | easiest-java-solution-for-beginners-by-j-x52o | \n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n\nclass AuthenticationManager {\n\n int time=0;\n\n HashMap<String,Inte | jaiyadav | NORMAL | 2023-01-11T15:08:05.192631+00:00 | 2023-01-11T15:08:05.192671+00:00 | 1,395 | false | \n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass AuthenticationManager {\n\n int time=0;\n\n HashMap<String,Integer>mp=new HashMap<>();\n\n public AuthenticationManager(int timeToLive) {\n \n time=timeToLive;\n\n }\n \n public void generate(String tokenId, int currentTime) {\n \n mp.put(tokenId,currentTime+time);\n\n }\n \n public void renew(String tokenId, int currentTime) {\n \n if(!mp.containsKey(tokenId)||mp.get(tokenId)<=currentTime)\n {\n return;\n }\n\n mp.put(tokenId,currentTime+time);\n\n }\n \n public int countUnexpiredTokens(int currentTime) {\n \n List<String>lr=new ArrayList<>(mp.keySet());\n \n for(int i=0;i<lr.size();i++){\n \n if(mp.get(lr.get(i))<=currentTime)mp.remove(lr.get(i));\n\n }\n\n return mp.size();\n \n }\n}\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * AuthenticationManager obj = new AuthenticationManager(timeToLive);\n * obj.generate(tokenId,currentTime);\n * obj.renew(tokenId,currentTime);\n * int param_3 = obj.countUnexpiredTokens(currentTime);\n */\n``` | 4 | 0 | ['Hash Table', 'Design', 'Java'] | 2 |
design-authentication-manager | In JavaScript using Hashmap | in-javascript-using-hashmap-by-vishwanat-4kgc | \n/**\n * @param {number} timeToLive\n */\nvar AuthenticationManager = function(timeToLive) {\n this.timeToLive=timeToLive;\n this.tokens=new Map();\n};\n | vishwanath1 | NORMAL | 2022-03-31T06:25:29.051996+00:00 | 2022-03-31T06:25:29.052043+00:00 | 259 | false | ```\n/**\n * @param {number} timeToLive\n */\nvar AuthenticationManager = function(timeToLive) {\n this.timeToLive=timeToLive;\n this.tokens=new Map();\n};\n\n/** \n * @param {string} tokenId \n * @param {number} currentTime\n * @return {void}\n */\nAuthenticationManager.prototype.generate = function(tokenId, currentTime) {\n if(!this.tokens.has(tokenId)){\n let tokenInfo={\n tokenId:tokenId,\n expiresAt:currentTime+this.timeToLive\n }\n this.tokens.set(tokenId,tokenInfo);\n }\n};\n\n/** \n * @param {string} tokenId \n * @param {number} currentTime\n * @return {void}\n */\nAuthenticationManager.prototype.renew = function(tokenId, currentTime) {\n if(!this.tokens.has(tokenId)) return;\n \n let token=this.tokens.get(tokenId);\n if(token.expiresAt>currentTime){\n this.tokens.set(tokenId,{...token,expiresAt:currentTime+this.timeToLive})\n }else{\n this.tokens.delete(tokenId);\n }\n};\n\n/** \n * @param {number} currentTime\n * @return {number}\n */\nAuthenticationManager.prototype.countUnexpiredTokens = function(currentTime) {\n let activeTokensCount=0;\n for(let [key,token] of this.tokens.entries()){\n if(token.expiresAt>currentTime) activeTokensCount++;\n }\n return activeTokensCount;\n};\n\n/** \n * Your AuthenticationManager object will be instantiated and called as such:\n * var obj = new AuthenticationManager(timeToLive)\n * obj.generate(tokenId,currentTime)\n * obj.renew(tokenId,currentTime)\n * var param_3 = obj.countUnexpiredTokens(currentTime)\n */\n``` | 4 | 0 | ['JavaScript'] | 1 |
design-authentication-manager | [C++] unordered_map + queue (faster than 100%) | c-unordered_map-queue-faster-than-100-by-fasg | \nclass AuthenticationManager {\n queue<pair<string, int>> q;\n unordered_map<string,int> mp;\n int ttl;\n \n\t//remove all the expired tokens in qu | vivekaltruist | NORMAL | 2021-03-20T16:37:59.772076+00:00 | 2021-03-20T16:43:39.371843+00:00 | 406 | false | ```\nclass AuthenticationManager {\n queue<pair<string, int>> q;\n unordered_map<string,int> mp;\n int ttl;\n \n\t//remove all the expired tokens in queue\n void removeExpired(int t){\n while(!q.empty() && q.front().second <= t){\n string id = q.front().first;\n if(mp[id] == q.front().second)\n mp.erase(id);\n q.pop();\n }\n }\npublic:\n AuthenticationManager(int timeToLive) {\n ttl = timeToLive;\n }\n \n void generate(string id, int t) {\n removeExpired(t);\n mp[id] = t + ttl;\n q.emplace(id, t+ttl);\n }\n \n void renew(string id, int t) {\n removeExpired(t);\n if(mp.find(id) == mp.end())\n return;\n\t\t//update new time in map and insert this item in queue\n\t\t//we can ignore multiple items in queue for same element since older item will anyways be removed\n q.emplace(id,t+ttl);\n mp[id] = t + ttl;\n }\n \n int countUnexpiredTokens(int t) {\n removeExpired(t);\n return mp.size();\n }\n};\n``` | 4 | 0 | [] | 0 |
design-authentication-manager | Beats 92% || C++|| Priority Queue || Map | beats-92-c-priority-queue-map-by-sai_sre-9q5r | Intuition\nThe goal of this problem is to design a class that manages authentication tokens with a certain time-to-live (TTL) value and provides functions for g | sai_sreekar_ | NORMAL | 2023-09-13T09:05:44.521124+00:00 | 2023-09-13T09:09:05.979434+00:00 | 655 | false | # **Intuition**\nThe goal of this problem is to design a class that manages authentication tokens with a certain time-to-live (TTL) value and provides functions for generating, renewing, and counting unexpired tokens based on the current time.\n\n# **Approach**\nTo solve this problem, we can use an unordered map (`ump`) to store the expiration time of each token based on its ID. We can also use a priority queue (`pq`) to keep track of tokens sorted by their expiration time, with the token that will expire soonest at the top of the queue.\n\n1. In the constructor (`AuthenticationManager`), we initialize the time-to-live (`ttl`) value.\n\n2. In the `generate` function, we calculate the expiration time for a token based on the current time and TTL, update the `ump` with the expiration time for the token, and push the token with its expiration time onto the priority queue.\n\n3. In the `renew` function, we check if the token exists in the `ump` and if its expiration time is greater than the current time. If both conditions are met, we update the expiration time for the token in the `ump`.\n\n4. In the `countUnexpiredTokens` function, we iterate through the priority queue while it\'s not empty. For each token at the top of the queue, we check if its original expiration time is greater than the current time. If it is, we pop it from the queue and check if its actual expiration time (as stored in `ump`) is greater than the current time. If it is, we push it back onto the queue. Finally, we return the size of the priority queue, which represents the count of unexpired tokens.\n\n## **Complexity**\n- **Time complexity:**\n - `generate` and `renew` functions both have a time complexity of O(1) because they involve simple map updates.\n - The `countUnexpiredTokens` function has a time complexity of O(logn) where \'n\' is the number of tokens in the priority queue. In the worst case, we may have to pop and push tokens back onto the queue.\n- **Space complexity:**\n - The space complexity is O(n) because we are using two data structures to store tokens: an unordered map (`ump`) to store the expiration times and a priority queue (`pq`) to store tokens sorted by expiration time.\n\n# Code\n```\nclass AuthenticationManager {\n\nprivate:\n struct compare\n {\n bool operator()(pair<string, int> p1, pair<string, int> p2)\n {\n return p1.second > p2.second;\n }\n };\n \n int ttl;\n unordered_map<string, int> ump;\n priority_queue<pair<string, int>, vector<pair<string, int>>, compare> pq;\n\npublic:\n AuthenticationManager(int timeToLive) \n {\n ttl = timeToLive;\n }\n\n void generate(string tokenId, int currentTime) \n {\n ump[tokenId] = currentTime + ttl;\n pq.push({tokenId, currentTime + ttl});\n }\n\n void renew(string tokenId, int currentTime) \n {\n if(ump.find(tokenId) != ump.end() && ump[tokenId] > currentTime)\n {\n ump[tokenId] = currentTime + ttl;\n }\n }\n\n int countUnexpiredTokens(int currentTime) \n {\n while (!pq.empty()) \n {\n int originalExpiryTime = pq.top().second;\n string tokenId = pq.top().first;\n if (originalExpiryTime > currentTime)\n {\n break;\n }\n\n pq.pop();\n int actualExpiryTime = ump[tokenId];\n if (actualExpiryTime > currentTime)\n {\n pq.push({tokenId,actualExpiryTime});\n }\n }\n return pq.size();\n }\n};\n\n``` | 3 | 0 | ['Hash Table', 'Design', 'Ordered Map', 'Heap (Priority Queue)', 'C++'] | 1 |
design-authentication-manager | C++ Solution | c-solution-by-pranto1209-bt7x | Approach\n Describe your approach to solving the problem. \n Map\n\n\n# Code\n\nclass AuthenticationManager {\npublic:\n int timeToLive;\n unordered_ma | pranto1209 | NORMAL | 2023-07-30T09:40:34.508839+00:00 | 2023-07-30T09:40:34.508857+00:00 | 2,234 | false | # Approach\n<!-- Describe your approach to solving the problem. -->\n Map\n\n\n# Code\n```\nclass AuthenticationManager {\npublic:\n int timeToLive;\n unordered_map<string, int> mp;\n \n AuthenticationManager(int timeToLive) {\n this->timeToLive = timeToLive;\n }\n \n void generate(string tokenId, int currentTime) {\n mp[tokenId] = currentTime + timeToLive;\n }\n \n void renew(string tokenId, int currentTime) {\n if (mp[tokenId] > currentTime) mp[tokenId] = currentTime + timeToLive;\n else mp[tokenId] = 0;\n }\n \n int countUnexpiredTokens(int currentTime) {\n int ans = 0;\n for (auto x: mp) {\n if (x.second > currentTime) ans++;\n }\n return ans;\n }\n};\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * AuthenticationManager* obj = new AuthenticationManager(timeToLive);\n * obj->generate(tokenId,currentTime);\n * obj->renew(tokenId,currentTime);\n * int param_3 = obj->countUnexpiredTokens(currentTime);\n */\n``` | 3 | 0 | ['C++'] | 0 |
design-authentication-manager | [Python3] Brute Force Hash Map | python3-brute-force-hash-map-by-blackspi-znul | \nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.ttl = timeToLive\n self.record = {}\n\n def generate(self, to | blackspinner | NORMAL | 2021-03-22T02:05:20.153773+00:00 | 2023-09-30T21:51:50.642879+00:00 | 209 | false | ```\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.ttl = timeToLive\n self.record = {}\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n self.record[tokenId] = currentTime\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n if tokenId in self.record:\n if self.record[tokenId] + self.ttl > currentTime:\n self.record[tokenId] = currentTime\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n return sum(1 for time in self.record.values() if time <= currentTime < time + self.ttl)\n``` | 3 | 0 | ['Python3'] | 0 |
design-authentication-manager | ✅ Javascript | Simplest Solution | 🏆Hash Table🏆 |🔥Beats 100%🔥 | javascript-simplest-solution-hash-table-qxp4q | \n\n# Intuition\nSimple storing tokens in Hash Table, then manipulate as update and iterate through.\n\n# Approach\nDefine timeToLive as this.ttl and Map() for | Satansoft | NORMAL | 2024-05-23T19:13:23.082795+00:00 | 2024-05-23T19:13:23.082830+00:00 | 29 | false | \n\n# Intuition\nSimple storing tokens in `Hash Table`, then manipulate as update and iterate through.\n\n# Approach\nDefine `timeToLive` as `this.ttl` and `Map()` for storing and manipulating with tokens data as `this.tokens`.\n\nIn `generate` method store new token as `[tokenId, currentTime + this.ttl]` with ttl offset.\n\nIn `renew` method check if token exist and is unexpired it or not.\nToken is expired if it\'s `currentTime` of set + `this.ttl` <= `currentTime`.\nIf it\'s unexpired, update it\'s expiration to `currentTime + this.ttl`, otherwise do nothing.\n\nIn `countUnexpiredTokens` set `counter` and iterate through the `this.tokens` with checking each for expiration and if it\'s not, increment count, otherwise do nothing. Return count at the end.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n/**\n * @param {number} timeToLive\n */\nvar AuthenticationManager = function(timeToLive) {\n this.ttl = timeToLive;\n this.tokens = new Map();\n};\n\n/** \n * @param {string} tokenId \n * @param {number} currentTime\n * @return {void}\n */\nAuthenticationManager.prototype.generate = function(tokenId, currentTime) {\n this.tokens.set(tokenId, currentTime + this.ttl);\n};\n\n/** \n * @param {string} tokenId \n * @param {number} currentTime\n * @return {void}\n */\nAuthenticationManager.prototype.renew = function(tokenId, currentTime) {\n const token = this.tokens.get(tokenId);\n\n if (token && token > currentTime) {\n this.tokens.set(tokenId, currentTime + this.ttl)\n }\n};\n\n/** \n * @param {number} currentTime\n * @return {number}\n */\nAuthenticationManager.prototype.countUnexpiredTokens = function(currentTime) {\n let count = 0;\n\n for (const [_, expiredAt] of this.tokens) {\n if (expiredAt > currentTime) count++;\n }\n\n return count;\n};\n\n/** \n * Your AuthenticationManager object will be instantiated and called as such:\n * var obj = new AuthenticationManager(timeToLive)\n * obj.generate(tokenId,currentTime)\n * obj.renew(tokenId,currentTime)\n * var param_3 = obj.countUnexpiredTokens(currentTime)\n */\n``` | 2 | 0 | ['Hash Table', 'JavaScript'] | 0 |
design-authentication-manager | Python3 - dict + heapq - beats 87% | python3-dict-heapq-beats-87-by-sebmulti2-m3yj | Intuition\nFor naive one, go through the hashmap and count the ones which have expired. This passes the test cases but its slow since you need to count all the | SebMulti21 | NORMAL | 2024-03-31T07:37:52.954183+00:00 | 2024-03-31T07:37:52.954218+00:00 | 163 | false | # Intuition\nFor naive one, go through the hashmap and count the ones which have expired. This passes the test cases but its slow since you need to count all the keys. \n\nWhat if we delete the expired ones from hashmap as we update the tokens map? \n\n# Approach\nMaintain a hashmap for O(1) lookup of tokens and a separate heapq for storing the smallest expiry first tokens. \n\n# Complexity\n- Time complexity:\nO(logN) -> worst case all are expired and we need to travel down the tree.\n\n- Space complexity:\nO(N) -> hashmap and heapq space. \n\n# Code\n```\nfrom heapq import heapify, heappush, heappop\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.TTL = timeToLive\n self.token_map = dict()\n self.my_heap = list()\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n total_time = currentTime + self.TTL\n self.token_map[tokenId] = total_time\n # self.my_queue.append((tokenId, total_time))\n heappush(self.my_heap, (total_time, tokenId))\n return\n\n def yeet(self, currentTime: int) -> None:\n # Delete all expired tokens\n while self.my_heap and self.my_heap[0][0] <= currentTime:\n # Pop these and delete from the map as well\n expiry_time, token_id = heappop(self.my_heap)\n if self.token_map[token_id] == expiry_time:\n del self.token_map[token_id]\n \n\n def renew(self, tokenId: str, currentTime: int) -> None:\n # Nothing happens are renew if the token is not present at all \n # or it has expired already\n self.yeet(currentTime)\n\n if tokenId not in self.token_map:\n return\n \n \n new_total_time = (currentTime + self.TTL)\n self.token_map[tokenId] = new_total_time\n self.my_heap.append((new_total_time, tokenId))\n return\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n self.yeet(currentTime)\n return len(self.token_map)\n \n\n\n# Your AuthenticationManager object will be instantiated and called as such:\n# obj = AuthenticationManager(timeToLive)\n# obj.generate(tokenId,currentTime)\n# obj.renew(tokenId,currentTime)\n# param_3 = obj.countUnexpiredTokens(currentTime)\n``` | 2 | 0 | ['Heap (Priority Queue)', 'Python3'] | 0 |
design-authentication-manager | [Java] HashMap + TreeSet | java-hashmap-treeset-by-hristokov-sznq | The algorithm is pretty straightforward, the idea is to add and renew the keys with the added time to live, so we can keep the expiration value and to use a Tre | HristoKov | NORMAL | 2022-09-29T13:34:08.792248+00:00 | 2022-09-29T13:34:08.792286+00:00 | 684 | false | The algorithm is pretty straightforward, the idea is to add and renew the keys with the added time to live, so we can keep the expiration value and to use a TreeSet for keeping it in a sorted manner with time complexity of O(Log (n)) for add and remove and O (M Log (n)) (where M is the number of items which will be traversed after the "midpoint" is found) for .tailSet(). The HashMap has the only purpose to store the expiration value of each key.\n\nThe Algorithm is kind of unstable and has performance between 44% and 93%.\n\n```\nclass AuthenticationManager {\n\n int timeToLive;\n TreeSet<Integer> treeSet;\n Map<String, Integer> map;\n public AuthenticationManager(int timeToLive) {\n this.timeToLive = timeToLive;\n treeSet = new TreeSet<>();\n map = new HashMap<>();\n }\n \n public void generate(String tokenId, int currentTime) {\n map.put(tokenId, currentTime + timeToLive);\n treeSet.add(currentTime + timeToLive);\n }\n \n public void renew(String tokenId, int currentTime) {\n \n Integer time = map.get(tokenId);\n\t\t// If null the token was never added, or it has expired before the renew call, which makes it invalid for renewing\n if (time == null || time <= currentTime) return;\n \n\t \n\t // Update the hashmap and treeSet with the new values\n map.put(tokenId, currentTime + timeToLive);\n treeSet.remove(time);\n treeSet.add(currentTime + timeToLive);\n \n\t\t// Clearing the treeset from already expired timestamps, it doesn\'t really improve the time execution, with about 10% only.\n while (!treeSet.isEmpty() && treeSet.lower(currentTime) != null) {\n treeSet.remove(treeSet.lower(currentTime));\n }\n }\n \n\t// Return the number of timestamps in the treeset, which have greated expiry time than the currentTime\n public int countUnexpiredTokens(int currentTime) {\n return treeSet.tailSet(currentTime, false).size();\n }\n}\n``` | 2 | 0 | ['Tree', 'Ordered Set', 'Java'] | 1 |
design-authentication-manager | [C++] | Easiest Solution | Clean Code | Single Map | c-easiest-solution-clean-code-single-map-ngk9 | Pls upvote if you like the solution!\n\nclass AuthenticationManager {\npublic:\n int time;\n unordered_map <string,int> m;\n AuthenticationManager(int | _dhruvbhatia_ | NORMAL | 2022-05-02T08:11:31.271445+00:00 | 2022-05-02T08:11:31.271475+00:00 | 341 | false | Pls upvote if you like the solution!\n```\nclass AuthenticationManager {\npublic:\n int time;\n unordered_map <string,int> m;\n AuthenticationManager(int timeToLive) {\n time = timeToLive;\n }\n \n void generate(string tokenId, int currentTime) {\n m[tokenId] = currentTime;\n }\n \n void renew(string tokenId, int currentTime) {\n if(m.find(tokenId) != m.end() && (currentTime - m[tokenId]) < time)\n m[tokenId] = currentTime;\n }\n \n int countUnexpiredTokens(int currentTime) {\n int res=0;\n for(auto i:m)\n if((currentTime - i.second) < time) res++;\n\t\t\t\n return res;\n }\n};\n``` | 2 | 0 | ['C'] | 0 |
design-authentication-manager | Python | Doubly LinkedList | All O(1) TC | python-doubly-linkedlist-all-o1-tc-by-ni-zfnd | \nclass Node:\n def __init__(self, key, exp):\n self.key = key\n self.exp = exp\n self.prev = None\n self.next = None\n \nclas | nishan_4 | NORMAL | 2022-03-24T18:45:23.872623+00:00 | 2022-04-01T08:40:11.542745+00:00 | 396 | false | ```\nclass Node:\n def __init__(self, key, exp):\n self.key = key\n self.exp = exp\n self.prev = None\n self.next = None\n \nclass AuthenticationManager:\n\n \'\'\'\n create Dobuly linked list\n unexpired tokens are on right \n expired will be on left , which is removed before any actions can happen\n \n on each operation \n remove element from left of the node which has exp time exceeds current time\n \n on add :\n add node to hash map and add node to end of DLL \n \n (inf,inf) -> node -> (inf,inf)\n \n on renew :\n check if node in DLL , then remove from first place add it to last because its renewed now\n before renwewal : (inf,inf) -> first -> node-a -> node-b -> (inf,inf)\n after renwewal : (inf,inf) -> node-a -> node-b -> first -> (inf,inf)\n \n \n on count :\n return length of hashmap because it can only have unexpired tokens \n \'\'\'\n \n \n def __init__(self, timeToLive: int):\n self.ttl = timeToLive\n self.head = Node(float(\'inf\'),float(\'inf\'))\n self.tail = Node(float(\'inf\'),float(\'inf\'))\n \n self.head.next = self.tail\n self.tail.prev = self.head\n \n self.lookup = {}\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n self.cleanup(currentTime)\n \n self.lookup[tokenId] = Node(tokenId, currentTime + self.ttl)\n self.addNode(self.lookup[tokenId])\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n self.cleanup(currentTime)\n \n if tokenId in self.lookup:\n self.deleteNode(tokenId)\n del self.lookup[tokenId] \n \n self.lookup[tokenId] = Node(tokenId, currentTime + self.ttl)\n self.addNode(self.lookup[tokenId])\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n self.cleanup(currentTime)\n \n return len(self.lookup)\n \n def cleanup(self, currentTime):\n \n head = self.head.next\n \n while head and head.key != float(\'inf\') and head.exp <= currentTime:\n \n node = head\n head = head.next\n \n self.deleteNode(node.key)\n del self.lookup[node.key]\n \n def addNode(self,node):\n \n prev = self.tail.prev\n \n prev.next = node\n node.next = self.tail\n \n self.tail.prev = node\n node.prev = prev\n \n def deleteNode(self,key):\n \n node = self.lookup[key]\n \n next = node.next\n prev = node.prev\n \n prev.next = next\n next.prev = prev\n \n# Your AuthenticationManager object will be instantiated and called as such:\n# obj = AuthenticationManager(timeToLive)\n# obj.generate(tokenId,currentTime)\n# obj.renew(tokenId,currentTime)\n# param_3 = obj.countUnexpiredTokens(currentTime)\n``` | 2 | 0 | ['Linked List', 'Doubly-Linked List', 'Python'] | 2 |
design-authentication-manager | Design Authentication Manager Solution Java | design-authentication-manager-solution-j-gpjc | class AuthenticationManager {\n int timeToLive;\n Map map;\n\n public AuthenticationManager(int timeToLive) {\n this.timeToLive = timeToLive;\n | bhupendra786 | NORMAL | 2022-03-21T10:26:48.749782+00:00 | 2022-03-21T10:26:48.749809+00:00 | 39 | false | class AuthenticationManager {\n int timeToLive;\n Map<String, Integer> map;\n\n public AuthenticationManager(int timeToLive) {\n this.timeToLive = timeToLive;\n map = new HashMap<String, Integer>();\n }\n \n public void generate(String tokenId, int currentTime) {\n map.put(tokenId, currentTime + timeToLive);\n }\n \n public void renew(String tokenId, int currentTime) {\n clearMap(currentTime);\n if (map.get(tokenId) != null)\n map.put(tokenId, currentTime + timeToLive);\n }\n \n public int countUnexpiredTokens(int currentTime) {\n clearMap(currentTime);\n return map.size();\n }\n \n public void clearMap(int currentTime) {\n Iterator it = map.entrySet().iterator();\n while (it.hasNext()) {\n Map.Entry entry = (Map.Entry)it.next();\n if ((int)entry.getValue() <= currentTime)\n it.remove();\n }\n }\n} | 2 | 1 | ['Design'] | 0 |
design-authentication-manager | Easy C++ solution | easy-c-solution-by-imran2018wahid-1m1y | \nclass AuthenticationManager {\npublic:\n int timeToLive;\n unordered_map<string,int>m;\n AuthenticationManager(int timeToLive) {\n this->timeT | imran2018wahid | NORMAL | 2022-03-21T06:02:55.198094+00:00 | 2022-03-21T06:02:55.198142+00:00 | 267 | false | ```\nclass AuthenticationManager {\npublic:\n int timeToLive;\n unordered_map<string,int>m;\n AuthenticationManager(int timeToLive) {\n this->timeToLive=timeToLive;\n m.clear();\n }\n \n void generate(string tokenId, int currentTime) {\n m[tokenId]=currentTime;\n }\n \n void renew(string tokenId, int currentTime) {\n if(m.find(tokenId)==m.end() || currentTime-m[tokenId]>=timeToLive) {\n return;\n }\n m[tokenId]=currentTime;\n }\n \n int countUnexpiredTokens(int currentTime) {\n int count=0;\n for(auto it:m) {\n if(currentTime-it.second<timeToLive) {\n count++;\n }\n }\n return count;\n }\n};\n```\n***Please upvote if you have got any help from my code. Thank you.*** | 2 | 0 | ['C'] | 0 |
design-authentication-manager | [Python3] Dictionary - easy understanding | python3-dictionary-easy-understanding-by-01dt | Time: O(max unexpired) for countUnexpiredTokens, O(1) for others\nSpace: O(max unexpired)\n\n\nclass AuthenticationManager:\n\n def __init__(self, timeToLive | dolong2110 | NORMAL | 2022-01-25T17:26:08.135679+00:00 | 2024-01-29T08:50:05.330987+00:00 | 199 | false | Time: O(max unexpired) for countUnexpiredTokens, O(1) for others\nSpace: O(max unexpired)\n\n```\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.ttl = timeToLive\n self.exp_at = dict()\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n self.exp_at[tokenId] = currentTime + self.ttl\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n if tokenId not in self.exp_at:\n return\n if currentTime < self.exp_at[tokenId]:\n self.exp_at[tokenId] = currentTime + self.ttl\n else:\n del self.exp_at[tokenId]\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n res = 0\n for token in self.exp_at:\n if self.exp_at[token] > currentTime:\n res += 1\n return res\n``` | 2 | 0 | ['Python', 'Python3'] | 1 |
design-authentication-manager | Brute Force | C++ | brute-force-c-by-smartchuza-xyax | \nclass AuthenticationManager {\npublic:\n map<string,int>M;\n multiset<int>S;\n int T;\n \n AuthenticationManager(int timeToLive) {\n T=t | smartchuza | NORMAL | 2021-04-20T19:47:37.359596+00:00 | 2021-04-20T19:47:37.359639+00:00 | 122 | false | ```\nclass AuthenticationManager {\npublic:\n map<string,int>M;\n multiset<int>S;\n int T;\n \n AuthenticationManager(int timeToLive) {\n T=timeToLive; \n }\n \n void generate(string tokenId, int currentTime) {\n M[tokenId]=currentTime+T;\n S.insert(M[tokenId]);\n }\n \n void renew(string tokenId, int currentTime) {\n if(M.find(tokenId)==M.end()) \n return ;\n if(M[tokenId]<=currentTime)\n return ;\n S.erase(S.find(M[tokenId]));\n M[tokenId]=currentTime+T;\n S.insert(M[tokenId]);\n }\n \n int countUnexpiredTokens(int currentTime) {\n int ans=0;\n for(int v:S){\n if(v>currentTime)\n ans++;\n }\n return ans;\n }\n};\n``` | 2 | 0 | [] | 0 |
design-authentication-manager | Python Faster than 100% Dictionary + Binary search | python-faster-than-100-dictionary-binary-vyai | \n\n\n\nfrom collections import defaultdict\nfrom typing import Dict, List, Tuple\n\n\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\ | sumeetsarkar | NORMAL | 2021-03-21T17:04:11.798416+00:00 | 2021-03-21T17:05:56.549911+00:00 | 376 | false | \n\n\n```\nfrom collections import defaultdict\nfrom typing import Dict, List, Tuple\n\n\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self._ttl = timeToLive\n\t\t# dictionary to store the token and its (provision, expiry time)\n\t\tself._tokens: Dict[str, Tuple[int, int]] = {}\n\n\t\t# stores all the unique expiry times - the arr is automatically set in increasing order\n\t\t# this array is helpful to perform binary search for `countUnexpiredTokens` calls\n self._token_expiry_timeline: List[int] = []\n\n\t\t# since we store the array with unique values of expiry, overlapping\n\t\t# expiries of many different tokens, this dictionary helps in keeping\n\t\t# a count of tokens sharing same expiry - helps to decide if particular\n\t\t# expiry can be removed if the token is renewed and there was only one\n\t\t# such token using that expiry - this is important or else, after renewal\n\t\t# older expiry will linger in this array\n self._expiry_time_count: Dict[int, int] = defaultdict(int)\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n if tokenId in self._tokens:\n return\n expiry = currentTime + self._ttl\n self._tokens[tokenId] = (currentTime, expiry)\n\n\t\t# Maintain unique expiries in _token_expiry_timeline\n if len(self._token_expiry_timeline) == 0 \\\n or (len(self._token_expiry_timeline) > 0 and self._token_expiry_timeline[-1] < expiry):\n self._token_expiry_timeline.append(expiry)\n self._expiry_time_count[expiry] += 1\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n if tokenId not in self._tokens:\n return\n older_expiry = self._tokens[tokenId][1]\n if currentTime >= older_expiry:\n return\n\t\t\n\t\t# comment at decalaration of `_expiry_time_count` at `__init__`\n\t\t# explains this logic\n\t\tif self._expiry_time_count[older_expiry] == 1:\n self._token_expiry_timeline.remove(older_expiry)\n self._expiry_time_count[older_expiry] -= 1\n\n\t\t# since the token becomes eligible for renew, remove older entry\n\t\t# and reuse `generate` function\n del self._tokens[tokenId]\n self.generate(tokenId, currentTime)\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n\t\t# Some quick checks to bail out fast\n if not self._token_expiry_timeline:\n return 0\n if self._token_expiry_timeline[-1] <= currentTime:\n return 0\n # binary search the max value in array <= currentTime\n n = len(self._token_expiry_timeline)\n left, right = 0, n\n while left < right:\n mid = left + (right - left) // 2\n if self._token_expiry_timeline[mid] <= currentTime:\n left = mid + 1\n else:\n right = mid\n\t\t# remaining items are not expired\n return n - left\n``` | 2 | 0 | ['Binary Search', 'Python', 'Python3'] | 1 |
design-authentication-manager | Easy JAVA Solution Using HashMap | easy-java-solution-using-hashmap-by-hima-hkmy | \nclass AuthenticationManager {\n HashMap<String,Integer> tokens;\n int life;\n \n public AuthenticationManager(int timeToLive) {\n tokens=n | himanshuchhikara | NORMAL | 2021-03-20T16:53:46.950093+00:00 | 2021-03-20T18:04:10.371904+00:00 | 99 | false | ```\nclass AuthenticationManager {\n HashMap<String,Integer> tokens;\n int life;\n \n public AuthenticationManager(int timeToLive) {\n tokens=new HashMap<>();\n life=timeToLive;\n \n }\n \n public void generate(String tokenId, int currentTime) {\n tokens.put(tokenId,currentTime);\n \n }\n \n public void renew(String tokenId, int currentTime) {\n updateTokensMap(currentTime);\n \n if(tokens.containsKey(tokenId)){\n int expireTime=tokens.get(tokenId)+ life;\n tokens.put(tokenId,currentTime);\n }\n }\n \n \n public int countUnexpiredTokens(int currentTime) { \n updateTokensMap(currentTime);\n return tokens.size();\n }\n \n private void updateTokensMap(int time){\n HashSet<String> removeIds=new HashSet<>();\n for(String id:tokens.keySet()){\n int expTime=tokens.get(id)+life;\n if(expTime<=time){\n removeIds.add(id);\n }\n }\n \n for(String id:removeIds){\n tokens.remove(id);\n }\n }\n}\n``` | 2 | 2 | ['Java'] | 0 |
design-authentication-manager | interval with expiration time c++ | interval-with-expiration-time-c-by-sguox-esxe | using hashmap to record the expiration time and ordered map to record the start and expiration time and then use prefix sum to get the count\n\n unordered_ma | sguox002 | NORMAL | 2021-03-20T16:12:36.174084+00:00 | 2021-03-20T16:12:36.174122+00:00 | 98 | false | using hashmap to record the expiration time and ordered map to record the start and expiration time and then use prefix sum to get the count\n```\n unordered_map<string,int> token;\n map<int,int> mp;\n int tl;\n AuthenticationManager(int timeToLive) {\n tl=timeToLive;\n }\n \n void generate(string tokenId, int currentTime) {\n token[tokenId]=currentTime+tl;\n mp[currentTime]++;\n mp[currentTime+tl]--;\n }\n \n void renew(string tokenId, int currentTime) {\n if(!token.count(tokenId) || token[tokenId]<=currentTime) return;\n int pre=token[tokenId];//expire time\n mp[pre]++,mp[currentTime+tl]--;\n token[tokenId]=currentTime+tl;// start time not changed\n }\n \n int countUnexpiredTokens(int currentTime) {\n int pre=0;\n for(auto t: mp){\n if(t.first>currentTime) return pre; //count after expire\n pre+=t.second;\n }\n return 0;\n }\n\t``` | 2 | 0 | [] | 0 |
design-authentication-manager | Python: Two solutions Explained Using (Doubly LinkedList + HashMap) or (Heapq + HashMap) | python-2-solutions-explained-using-doubl-7leb | Approach 1Doubly LinkedList + DictionaryComplexity
Time complexity: Generate and Renew O(1), CountExpiry O(n)
Space complexity: O(n)
CodeApproach 2Heapq + Dict | kushalpatel | NORMAL | 2025-04-02T03:38:04.305084+00:00 | 2025-04-02T03:38:30.244692+00:00 | 63 | false | # Approach 1
Doubly LinkedList + Dictionary
# Complexity
- Time complexity: Generate and Renew O(1), CountExpiry O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class ListNode():
def __init__(self, tokenId='', expiryTime=0):
self.tokenId, self.expiryTime = tokenId, expiryTime
self.next = self.prev = None
class AuthenticationManager:
def __init__(self, timeToLive: int):
self.authManager = dict() # tokenId -> reference to node
self.start, self.end = ListNode(), ListNode()
self.start.next, self.end.prev = self.end, self.start # Link dummy nodes
self.size = 0
self.ttl = timeToLive
def insert(self, node):
prev, end = self.end.prev, self.end
prev.next, end.prev = node, node
node.prev, node.next = prev, end
self.size += 1
def remove(self, node):
prev, nxt = node.prev, node.next
prev.next, nxt.prev = nxt, prev
self.size -= 1
def generate(self, tokenId: str, currentTime: int) -> None:
expiry = currentTime + self.ttl
self.authManager[tokenId] = ListNode(tokenId, expiry)
self.insert(self.authManager[tokenId])
def renew(self, tokenId: str, currentTime: int) -> None:
if tokenId in self.authManager:
node = self.authManager[tokenId]
if node.expiryTime > currentTime:
# Remove node from current position
self.remove(node)
# Update expiry time
node.expiryTime = currentTime + self.ttl
# Reinsert at the end
self.insert(node)
else:
# If expired, remove from map
self.remove(node)
del self.authManager[tokenId]
def countUnexpiredTokens(self, currentTime: int) -> int:
start = self.start.next
while start != self.end and start.expiryTime <= currentTime:
self.remove(start)
del self.authManager[start.tokenId] # Also remove from dictionary
start = start.next # Move to the next node
return self.size
```
---
# Approach 2
Heapq + Dictionary
# Complexity
- Time complexity: Generate and Renew O(logn), CountExpiry O(nlogn)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
import heapq
class AuthenticationManager:
def __init__(self, timeToLive: int):
self.authManager = dict() # tokenId, expiry
self.minHeap = [] #(expiryTime, tokenId)
self.ttl = timeToLive
def generate(self, tokenId: str, currentTime: int) -> None:
tokenExpiry = currentTime + self.ttl
self.authManager[tokenId] = tokenExpiry
heapq.heappush(self.minHeap, (tokenExpiry, tokenId))
def renew(self, tokenId: str, currentTime: int) -> None:
if tokenId in self.authManager:
currExpiryOfToken = self.authManager[tokenId]
if currExpiryOfToken > currentTime:
newExpiry = currentTime + self.ttl
self.authManager[tokenId] = newExpiry
heapq.heappush(self.minHeap, (newExpiry, tokenId))
def countUnexpiredTokens(self, currentTime: int) -> int:
while self.minHeap and self.minHeap[0][0] <= currentTime:
expiry, tokenId = heapq.heappop(self.minHeap)
if tokenId in self.authManager and self.authManager[tokenId] <= currentTime:
del self.authManager[tokenId]
return len(self.authManager)
``` | 1 | 0 | ['Hash Table', 'Heap (Priority Queue)', 'Doubly-Linked List', 'Python3'] | 0 |
design-authentication-manager | [C++] list + unordered_map clean solution | c-list-unordered_map-clean-solution-by-a-3wi4 | Code | axard | NORMAL | 2024-12-30T22:18:27.287643+00:00 | 2024-12-30T22:19:52.705423+00:00 | 76 | false |
# Code
```cpp []
class AuthenticationManager {
public:
int ttl = 0;
list<string> l;
unordered_map<string, pair<list<string>::iterator, int>> mp;
AuthenticationManager(int timeToLive) {
ttl = timeToLive;
}
void generate(string tokenId, int currentTime) {
l.push_front(tokenId);
mp[tokenId] = {l.begin(), currentTime + ttl};
}
void renew(string tokenId, int currentTime) {
refresh(currentTime);
if (!mp.count(tokenId)) return;
auto it = mp[tokenId].first;
l.erase(it);
l.push_front(tokenId);
mp[tokenId] = {l.begin(), currentTime + ttl};
}
int countUnexpiredTokens(int currentTime) {
refresh(currentTime);
return l.size();
}
void refresh(int currentTime) {
while (!l.empty() && mp[l.back()].second <= currentTime) {
mp.erase(l.back());
l.pop_back();
}
}
};
/**
* 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);
*/
``` | 1 | 0 | ['C++'] | 0 |
design-authentication-manager | amortized O(1) ^^ | amortized-o1-by-andrii_khlevniuk-gdxp | time: amortized O(1)\n\nclass AuthenticationManager \n{\n int t;\n int uniques{};\n unordered_map<string, int> st;\n queue<pair<string, int>> q;\n | andrii_khlevniuk | NORMAL | 2024-08-06T00:22:02.528930+00:00 | 2024-08-06T17:06:05.899753+00:00 | 55 | false | **time: `amortized O(1)`**\n```\nclass AuthenticationManager \n{\n int t;\n int uniques{};\n unordered_map<string, int> st;\n queue<pair<string, int>> q;\n \npublic:\n AuthenticationManager(int t) : t{t} \n { \n }\n \n void generate(string s, int ct) \n {\n st[s] = ct+t-1;\n ++uniques;\n q.push({s, ct+t-1});\n }\n \n void drop(int ct)\n {\n for( ; !empty(q) and q.front().second<ct; q.pop())\n if(st[q.front().first]==q.front().second and st[q.front().first]<ct) --uniques; \n }\n \n void renew(string s, int ct) \n {\n if(st[s]>=ct)\n {\n st[s] = ct+t-1;\n q.push({s, ct+t-1});\n }\n }\n \n int countUnexpiredTokens(int ct) \n {\n drop(ct);\n return uniques; \n }\n};\n```\n\n**straightforward:**\n**time: `O(tokens)`** \n```\nclass AuthenticationManager \n{\n int t;\n unordered_map<string, int> st;\n \npublic:\n AuthenticationManager(int t) : t{t} \n { \n }\n \n void generate(string s, int ct) \n {\n st[s] = ct+t-1;\n }\n \n void renew(string s, int ct) \n {\n if(st[s]>=ct)\n st[s] = ct+t-1;\n }\n \n int countUnexpiredTokens(int ct) \n {\n return count_if(begin(st), end(st), [&](const auto e){ return e.second>=ct; }); \n }\n};\n``` | 1 | 0 | ['C', 'C++'] | 0 |
design-authentication-manager | Java solution using hashmap + queue beats 96% | java-solution-using-hashmap-queue-beats-skvwz | Intuition\nIn order to manage tokens effectively, we need two datastructures - a map to store token -> expiry time data and a queue to easily get the unexpired | problemsolver1111 | NORMAL | 2024-04-03T20:07:04.674928+00:00 | 2024-04-03T20:07:04.674953+00:00 | 76 | false | # Intuition\nIn order to manage tokens effectively, we need two datastructures - a map to store token -> expiry time data and a queue to easily get the unexpired token size information.\n\n# Approach\n\nFor generate and renew, simply update the map with token -> new expiry time information. When you generate a new token or update a token, update the state of the token in the queue as well\n\nCreate a separate queue cleaning up method to remove any expired tokens as you go so you can simply return the queue size for number of unexpired tokens.\n\n# Complexity\n- Time complexity:\nO(N)\n\n- Space complexity:\nO(N)\n\n# Code\n```\nclass AuthenticationManager {\n\n private static int ttl;\n HashMap<String, Integer> tokenTTLMap;\n Queue<String> queue;\n\n public AuthenticationManager(int timeToLive) {\n this.tokenTTLMap = new HashMap<>();\n this.queue = new ArrayDeque<>();\n this.ttl = timeToLive;\n }\n \n private void removeExpired(int currentTime) {\n\n while(!queue.isEmpty()) {\n String token = queue.peek();\n \n if(tokenTTLMap.containsKey(token) && tokenTTLMap.get(token) > currentTime) {\n break;\n } \n\n queue.poll();\n tokenTTLMap.remove(token);\n }\n\n }\n\n public void generate(String tokenId, int currentTime) {\n\n if(!this.tokenTTLMap.containsKey(tokenId)) {\n this.queue.add(tokenId);\n }\n\n this.tokenTTLMap.put(tokenId, currentTime + this.ttl);\n this.removeExpired(currentTime);\n }\n \n public void renew(String tokenId, int currentTime) {\n if(this.tokenTTLMap.containsKey(tokenId) && this.tokenTTLMap.get(tokenId) > currentTime) {\n this.tokenTTLMap.put(tokenId, currentTime + this.ttl);\n this.queue.remove(tokenId);\n this.queue.add(tokenId);\n } \n this.removeExpired(currentTime);\n }\n \n public int countUnexpiredTokens(int currentTime) {\n this.removeExpired(currentTime);\n \n return queue.size();\n }\n}\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * AuthenticationManager obj = new AuthenticationManager(timeToLive);\n * obj.generate(tokenId,currentTime);\n * obj.renew(tokenId,currentTime);\n * int param_3 = obj.countUnexpiredTokens(currentTime);\n */\n``` | 1 | 0 | ['Java'] | 0 |
design-authentication-manager | C++ Solution using 2 maps | c-solution-using-2-maps-by-mrcawfee-9izm | \n# Approach\n\nUsing 2 hash maps, one is the index of token_id => timestamp and another is a multimap for timestamp => iterator in the first map. There are 2 m | mrcawfee | NORMAL | 2024-02-20T19:13:49.881246+00:00 | 2024-02-20T19:13:49.881280+00:00 | 13 | false | \n# Approach\n\nUsing 2 hash maps, one is the index of token_id => timestamp and another is a multimap for timestamp => iterator in the first map. There are 2 maps so that countUnexpiredTokens() doesn\'t need to do a full scan of all nodes in the first map, only an indexed version of times.\n\n# Complexity\n- Time complexity: O(2 log n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(2n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\n\nclass AuthenticationManager {\n\nprivate:\n // time to live as provided in the constructor\n int ttl;\n\n // map of the tokens => expiry time\n typedef std::unordered_map<string, int> auth_tokens_t;\n auth_tokens_t auth_tokens;\n\n // map of expiry time => iterator in auth_tokens\n typedef std::multimap<int, auth_tokens_t::iterator > time_index_t ;\n time_index_t time_index;\n\n // Remove expired tokens\n void expire( int currentTime ) {\n\n auto e = time_index.upper_bound(currentTime);\n for ( auto i = time_index.begin(); i != e; ) {\n //printf("remove %d\\n", (*i).first);\n auto p = i;\n i++;\n auth_tokens.erase( (*p).second );\n time_index.erase(p);\n }\n }\n\npublic:\n AuthenticationManager(int timeToLive) : ttl(timeToLive){\n \n }\n \n void generate(string tokenId, int currentTime) {\n\n // get the expiration of the token\n const int tm = ttl+currentTime;\n\n // add the token to the map\n auto pair = auth_tokens.insert( auth_tokens_t::value_type( tokenId, 0 ));\n // since insert() returns the iterator to the object\n // if created, or it returns an existing iterator if it\n // already exists then we need to update time\n (*pair.first).second = tm;\n\n if ( pair.second ) {\n // pair.second from insert returns true if this is a new entry in the list, so we need to add the iterator into the parallel time_index\n time_index.insert( time_index_t::value_type( tm, pair.first ));\n }\n }\n \n void renew(string tokenId, int currentTime) {\n\n auto i = auth_tokens.find( tokenId );\n if ( i != auth_tokens.end() ) {\n if ( (*i).second > currentTime ) {\n // token can be renewed\n\n // update the expiry time in the token map\n int new_time = currentTime + ttl;\n (*i).second = new_time;\n\n // updating the time index is a bit trickier, \n // since you can\'t really update the key in a map easily we need to search for all current entries in the time index with the same timestamp\n auto range = time_index.equal_range( (*i).second );\n\n // update the index;\n for ( auto p = range.first; p != range.second; p++ ) {\n // since we are pulling all tokens with the same expiry time, we need to check to see if this is indeed the entry for that token. easy way to do it is just to see if the iterator in the time map is the same as the one in the main map\n if ( (*p).second == i ) {\n \n time_index.erase(p);\n time_index.insert( time_index_t::value_type( new_time, i ));\n break;\n }\n }\n\n } else {\n // token is already expired\n }\n } else {\n // token does not exist\n }\n }\n \n int countUnexpiredTokens(int currentTime) {\n \n int rval = 0;\n\n // using the upper_bound function, which returns an iterator for all values in the map that are >= currentTime, just iterate through them and return the value\n for ( auto i = time_index.upper_bound(currentTime); i != time_index.end(); i++, rval++);\n\n return rval;\n }\n};\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * AuthenticationManager* obj = new AuthenticationManager(timeToLive);\n * obj->generate(tokenId,currentTime);\n * obj->renew(tokenId,currentTime);\n * int param_3 = obj->countUnexpiredTokens(currentTime);\n */\n``` | 1 | 0 | ['C++'] | 0 |
design-authentication-manager | Simple Java solution with Streams | simple-java-solution-with-streams-by-mrk-uhvl | Intuition\n\nWe could store tokens in Map using token as a key and expiration time as a value.\n\n# Approach\n\nIn this approach we store state in HashMap durin | mrk-andreev | NORMAL | 2024-02-10T20:53:58.449920+00:00 | 2024-02-10T20:53:58.449953+00:00 | 221 | false | # Intuition\n\nWe could store tokens in Map using token as a key and expiration time as a value.\n\n# Approach\n\nIn this approach we store state in HashMap during all tests. This solution contains a memory leak because we don\'t clean expired tokens. Good solution will have a separate handler for removement of expired tokens.\n\nAlso, concurrency out of scope for this solution.\n\n# Complexity\n- Time complexity:\n - Count tokens $$O(n)$$\n - Generate / Renew token $$O(1)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```\n\nclass AuthenticationManager {\n private final int ttl;\n private final Map<String, Integer> tokens = new HashMap<>();\n\n public AuthenticationManager(int timeToLive) {\n this.ttl = timeToLive;\n }\n\n public void generate(String tokenId, int currentTime) {\n tokens.put(tokenId, currentTime + ttl);\n }\n\n public void renew(String tokenId, int currentTime) {\n if (tokens.containsKey(tokenId) && tokens.get(tokenId) > currentTime) {\n tokens.put(tokenId, currentTime + ttl);\n }\n }\n\n public int countUnexpiredTokens(int currentTime) {\n return (int) tokens.values().stream()\n .filter(t -> t > currentTime)\n .count();\n }\n}\n\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * AuthenticationManager obj = new AuthenticationManager(timeToLive);\n * obj.generate(tokenId,currentTime);\n * obj.renew(tokenId,currentTime);\n * int param_3 = obj.countUnexpiredTokens(currentTime);\n */\n``` | 1 | 0 | ['Java'] | 0 |
design-authentication-manager | Python solution using OrderedDict (LinkedHashMap) - new data structure learning | python-solution-using-ordereddict-linked-56z3 | Complexity\n- Time complexity:\nAverage: O(1) for each query\n\n\n# Code\n\nfrom collections import OrderedDict\n\nclass AuthenticationManager:\n\n def __ini | akki06 | NORMAL | 2024-02-10T12:52:35.941265+00:00 | 2024-02-10T12:52:35.941287+00:00 | 270 | false | # Complexity\n- Time complexity:\nAverage: O(1) for each query\n\n\n# Code\n```\nfrom collections import OrderedDict\n\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.timeToLive = timeToLive\n self.orderedTokens = OrderedDict()\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n self.orderedTokens[tokenId] = currentTime + self.timeToLive\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n if (\n tokenId in self.orderedTokens\n and currentTime < self.orderedTokens[tokenId]\n ):\n self.orderedTokens[tokenId] = currentTime + self.timeToLive\n self.orderedTokens.move_to_end(tokenId, last=True)\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n # To loop over the ordered dict without modifying it and\n # without creating an extra copy of all its keys in-memory.\n while self.orderedTokens:\n delete_me = False\n for tokenId in self.orderedTokens.keys():\n if self.orderedTokens[tokenId] <= currentTime:\n delete_me = True\n break\n if delete_me:\n del self.orderedTokens[tokenId]\n else:\n break\n\n return len(self.orderedTokens)\n\n``` | 1 | 0 | ['Python3'] | 0 |
design-authentication-manager | C++ USING SINGLE MAP | c-using-single-map-by-arpiii_7474-kafr | Code\n\nclass AuthenticationManager {\n int ttl;\n unordered_map<string,int> mp;\npublic:\n AuthenticationManager(int timeToLive) {\n ttl=timeTo | arpiii_7474 | NORMAL | 2023-09-30T19:44:44.017992+00:00 | 2023-09-30T19:44:44.018008+00:00 | 52 | false | # Code\n```\nclass AuthenticationManager {\n int ttl;\n unordered_map<string,int> mp;\npublic:\n AuthenticationManager(int timeToLive) {\n ttl=timeToLive;\n } \n void generate(string tokenId, int currentTime) {\n mp[tokenId]=currentTime+ttl;\n } \n void renew(string tokenId, int currentTime) {\n auto token=mp.find(tokenId);\n if(token!=mp.end() && mp[tokenId]>currentTime){\n mp[tokenId]=currentTime+ttl;\n }\n } \n int countUnexpiredTokens(int currentTime) {\n int res=0;\n for(auto token:mp){\n if(token.second>currentTime) res++;\n }\n return res;\n }\n};\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * AuthenticationManager* obj = new AuthenticationManager(timeToLive);\n * obj->generate(tokenId,currentTime);\n * obj->renew(tokenId,currentTime);\n * int param_3 = obj->countUnexpiredTokens(currentTime);\n */\n``` | 1 | 0 | ['C++'] | 0 |
design-authentication-manager | Heap solution (beats 99%) - O(1) generate, O(1) renew , O(nlogn) count | heap-solution-beats-99-o1-generate-o1-re-in25 | Intuition\n Describe your first thoughts on how to solve this problem. \nFirst thoughts:\n- Can generate and renew using hashmaps\n- I have to calculate the num | A-V-Jagannathan | NORMAL | 2023-09-01T19:19:44.306527+00:00 | 2023-09-01T19:19:44.306555+00:00 | 611 | false | # Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nFirst thoughts:\n- Can generate and renew using hashmaps\n- I have to calculate the number of expired tokens for count\n- Brute way is to check and remove each token, is there any faster approach?\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nHow to solve faster?\n- If i can have the token that\'s gonna expire first with me at all times , i can keep removing tokens until i find the token which has an expiry time> current time.\n- First thoughts whenever you have to keep getting minimum elements should be a heap. heappop will return the token with min expiry time.\nWell so how do i do it actually?\n## Generate\n- push (timeToLive+currentTime,tokenId) to heap\n- make hashmap[tokenid]=timeToLive+currentTime\n- Add 1 to total\n## Renew\nif hashmap[tokenid] exists,\n\n\n*if hashmap[tokenid] value is greater than currentTime*\n- make hashmap[tokenid] = timeToLive+currentTime\n- push (timeToLive+currentTime,tokenId) to heap ( i will explain why you don\'t have to change the pre existing value later on)\n\n*if its value is less than currentTime it has expired*\n- so delete hashmap[tokenid] from hashmap\n- subtract total by 1\n\nNote: we can say that the hashmap stores the **most recently updated value of expiration** for each tokens.\n\n## Count\n\n**while the heap is not empty and the top element has an expiry time less or equal to currentTime :**\n- Remove the top element from heap, lets call it removed.\n- if removed[1] (*ie , the tokenId*) exists in the hashmap\n - if it\'s value is same as removed[0]:\n - subtract 1 from total, because the hashmap stores the recent value of expiration\n - now delete hashmap[removed[1]] from hashmap as it is expired\n - if it\'s value is not same as removed[0]\n - it means that the tokenId(removed[1]) is updated and there exists one more element in heap like: (renewed_exp_time,tokenid)\n - so don\'t do anything.\n- if removed[1] doesnt exist in hashmap, then it has expired and it had been taken into account while renewing.\n\n**return total** \n\n \n# Complexity\n- Time complexity: \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(1) generate, O(1) renew , O(nlogn) count\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n) - for storing heap\n\n# Code\n```\nfrom heapq import heapify,heappop,heappush\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.heap=[]\n heapify(self.heap)\n self.d={}\n self.total=0\n self.c=[]\n self.time_to_live=timeToLive\n def generate(self, tokenId: str, currentTime: int) -> None:\n self.total+=1\n time=currentTime+self.time_to_live\n self.d[tokenId]=time\n heappush(self.heap,(time,tokenId)) \n def renew(self, tokenId: str, currentTime: int) -> None:\n time=currentTime+self.time_to_live\n if(tokenId in self.d):\n if(self.d[tokenId]>currentTime):\n self.d[tokenId]=time\n heappush(self.heap,(time,tokenId))\n else:\n del(self.d[tokenId])\n self.total-=1 \n def countUnexpiredTokens(self, currentTime: int) -> int:\n time=currentTime\n while(len(self.heap)>0 and self.heap[0][0]<=time):\n t,token=heappop(self.heap)\n if(token in self.d and self.d[token]==t):\n self.total-=1\n del(self.d[token]) \n return self.total\n \n\n\n# Your AuthenticationManager object will be instantiated and called as such:\n# obj = AuthenticationManager(timeToLive)\n# obj.generate(tokenId,currentTime)\n# obj.renew(tokenId,currentTime)\n# param_3 = obj.countUnexpiredTokens(currentTime)\n``` | 1 | 0 | ['Python', 'C++', 'Java', 'Python3'] | 1 |
design-authentication-manager | [Java] Easy 100% solution using HashMap and TreeMap | java-easy-100-solution-using-hashmap-and-7pyn | java\nimport java.util.*;\n\nclass AuthenticationManager {\n private final TreeMap<Integer, String> timestamps;\n private final Map<String, Integer> token | YTchouar | NORMAL | 2023-05-25T03:16:31.439873+00:00 | 2023-05-25T03:16:31.439913+00:00 | 1,553 | false | ```java\nimport java.util.*;\n\nclass AuthenticationManager {\n private final TreeMap<Integer, String> timestamps;\n private final Map<String, Integer> tokens;\n private final int timeToLive;\n\n public AuthenticationManager(final int timeToLive) {\n this.timestamps = new TreeMap<>();\n this.tokens = new HashMap<>();\n this.timeToLive = timeToLive;\n }\n\n public void generate(final String tokenId, final int currentTime) {\n removeExpiredTokens(currentTime);\n tokens.put(tokenId, currentTime);\n timestamps.put(currentTime, tokenId);\n }\n\n public void renew(final String tokenId, final int currentTime) {\n removeExpiredTokens(currentTime);\n if (tokens.containsKey(tokenId)) {\n int tokenTime = tokens.get(tokenId);\n if (currentTime - tokenTime < timeToLive) {\n timestamps.remove(tokenTime);\n timestamps.put(currentTime, tokenId);\n tokens.put(tokenId, currentTime);\n }\n }\n }\n\n public int countUnexpiredTokens(final int currentTime) {\n removeExpiredTokens(currentTime);\n return tokens.size();\n }\n \n private void removeExpiredTokens(final int currentTime) {\n final Iterator<Map.Entry<Integer, String>> iterator = timestamps.entrySet().iterator();\n while (iterator.hasNext()) {\n Map.Entry<Integer, String> entry = iterator.next();\n int tokenTime = entry.getKey();\n if (currentTime - tokenTime >= timeToLive) {\n String tokenId = entry.getValue();\n iterator.remove();\n tokens.remove(tokenId);\n } else {\n break;\n }\n }\n }\n}\n\n``` | 1 | 0 | ['Java'] | 1 |
design-authentication-manager | Python3 queue with explanation amortized time O(1) beats 99% | python3-queue-with-explanation-amortized-jhui | Intuition\nFailed this question at a job interview, so glad I found it at leetcode. The trick to optimal solution is to consider amortized time for countUnexpir | sleepingonee | NORMAL | 2023-03-11T12:02:45.195971+00:00 | 2023-03-11T12:04:21.472555+00:00 | 104 | false | # Intuition\nFailed this question at a job interview, so glad I found it at leetcode. The trick to optimal solution is to consider amortized time for countUnexpiredTokens method. \n\nUse two data structures:\n- live_tokens hashmap for storing count of live tokens (each successful call to method renew will increase count by one)\n- timeline queue for storing each generate/renew events\n\nAnd also helper method _prune function which will pop expired tokens from timeline queue. When number of live tokens hits zero, then we no longer count token as active in countUnexpiredTokens method.\n\n# Complexity\nn is number of calls to generate/renew methods\n\n- Time complexity:\n1. generate method: O(1)\n1. renew method: asymptotic O(n) amortized O(1)\n1. countUnexpiredTokens method: asymptotic O(n) amortized O(1)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.ttl = timeToLive\n self.live_tokens = {}\n self.timeline = deque()\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n self.live_tokens[tokenId] = 1\n self.timeline.append((currentTime, tokenId))\n \n def _prune(self, currentTime):\n while self.timeline and self.timeline[0][0] <= (currentTime - self.ttl):\n _, token = self.timeline.popleft()\n self.live_tokens[token] -= 1\n if self.live_tokens[token] == 0:\n del self.live_tokens[token]\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n self._prune(currentTime)\n if tokenId in self.live_tokens:\n self.live_tokens[tokenId] += 1\n self.timeline.append((currentTime, tokenId)) \n \n def countUnexpiredTokens(self, currentTime: int) -> int:\n self._prune(currentTime)\n return len(self.live_tokens)\n``` | 1 | 0 | ['Hash Table', 'Queue', 'Python3'] | 0 |
design-authentication-manager | c# Accepted : Easy to understand | c-accepted-easy-to-understand-by-rhazem1-att0 | \npublic class AuthenticationManager {\n public int ttl;\n Dictionary<string,int> tokens;\n public AuthenticationManager(int timeToLive) {\n thi | rhazem13 | NORMAL | 2023-03-10T10:04:44.881772+00:00 | 2023-03-10T10:04:44.881810+00:00 | 751 | false | ```\npublic class AuthenticationManager {\n public int ttl;\n Dictionary<string,int> tokens;\n public AuthenticationManager(int timeToLive) {\n this.ttl = timeToLive;\n tokens=new();\n }\n \n public void Generate(string tokenId, int currentTime) {\n tokens.Add(tokenId,currentTime);\n }\n \n public void Renew(string tokenId, int currentTime) {\n if(tokens.ContainsKey(tokenId))\n if(currentTime-tokens[tokenId]<ttl)\n tokens[tokenId]=currentTime;\n }\n \n public int CountUnexpiredTokens(int currentTime) {\n int count=0;\n foreach(var kvp in tokens){\n if(currentTime-kvp.Value<ttl)\n count++;\n }\n return count;\n }\n}\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * AuthenticationManager obj = new AuthenticationManager(timeToLive);\n * obj.Generate(tokenId,currentTime);\n * obj.Renew(tokenId,currentTime);\n * int param_3 = obj.CountUnexpiredTokens(currentTime);\n */\n``` | 1 | 0 | [] | 0 |
design-authentication-manager | Java solution using LinkedHashMap beats 100% with detailed description | java-solution-using-linkedhashmap-beats-yeyvo | Intuition\nWe need to maintain the sessions of different token ids and need a data structure which helps in reduce time by sorting the sessions by their expiry | ayushprakash1912 | NORMAL | 2023-01-12T19:02:02.771674+00:00 | 2023-01-12T19:02:02.771721+00:00 | 84 | false | # Intuition\nWe need to maintain the sessions of different token ids and need a data structure which helps in reduce time by sorting the sessions by their expiry time. \n\n# Approach\nI have used a linked HashMap. TreeMap may also be used. \nBenefit of using a linked HashMap is that it iterated through the key set in the order of their insertion. Everytime you add a new session, its get added as the last node and the session which is inserted last will expire last. The only case we need to handle is the case of renewal. \nWhile you are renewing a session, clean the map of the ones already expired(to avoid renewing the already expired tokenIds). Since the renewed session will be the last to expire till that time, we have to move the tokenId to last of the LinkedHashMap\'s linkedList to ensure the ordering, for doing it, simply remove the entry and then create a fresh entry with the new expiry.\nWhenever we have to count the number of unexpired sessions, simply clean the map off the expired session and return the size of the map. For removing the map with the expired tokens, simply iterate through the keys and keep removing the keys till we find the first unexpired token since the linkedHashMap is sorted in the order by expiryTime\n\n# Complexity\n- Time complexity:\nComplexity of generation: O(1);\nComplexity of renew: O(n);\nComplexity of count: O(n);\n\nWorst case: O(n2) [for n operations]\n\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass AuthenticationManager {\n\n int timeToLive;\n Map<String, Integer> map;\n\n public AuthenticationManager(int timeToLive) {\n this.timeToLive = timeToLive;\n map = new LinkedHashMap<>();\n }\n \n public void generate(String tokenId, int currentTime) {\n map.put(tokenId, currentTime+timeToLive);\n }\n \n public void renew(String tokenId, int currentTime) {\n removeExpiredSessions(currentTime);\n if(map.containsKey(tokenId)) {\n map.remove(tokenId);\n map.put(tokenId, currentTime+timeToLive);\n }\n }\n \n public int countUnexpiredTokens(int currentTime) {\n\n removeExpiredSessions(currentTime);\n return map.size();\n }\n\n public void removeExpiredSessions(int currentTime) {\n \n Iterator<Map.Entry<String,Integer>> iter = map.entrySet().iterator();\n \n while(iter.hasNext()) {\n Map.Entry<String,Integer> entry = iter.next();\n if(entry.getValue()<=currentTime){\n iter.remove();\n } else {\n break;\n }\n }\n }\n}\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * AuthenticationManager obj = new AuthenticationManager(timeToLive);\n * obj.generate(tokenId,currentTime);\n * obj.renew(tokenId,currentTime);\n * int param_3 = obj.countUnexpiredTokens(currentTime);\n */\n``` | 1 | 0 | ['Ordered Map', 'Java'] | 0 |
design-authentication-manager | JS Simple Solution | js-simple-solution-by-edwardfalcon-5hkg | \n/**\n * @param {number} timeToLive\n */\nvar AuthenticationManager = function (timeToLive) {\n this.timeToLive = timeToLive;\n this.currentTime = 0;\n this | edwardfalcon | NORMAL | 2022-11-09T17:38:13.779151+00:00 | 2022-11-09T17:38:13.779192+00:00 | 187 | false | ```\n/**\n * @param {number} timeToLive\n */\nvar AuthenticationManager = function (timeToLive) {\n this.timeToLive = timeToLive;\n this.currentTime = 0;\n this.tokens = {};\n};\n\n/**\n * @param {string} tokenId\n * @param {number} currentTime\n * @return {void}\n */\nAuthenticationManager.prototype.generate = function (tokenId, currentTime) {\n this.currentTime = currentTime;\n this.tokens[tokenId] = this.currentTime + this.timeToLive;\n};\n\n/**\n * @param {string} tokenId\n * @param {number} currentTime\n * @return {void}\n */\nAuthenticationManager.prototype.renew = function (tokenId, currentTime) {\n this.currentTime = currentTime;\n if (this.tokens[tokenId] > this.currentTime) {\n this.tokens[tokenId] = this.currentTime + this.timeToLive;\n } else {\n delete this.tokens[tokenId];\n }\n};\n\n/**\n * @param {number} currentTime\n * @return {number}\n */\nAuthenticationManager.prototype.countUnexpiredTokens = function (currentTime) {\n this.currentTime = currentTime;\n let count = 0;\n for (let tokenId in this.tokens) {\n if (this.tokens[tokenId] > this.currentTime) {\n count++;\n } else {\n delete this.tokens[tokenId];\n }\n }\n return count;\n};\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * var obj = new AuthenticationManager(timeToLive)\n * obj.generate(tokenId,currentTime)\n * obj.renew(tokenId,currentTime)\n * var param_3 = obj.countUnexpiredTokens(currentTime)\n */\n``` | 1 | 0 | ['Hash Table', 'JavaScript'] | 0 |
design-authentication-manager | C++ Single Map Solution | c-single-map-solution-by-rahul_v_2001-nnt0 | This Solution is Also works very fine.\n\nclass AuthenticationManager {\npublic:\n int n;\n AuthenticationManager(int timeToLive) {\n n = timeToLiv | rahul_v_2001 | NORMAL | 2022-09-10T17:28:34.632214+00:00 | 2022-09-10T17:28:34.632252+00:00 | 760 | false | This Solution is Also works very fine.\n```\nclass AuthenticationManager {\npublic:\n int n;\n AuthenticationManager(int timeToLive) {\n n = timeToLive;\n }\n unordered_map<string, int> mp;\n void generate(string tokenId, int currentTime) {\n if(mp.find(tokenId) == mp.end()){\n mp.insert({tokenId, currentTime});\n }\n }\n \n void renew(string tokenId, int currentTime) {\n if(mp.find(tokenId) != mp.end()){\n if(n + mp[tokenId] > currentTime){\n mp[tokenId] = currentTime;\n }\n }\n }\n \n int countUnexpiredTokens(int currentTime) {\n int ans = 0;\n for(auto x : mp){\n if(x.second + n > currentTime){\n ans++;\n }\n }\n return ans;\n }\n};\n``` | 1 | 0 | [] | 1 |
design-authentication-manager | C++ easy solution using stl | c-easy-solution-using-stl-by-mananagrawa-zjdl | \nclass AuthenticationManager {\n int timeToLive;\n unordered_map<string, int> tokens;\npublic:\n AuthenticationManager(int timeToLive) {\n this | mananagrawal26 | NORMAL | 2022-07-16T12:36:53.580432+00:00 | 2022-07-16T12:36:53.580462+00:00 | 609 | false | ```\nclass AuthenticationManager {\n int timeToLive;\n unordered_map<string, int> tokens;\npublic:\n AuthenticationManager(int timeToLive) {\n this->timeToLive = timeToLive;\n }\n \n void generate(string tokenId, int currentTime) {\n tokens[tokenId] = currentTime;\n }\n \n void renew(string tokenId, int currentTime) {\n if(tokens.find(tokenId) == tokens.end())\n return;\n if(tokens[tokenId] + timeToLive <= currentTime)\n tokens.erase(tokenId);\n else\n tokens[tokenId] = currentTime;\n }\n \n int countUnexpiredTokens(int currentTime) {\n int count = 0;\n unordered_map<string, int>:: iterator p;\n for (p = tokens.begin(); p != tokens.end(); p++){\n if(p->second + timeToLive > currentTime)\n count++;\n }\n return count;\n }\n};\n``` | 1 | 0 | ['C', 'C++'] | 0 |
design-authentication-manager | [Rust] Token HashMap | rust-token-hashmap-by-kurosuha-imzs | rust\nuse std::{\n cell::RefCell,\n cmp::Ordering,\n collections::hash_map::Entry::Occupied,\n collections::{hash_map::Entry::Vacant, BTreeSet},\n | kurosuha | NORMAL | 2022-06-28T06:26:43.637932+00:00 | 2022-06-28T06:26:43.637982+00:00 | 97 | false | ```rust\nuse std::{\n cell::RefCell,\n cmp::Ordering,\n collections::hash_map::Entry::Occupied,\n collections::{hash_map::Entry::Vacant, BTreeSet},\n collections::{BTreeMap, BinaryHeap, HashMap, HashSet, VecDeque},\n rc::Rc,\n};\n\n\n\nstruct AuthenticationManager {\n time_to_live: i32,\n tokens: HashMap<String, i32>,\n}\n\nimpl AuthenticationManager {\n fn new(time_to_live: i32) -> Self {\n Self {\n time_to_live,\n tokens: HashMap::new(),\n }\n }\n\n fn generate(&mut self, token_id: String, current_time: i32) {\n self.tokens\n .insert(token_id, current_time + self.time_to_live);\n }\n\n fn renew(&mut self, token_id: String, current_time: i32) {\n self.clean_expired_tokens(current_time);\n match self.tokens.entry(token_id) {\n Occupied(mut entry) => *entry.get_mut() = current_time + self.time_to_live,\n Vacant(_) => (),\n }\n }\n\n fn count_unexpired_tokens(&mut self, current_time: i32) -> i32 {\n self.clean_expired_tokens(current_time);\n self.tokens.len() as i32\n }\n\n fn clean_expired_tokens(&mut self, current_time: i32) {\n self.tokens.retain(|_, exp_time| *exp_time > current_time)\n }\n}\n\n``` | 1 | 0 | [] | 1 |
design-authentication-manager | C++ (simple hash map design) | c-simple-hash-map-design-by-dakre-545n | \nclass AuthenticationManager {\n int ttl_;\n unordered_map<string, int> s_;\npublic:\n AuthenticationManager(int ttl): ttl_(ttl) {\n \n }\n | dakre | NORMAL | 2022-06-23T00:31:52.743543+00:00 | 2022-06-23T00:32:06.884882+00:00 | 121 | false | ```\nclass AuthenticationManager {\n int ttl_;\n unordered_map<string, int> s_;\npublic:\n AuthenticationManager(int ttl): ttl_(ttl) {\n \n }\n \n void generate(string tid, int ct) {\n s_[tid] = ct;\n }\n \n void renew(string tid, int ct) {\n if (s_.find(tid) == s_.end()) return;\n if (s_[tid] + ttl_ <= ct) s_.erase(tid);\n else s_[tid] = ct;\n }\n \n int countUnexpiredTokens(int ct) {\n int cnt = 0;\n vector<string> to_exp;\n for (auto& [token, time] : s_) {\n if (time + ttl_ <= ct) to_exp.emplace_back(token);\n else cnt++;\n }\n for (const auto& t : to_exp) s_.erase(t);\n return cnt;\n }\n};\n``` | 1 | 0 | ['C'] | 0 |
design-authentication-manager | Simple and readable Java solution (HashMap) | simple-and-readable-java-solution-hashma-yhs2 | \nclass AuthenticationManager {\n private int ttl;\n private Map<String, Integer> map;\n\n public AuthenticationManager(int timeToLive) {\n this | RuslanVdovychenko | NORMAL | 2022-06-18T15:30:58.197493+00:00 | 2022-06-18T15:30:58.197523+00:00 | 371 | false | ```\nclass AuthenticationManager {\n private int ttl;\n private Map<String, Integer> map;\n\n public AuthenticationManager(int timeToLive) {\n this.ttl = timeToLive;\n this.map = new HashMap<>();\n }\n \n public void generate(String tokenId, int currentTime) {\n map.put(tokenId, currentTime + this.ttl);\n }\n \n public void renew(String tokenId, int currentTime) {\n Integer expirationTime = this.map.getOrDefault(tokenId, null);\n if (expirationTime == null || expirationTime <= currentTime)\n return;\n \n generate(tokenId, currentTime);\n }\n \n public int countUnexpiredTokens(int currentTime) {\n int count = 0;\n for (Map.Entry<String, Integer> entry: this.map.entrySet())\n if (entry.getValue() > currentTime)\n count++;\n \n return count;\n }\n}\n\n``` | 1 | 0 | ['Java'] | 0 |
design-authentication-manager | Go language using FibonacciHeap | go-language-using-fibonacciheap-by-andri-wi00 | \n// Heap Node.\ntype Node struct {\n\t// \u0421\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0435 \u0443\u0437\u043B\u0430.\n\tx string\n\t// \u041A\u043B\ | andribas404 | NORMAL | 2022-03-31T08:31:18.071773+00:00 | 2022-03-31T08:31:18.071801+00:00 | 119 | false | ```\n// Heap Node.\ntype Node struct {\n\t// \u0421\u043E\u0434\u0435\u0440\u0436\u0438\u043C\u043E\u0435 \u0443\u0437\u043B\u0430.\n\tx string\n\t// \u041A\u043B\u044E\u0447\n\tkey int\n\t// \u041F\u0440\u0435\u0434\u043E\u043A \u0443\u0437\u043B\u0430\n\tparent *Node\n\t// \u041B\u0435\u0432\u044B\u0439 \u0431\u0440\u0430\u0442\u0441\u043A\u0438\u0439 / \u0441\u0435\u0441\u0442\u0440\u0438\u043D\u0441\u043A\u0438\u0439 \u0443\u0437\u0435\u043B\n\tleft *Node\n\t// \u041F\u0440\u0430\u0432\u044B\u0439 \u0431\u0440\u0430\u0442\u0441\u043A\u0438\u0439 / \u0441\u0435\u0441\u0442\u0440\u0438\u043D\u0441\u043A\u0438\u0439 \u0443\u0437\u0435\u043B\n\tright *Node\n\t// \u041F\u0440\u044F\u043C\u043E\u0439 \u043F\u043E\u0442\u043E\u043C\u043E\u043A \u0443\u0437\u043B\u0430\n\tchild *Node\n\t// \u0420\u0430\u043D\u0433 \u0443\u0437\u043B\u0430 = \u043A\u043E\u043B-\u0432\u043E \u043F\u0440\u044F\u043C\u044B\u0445 \u043F\u043E\u0442\u043E\u043C\u043A\u043E\u0432\n\trank int\n\t// \u041F\u0435\u0440\u0435\u043C\u0435\u0449\u0430\u043B\u0438\u0441\u044C \u043B\u0438 \u0440\u0430\u043D\u0435\u0435 \u043F\u043E\u0442\u043E\u043C\u043A\u0438 \u044D\u0442\u043E\u0433\u043E \u0443\u0437\u043B\u0430\n\tmarked bool\n}\n\nfunc ConstructNode(x string, key int) Node {\n\t// Node initialization.\n\tthis := Node{\n\t\tx: x,\n\t\tkey: key,\n\t}\n\treturn this\n}\n\nfunc (this *Node) _extract() {\n\t// \u0423\u0434\u0430\u043B\u0435\u043D\u0438\u0435 \u0441\u0432\u044F\u0437\u0435\u0439 \u043F\u0435\u0440\u0435\u0434 \u043F\u0435\u0440\u0435\u043D\u043E\u0441\u043E\u043C \u0443\u0437\u043B\u0430.\n\tthis.parent = nil\n\tthis.left = nil\n\tthis.right = nil\n}\n\nfunc (this *Node) __repr__() string {\n\t// Node representation.\n\treturn fmt.Sprintf("Node(x={%d})", this.x)\n}\n\n// \u0424\u0438\u0431\u043E\u043D\u0430\u0447\u0447\u0438\u0435\u0432\u0430 \u043A\u0443\u0447\u0430.\ntype FibonacciHeap struct {\n\tminNode *Node\n}\n\nfunc ConstructHeap(node *Node) *FibonacciHeap {\n\t/*\n\t \u0421\u043E\u0437\u0434\u0430\u043D\u0438\u0435 \u043D\u043E\u0432\u043E\u0439 \u0444\u0438\u0431\u043E\u043D\u0430\u0447\u0447\u0438\u0435\u0432\u043E\u0439 \u043A\u0443\u0447\u0438.\n\n\t \u0412\u0440\u0435\u043C\u044F \u0440\u0430\u0431\u043E\u0442\u044B: O(1)\n\t*/\n\tthis := &FibonacciHeap{minNode: node}\n\treturn this\n}\n\nfunc (this *FibonacciHeap) insert(node *Node) {\n\t/*\n\t \u0412\u0441\u0442\u0430\u0432\u043A\u0430 \u0443\u0437\u043B\u0430 node \u0432 \u0441\u043F\u0438\u0441\u043E\u043A \u043A\u043E\u0440\u043D\u0435\u0432\u044B\u0445 \u0443\u0437\u043B\u043E\u0432.\n\n\t \u0412\u0440\u0435\u043C\u044F \u0440\u0430\u0431\u043E\u0442\u044B: O(1)\n\t*/\n\th2 := ConstructHeap(nil)\n\th2._set_min(node)\n\tthis.meld(h2)\n}\n\nfunc (this *FibonacciHeap) _set_min(node *Node) {\n\t/*\n\t \u0423\u0441\u0442\u0430\u043D\u043E\u0432\u043A\u0430 \u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u0443\u0437\u043B\u0430.\n\n\t \u0412\u0440\u0435\u043C\u044F \u0440\u0430\u0431\u043E\u0442\u044B: O(1)\n\t*/\n\tthis.minNode = node\n}\n\nfunc (this *FibonacciHeap) _update_min(node *Node) {\n\t/*\n\t \u041E\u0431\u043D\u043E\u0432\u043B\u0435\u043D\u0438\u0435 \u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u0443\u0437\u043B\u0430, \u0435\u0441\u043B\u0438 \u043A\u043B\u044E\u0447 \u043C\u0435\u043D\u044C\u0448\u0435.\n\n\t \u0412\u0440\u0435\u043C\u044F \u0440\u0430\u0431\u043E\u0442\u044B: O(1)\n\t*/\n\tcurrent := this.find_min()\n\tif current == nil {\n\t\tthis._set_min(node)\n\t} else if node != nil && node.key <= current.key {\n\t\tthis._set_min(node)\n\t}\n}\n\nfunc (this *FibonacciHeap) find_min() *Node {\n\t/*\n\t \u041F\u043E\u0438\u0441\u043A \u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u0443\u0437\u043B\u0430.\n\n\t \u0412\u0440\u0435\u043C\u044F \u0440\u0430\u0431\u043E\u0442\u044B: O(1)\n\t*/\n\treturn this.minNode\n}\n\nfunc (this *FibonacciHeap) meld(h *FibonacciHeap) {\n\t/*\n\t \u041E\u0431\u044A\u0435\u0434\u0438\u043D\u0435\u043D\u0438\u0435 \u0434\u0432\u0443\u0445 \u0444\u0438\u0431\u043E\u043D\u0430\u0447\u0447\u0438\u0435\u0432\u044B\u0445 \u043A\u0443\u0447.\n\n\t \u0412\u0440\u0435\u043C\u044F \u0440\u0430\u0431\u043E\u0442\u044B: O(1)\n\t*/\n\tnode1 := this.find_min()\n\tnode2 := h.find_min()\n\t// \u0421\u043A\u043B\u0435\u0438\u0432\u0430\u043D\u0438\u0435 \u0434\u0432\u0443\u0445 \u0434\u0432\u0443\u0441\u0432\u044F\u0437\u043D\u044B\u0445 \u0441\u043F\u0438\u0441\u043A\u043E\u0432 (\u043A\u043E\u043B\u0435\u0446)\n\t// x - \u0443\u0434\u0430\u043B\u044F\u0435\u043C\u0430\u044F \u0441\u0432\u044F\u0437\u044C\n\t// left1 <-x node1 -> right1\n\t// X\n\t// left2 <-x node2 -> right2\n\n\t// \u0414\u043E\u0431\u0430\u0432\u043B\u044F\u0435\u043C\u0430\u044F \u043A\u0443\u0447\u0430 \u043F\u0443\u0441\u0442\u0430\n\tif node2 == nil {\n\t\treturn\n\t}\n\n\t// \u0418\u0441\u0445\u043E\u0434\u043D\u0430\u044F \u043A\u0443\u0447\u0430 \u043F\u0443\u0441\u0442\u0430\n\tif node1 == nil {\n\t\tthis._set_min(node2)\n\t\treturn\n\t}\n\n\t// \u041F\u043E\u0441\u043A\u043E\u043B\u044C\u043A\u0443 \u0441\u043F\u0438\u0441\u043E\u043A \u0434\u0432\u0443\u0441\u0432\u044F\u0437\u043D\u044B\u0439 \u043A\u043E\u043B\u044C\u0446\u0435\u0432\u043E\u0439, \u0442\u043E \u0435\u0441\u043B\u0438 \u0435\u0441\u0442\u044C \u043B\u0435\u0432\u044B\u0439 \u0443\u0437\u0435\u043B,\n\t// \u0442\u043E \u0441\u0443\u0449\u0435\u0441\u0442\u0432\u0443\u0435\u0442 \u043F\u0440\u0430\u0432\u044B\u0439 (\u0440\u0430\u0432\u0435\u043D \u043B\u0435\u0432\u043E\u043C\u0443 \u0438\u043B\u0438 \u0434\u0440\u0443\u0433\u043E\u043C\u0443)\n\t// \u0415\u0441\u043B\u0438 \u0432 \u0441\u043F\u0438\u0441\u043A\u0435 1 \u044D\u043B\u0435\u043C\u0435\u043D\u0442, \u0442\u043E \u043E\u043D \u043D\u0435 \u0443\u043A\u0430\u0437\u044B\u0432\u0430\u0435\u0442 \u0441\u0430\u043C \u043D\u0430 \u0441\u0435\u0431\u044F = None\n\tleft1 := node1.left\n\tleft2 := node2.left\n\n\t// \u0412 \u0438\u0441\u0445\u043E\u0434\u043D\u043E\u0439 \u043A\u0443\u0447\u0435 1 \u043A\u043E\u0440\u043D\u0435\u0432\u043E\u0439 \u0443\u0437\u0435\u043B\n\tif left1 == nil {\n\t\tif left2 != nil {\n\t\t\t// \u041F\u043E \u043B\u0435\u0432\u043E\u043C\u0443 \u0443\u0437\u043B\u0443 \u0432\u0442\u043E\u0440\u043E\u0439 \u043A\u0443\u0447\u0438\n\t\t\t// node1\n\t\t\t// | |\n\t\t\t// left2 <-x node2\n\t\t\tnode1.left = left2\n\t\t\tnode1.right = node2\n\t\t\tleft2.right = node1\n\t\t\tnode2.left = node1\n\t\t} else {\n\t\t\t// \u0412 \u043E\u0431\u0435\u0438\u0445 \u043A\u0443\u0447\u0430\u0445 1 \u043A\u043E\u0440\u043D\u0435\u0432\u043E\u0439 \u0443\u0437\u0435\u043B\n\t\t\t// node1\n\t\t\t// |\n\t\t\t// node2\n\t\t\tnode1.left = node2\n\t\t\tnode1.right = node2\n\t\t\tnode2.left = node1\n\t\t\tnode2.right = node1\n\t\t}\n\t} else {\n\t\t// \u0421\u043A\u043B\u0435\u0438\u0432\u0430\u0435\u043C \u0447\u0435\u0440\u0435\u0437 \u043B\u0435\u0432\u044B\u0439 \u043A\u043E\u0440\u043D\u0435\u0432\u043E\u0439 \u0443\u0437\u0435\u043B \u0432\u0442\u043E\u0440\u043E\u0439 \u043A\u0443\u0447\u0438\n\t\tif left2 != nil {\n\t\t\t// left1 <-x node1\n\t\t\t// X\n\t\t\t// left2 <-x node2\n\t\t\t// \u043D\u0430\u0438\u0441\u043A\u043E\u0441\u043E\u043A\n\t\t\tleft1.right = node2\n\t\t\tnode1.left = left2\n\t\t\tleft2.right = node1\n\t\t\tnode2.left = left1\n\t\t\t// \u0412\u043E \u0432\u0442\u043E\u0440\u043E\u0439 \u043A\u0443\u0447\u0435 1 \u043A\u043E\u0440\u043D\u0435\u0432\u043E\u0439 \u0443\u0437\u0435\u043B\n\t\t} else {\n\t\t\t// left1 <-x node1\n\t\t\t// | |\n\t\t\t// node2\n\t\t\tnode2.left = left1\n\t\t\tnode2.right = node1\n\t\t\tleft1.right = node2\n\t\t\tnode1.left = node2\n\t\t}\n\t}\n\t// \u0415\u0441\u043B\u0438 \u043D\u0443\u0436\u043D\u043E, \u043E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C \u043C\u0438\u043D\u0438\u043C\u0443\u043C\n\tthis._update_min(node2)\n}\n\nfunc (this *FibonacciHeap) delete_min() *Node {\n\t/*\n\t \u0418\u0437\u0432\u043B\u0435\u0447\u0435\u043D\u0438\u0435 \u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u043E\u0433\u043E \u0443\u0437\u043B\u0430.\n\n\t \tx\n\t \t/ | \\\n\t c1 c2 c3\n\t \u0410\u043C\u043E\u0440\u0442\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0435 \u0432\u0440\u0435\u043C\u044F \u0440\u0430\u0431\u043E\u0442\u044B: O(log n)\n\t*/\n\troot := this.find_min()\n\tif root == nil {\n\t\t// raise ValueError("\u041A\u0443\u0447\u0430 \u043F\u0443\u0441\u0442\u0430")\n\t\treturn nil\n\t}\n\t// \u0423\u0441\u0442\u0430\u043D\u0430\u0432\u043B\u0438\u0432\u0430\u0435\u043C \u0432\u0440\u0435\u043C\u0435\u043D\u043D\u043E \u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u044B\u0439 \u0443\u0437\u0435\u043B \u043D\u0430 \u043B\u0435\u0432\u044B\u0439\n\tthis._set_min(root.left)\n\t// \u0423\u0434\u0430\u043B\u044F\u0435\u043C \u0438\u0437 \u0441\u043F\u0438\u0441\u043A\u0430 \u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u044B\u0439 \u0443\u0437\u0435\u043B\n\tthis._unlink(root)\n\t// \u0421\u043E\u0437\u0434\u0430\u0435\u043C \u043D\u043E\u0432\u0443\u044E \u043A\u0443\u0447\u0443 \u0438\u0437 \u043F\u043E\u0442\u043E\u043C\u043A\u043E\u0432 root (\u0443 \u043D\u0438\u0445 \u043F\u0440\u0435\u0436\u043D\u0438\u0439 parent)\n\th := ConstructHeap(root.child)\n\tthis.meld(h)\n\tthis._consolidate()\n\troot._extract()\n\troot.child = nil\n\treturn root\n}\n\nfunc (this *FibonacciHeap) _unlink(node *Node) *Node {\n\t/*\n\t \u0418\u0437\u0432\u043B\u0435\u0447\u0435\u043D\u0438\u0435 \u0443\u0437\u043B\u0430 \u0438\u0437 \u0434\u0432\u0443\u0445\u0441\u0432\u044F\u0437\u043D\u043E\u0433\u043E \u0441\u043F\u0438\u0441\u043A\u0430.\n\n\t \u0412\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 \u043B\u0435\u0432\u044B\u0439 \u0443\u0437\u0435\u043B \u0438\u0437 \u043E\u0441\u0442\u0430\u0432\u0448\u0438\u0445\u0441\u044F \u0432 \u0441\u043F\u0438\u0441\u043A\u0435, \u043B\u0438\u0431\u043E None\n\t left - node - right = left - right\n\t \u0412\u0440\u0435\u043C\u044F \u0440\u0430\u0431\u043E\u0442\u044B: O(1)\n\t*/\n\tleft := node.left\n\tright := node.right\n\n\t// \u0412 \u0441\u043F\u0438\u0441\u043A\u0435 1 \u044D\u043B\u0435\u043C\u0435\u043D\u0442 - \u0443\u0434\u0430\u043B\u044F\u0435\u043C\u044B\u0439\n\tif left == nil {\n\t\treturn nil\n\t}\n\n\tif left == right {\n\t\t// \u0412 \u0441\u043F\u0438\u0441\u043A\u0435 \u0431\u044B\u043B\u043E 2 \u044D\u043B\u0435\u043C\u0435\u043D\u0442\u0430\n\t\tleft.left = nil\n\t\tleft.right = nil\n\t} else {\n\t\tleft.right = right\n\t\tright.left = left\n\t}\n\n\treturn left\n}\n\nfunc (this *FibonacciHeap) _consolidate() {\n\t/*\n\t \u0423\u043F\u043B\u043E\u0442\u043D\u0435\u043D\u0438\u0435 \u0441\u043F\u0438\u0441\u043A\u0430 \u043A\u043E\u0440\u043D\u0435\u0439 - \u0441\u043A\u043B\u0435\u0438\u0432\u0430\u043D\u0438\u0435 \u0434\u0435\u0440\u0435\u0432\u044C\u0435\u0432 \u0441 \u043E\u0434\u0438\u043D\u0430\u043A\u043E\u0432\u044B\u043C \u0440\u0430\u043D\u0433\u043E\u043C.\n\n\t \u041E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u0442 \u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u044B\u0439 \u0443\u0437\u0435\u043B\n\t \u0438 \u0443\u0441\u0442\u0430\u043D\u0430\u0432\u043B\u0438\u0432\u0430\u0435\u0442 parent=None \u0434\u043B\u044F \u0432\u0441\u0435\u0445 \u043A\u043E\u0440\u043D\u0435\u0432\u044B\u0445 \u0443\u0437\u043B\u043E\u0432\n\t \u0412\u0440\u0435\u043C\u044F \u0440\u0430\u0431\u043E\u0442\u044B: O(log n)\n\t*/\n\t// \u0432\u0440\u0435\u043C\u0435\u043D\u043D\u044B\u0439 \u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u044B\u0439 \u0443\u0437\u0435\u043B\n\troot := this.find_min()\n\tif root == nil {\n\t\treturn\n\t}\n\n\t// \u0421\u043B\u043E\u0432\u0430\u0440\u044C \u043A\u043E\u0440\u043D\u0435\u0432\u044B\u0445 \u0443\u0437\u043B\u043E\u0432 \u0432\u0438\u0434\u0430 \u0440\u0430\u043D\u0433 -> \u0443\u0437\u0435\u043B\n\tranked := map[int]*Node{}\n\tranked[root.rank] = root\n\troot.parent = nil\n\tnode := root.right\n\n\tfor {\n\t\tif node == nil {\n\t\t\tbreak\n\t\t}\n\t\t// \u0423 \u043A\u043E\u0440\u043D\u044F \u043D\u0435\u0442 \u043F\u0440\u0435\u0434\u043A\u043E\u0432\n\t\tnode.parent = nil\n\t\t// \u0422\u0435\u043A\u0443\u0449\u0438\u0439 \u0443\u0437\u0435\u043B\n\t\tmelded := node\n\t\t// \u0421\u043B\u0435\u0434\u0443\u044E\u0449\u0438\u0439 \u043F\u0440\u043E\u0441\u043C\u0430\u0442\u0440\u0438\u0432\u0430\u0435\u043C\u044B\u0439 \u0443\u0437\u0435\u043B\n\t\tnode = node.right\n\t\tv, ok := ranked[node.rank]\n\t\tif ok && v == node {\n\t\t\t// \u041C\u044B \u0442\u0430\u043C \u0443\u0436\u0435 \u0431\u044B\u043B\u0438, \u043F\u043E\u044D\u0442\u043E\u043C\u0443 \u044D\u0442\u0430 \u0438\u0442\u0435\u0440\u0430\u0446\u0438\u044F \u043F\u043E\u0441\u043B\u0435\u0434\u043D\u044F\u044F\n\t\t\tnode = nil\n\t\t}\n\n\t\tfor {\n\t\t\t// \u0412 \u0441\u043F\u0438\u0441\u043A\u0435 \u043A\u043E\u0440\u043D\u0435\u0439 \u0435\u0441\u0442\u044C \u0434\u0435\u0440\u0435\u0432\u043E \u0441 \u0442\u0430\u043A\u0438\u043C \u0436\u0435 \u0440\u0430\u043D\u0433\u043E\u043C.\n\t\t\trank := melded.rank\n\n\t\t\tv, ok := ranked[rank]\n\t\t\tif !ok {\n\t\t\t\tbreak\n\t\t\t}\n\t\t\t// \u0421\u043A\u043B\u0435\u0438\u0432\u0430\u0435\u043C\n\t\t\tmelded = this._link(melded, v)\n\t\t\t// \u0438 \u0443\u0434\u0430\u043B\u044F\u0435\u043C \u0438\u0437 \u0441\u043B\u043E\u0432\u0430\u0440\u044F \u043F\u0440\u0435\u0436\u043D\u0438\u0439 \u0440\u0430\u043D\u0433\n\t\t\tdelete(ranked, rank)\n\t\t}\n\t\t// \u043E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C \u0441 \u043D\u043E\u0432\u044B\u043C \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u0435\u043C \u0440\u0430\u043D\u0433\u0430 \u043F\u043E\u043B\u0443\u0447\u0438\u0432\u0448\u0435\u0435\u0441\u044F \u0434\u0435\u0440\u0435\u0432\u043E\n\t\tranked[melded.rank] = melded\n\t\t// \u041E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C \u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u044B\u0439 \u0443\u0437\u0435\u043B\n\t\tthis._update_min(melded)\n\t}\n}\n\nfunc (this *FibonacciHeap) _link(node1 *Node, node2 *Node) *Node {\n\t/*\n\t \u0421\u043A\u043B\u0435\u0438\u0432\u0430\u043D\u0438\u0435 \u0434\u0432\u0443\u0445 \u043A\u043E\u0440\u043D\u0435\u0439.\n\n\t \u041A\u043E\u0440\u043D\u0435\u043C \u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0441\u044F \u0443\u0437\u0435\u043B \u0441 \u043C\u0435\u043D\u044C\u0448\u0438\u043C \u043A\u043B\u044E\u0447\u043E\u043C, \u0432\u0442\u043E\u0440\u043E\u0439 - \u0435\u0433\u043E \u043F\u043E\u0442\u043E\u043C\u043A\u043E\u043C\n\t \u0412\u043E\u0437\u0432\u0440\u0430\u0449\u0430\u0435\u0442 \u043F\u043E\u043B\u0443\u0447\u0438\u0432\u0448\u0438\u0439\u0441\u044F \u043A\u043E\u0440\u0435\u043D\u044C\n\t \u0412\u0440\u0435\u043C\u044F \u0440\u0430\u0431\u043E\u0442\u044B: O(1)\n\t*/\n\tif node1.key > node2.key {\n\t\tnode1, node2 = node2, node1\n\t}\n\t// node1 node1\n\t// | -> |\n\t// child node2 - child\n\n\t// node2 \u0438\u0437\u0432\u043B\u0435\u043A\u0430\u0435\u0442\u0441\u044F \u0438\u0437 \u0441\u043F\u0438\u0441\u043A\u0430 \u043A\u043E\u0440\u043D\u0435\u0439\n\tthis._unlink(node2)\n\tnode2._extract()\n\t// \u0443\u0431\u0438\u0440\u0430\u0435\u0442\u0441\u044F \u043E\u0442\u043C\u0435\u0442\u043A\u0430\n\tnode2.marked = false\n\t// \u0438 \u043E\u043D \u0441\u0442\u0430\u043D\u043E\u0432\u0438\u0442\u0441\u044F \u043F\u043E\u0442\u043E\u043C\u043A\u043E\u043C node1\n\tnode2.parent = node1\n\t// \u041E\u0431\u043D\u043E\u0432\u043B\u044F\u0435\u043C \u0440\u0430\u043D\u0433 \u043F\u043E\u043B\u0443\u0447\u0438\u0432\u0448\u0435\u0433\u043E\u0441\u044F \u0434\u0435\u0440\u0435\u0432\u0430\n\tnode1.rank += 1\n\n\t// \u041F\u043E\u0442\u043E\u043C\u043E\u043A \u043F\u0435\u0440\u0432\u043E\u0433\u043E \u043A\u043E\u0440\u043D\u044F\n\tchild := node1.child\n\tif child == nil {\n\t\t// \u0415\u0441\u043B\u0438 \u043D\u0435\u0442 \u043F\u043E\u0442\u043E\u043C\u043A\u043E\u0432\n\t\tnode1.child = node2\n\t} else {\n\t\tleft := child.left\n\t\tif left == nil {\n\t\t\t// \u041E\u0434\u0438\u043D \u043F\u043E\u0442\u043E\u043C\u043E\u043A\n\t\t\t// child - node2\n\t\t\tchild.left = node2\n\t\t\tchild.right = node2\n\t\t\tnode2.left = child\n\t\t\tnode2.right = child\n\t\t} else {\n\t\t\t// left <-x child\n\t\t\t// | |\n\t\t\t// node2\n\t\t\tnode2.left = left\n\t\t\tnode2.right = child\n\t\t\tleft.right = node2\n\t\t\tchild.left = node2\n\t\t}\n\t}\n\n\treturn node1\n}\n\nfunc (this *FibonacciHeap) decrease_key(node *Node, newkey int) {\n\t/*\n\t \u0423\u043C\u0435\u043D\u044C\u0448\u0435\u043D\u0438\u0435 \u043A\u043B\u044E\u0447\u0430 \u0443\u0437\u043B\u0430 node \u0434\u043E \u0437\u043D\u0430\u0447\u0435\u043D\u0438\u044F newkey.\n\n\t \u0412\u0440\u0435\u043C\u044F \u0440\u0430\u0431\u043E\u0442\u044B: O(1)\n\t*/\n\tnode.key = newkey\n\n\tif node.parent == nil {\n\t\t// \u0423\u0437\u0435\u043B - \u043A\u043E\u0440\u043D\u0435\u0432\u043E\u0439\n\t\tthis._update_min(node)\n\t\treturn\n\t}\n\n\tparent := node.parent\n\tparent.rank -= 1\n\tparent.child = this._unlink(node)\n\tthis._cascading_cut(parent)\n\tnode._extract()\n\tthis.insert(node)\n}\n\nfunc (this *FibonacciHeap) _cut(node *Node) {\n\t/*\n\t \u041F\u043E\u0434\u0440\u0435\u0437\u043A\u0430 \u0434\u0435\u0440\u0435\u0432\u0430 - \u043F\u0435\u0440\u0435\u043D\u043E\u0441 node \u0432 \u0441\u043F\u0438\u0441\u043E\u043A \u043A\u043E\u0440\u043D\u0435\u0439.\n\n\t \u0412\u0440\u0435\u043C\u044F \u0440\u0430\u0431\u043E\u0442\u044B: O(1)\n\t*/\n\tparent := node.parent\n\tif parent == nil {\n\t\t// \u0423\u0437\u0435\u043B \u0443\u0436\u0435 \u043A\u043E\u0440\u043D\u0435\u0432\u043E\u0439\n\t\treturn\n\t}\n\tparent.rank -= 1\n\tparent.child = this._unlink(node)\n\tnode._extract()\n\tthis.insert(node)\n}\n\nfunc (this *FibonacciHeap) _cascading_cut(node *Node) {\n\t/*\n\t \u041A\u0430\u0441\u043A\u0430\u0434\u043D\u0430\u044F \u043F\u043E\u0434\u0440\u0435\u0437\u043A\u0430 \u0434\u0435\u0440\u0435\u0432\u0430.\n\n\t \u041D\u0430\u0447\u0438\u043D\u0430\u044F \u043E\u0442 \u0443\u0437\u043B\u0430 node, \u0438 \u043F\u043E\u043A\u0430 \u043F\u0440\u0435\u0434\u0448\u0435\u0441\u0442\u0432\u0443\u044E\u0449\u0438\u0439 \u0443\u0437\u0435\u043B \u0438\u043C\u0435\u0435\u0442 \u043E\u0442\u043C\u0435\u0442\u043A\u0443\n\t \u043E \u043F\u0435\u0440\u0435\u043C\u0435\u0449\u0435\u043D\u0438\u0438 (marked = True), \u0432\u0441\u0435 \u043E\u043D\u0438 \u0441\u0442\u0430\u043D\u043E\u0432\u044F\u0442\u0441\u044F \u043A\u043E\u0440\u043D\u0435\u0432\u044B\u043C\u0438.\n\n\t \u0412\u0440\u0435\u043C\u044F \u0440\u0430\u0431\u043E\u0442\u044B: O(log n)\n\t*/\n\tparent := node\n\tfor {\n\t\tif parent == nil {\n\t\t\tbreak\n\t\t}\n\t\tif !parent.marked {\n\t\t\tparent.marked = true\n\t\t\treturn\n\t\t} else {\n\t\t\tnode = parent\n\t\t\tparent = node.parent\n\t\t\tthis._cut(node)\n\t\t}\n\t}\n}\n\nfunc (this *FibonacciHeap) remove(node *Node) *Node {\n\t/*\n\t \u0423\u0434\u0430\u043B\u0435\u043D\u0438\u0435 \u0443\u0437\u043B\u0430 node.\n\n\t \u0410\u043C\u043E\u0440\u0442\u0438\u0437\u0438\u0440\u043E\u0432\u0430\u043D\u043D\u043E\u0435 \u0432\u0440\u0435\u043C\u044F \u0440\u0430\u0431\u043E\u0442\u044B: O(log n)\n\t*/\n\tif node == this.find_min() {\n\t\t// \u0423\u0437\u0435\u043B - \u043C\u0438\u043D\u0438\u043C\u0430\u043B\u044C\u043D\u044B\u0439\n\t\treturn this.delete_min()\n\t}\n\n\tparent := node.parent\n\tif parent == nil {\n\t\t// \u0423\u0437\u0435\u043B - \u043A\u043E\u0440\u043D\u0435\u0432\u043E\u0439\n\t\tthis._unlink(node)\n\t} else {\n\t\tparent.rank -= 1\n\t\tparent.child = this._unlink(node)\n\t\tthis._cascading_cut(parent)\n\t}\n\n\th := ConstructHeap(node.child)\n\tthis.meld(h)\n\tthis._consolidate()\n\tnode._extract()\n\tnode.child = nil\n\treturn node\n}\n\n\n\ntype AuthenticationManager struct {\n fh *FibonacciHeap\n timeToLive int\n nodes map[string]*Node\n}\n\n\nfunc Constructor(timeToLive int) AuthenticationManager {\n this := AuthenticationManager{\n fh: ConstructHeap(nil),\n timeToLive: timeToLive,\n nodes: map[string]*Node{},\n }\n return this\n}\n\n\nfunc (this *AuthenticationManager) Generate(tokenId string, currentTime int) {\n expired := currentTime + this.timeToLive\n node := ConstructNode(tokenId, expired)\n this.nodes[tokenId] = &node\n this.fh.insert(&node)\n}\n\n\nfunc (this *AuthenticationManager) Renew(tokenId string, currentTime int) {\n node, ok := this.nodes[tokenId]\n if !ok {\n return\n }\n this.fh.remove(node)\n if node.key <= currentTime {\n delete(this.nodes, tokenId)\n return\n }\n expired := currentTime + this.timeToLive\n node.key = expired\n this.fh.insert(node) \n \n}\n\n\nfunc (this *AuthenticationManager) CountUnexpiredTokens(currentTime int) int {\n for {\n node := this.fh.find_min()\n if node == nil {\n break\n }\n if node.key <= currentTime {\n this.fh.delete_min()\n delete(this.nodes, node.x)\n } else {\n break\n }\n }\n return len(this.nodes)\n}\n``` | 1 | 0 | ['Go'] | 1 |
design-authentication-manager | ✅ [Solution] Swift: Design Authentication Manager | solution-swift-design-authentication-man-ab95 | swift\nclass AuthenticationManager {\n \n private struct Token {\n let id: String\n let time: Int\n }\n \n private let timeToLive:I | AsahiOcean | NORMAL | 2022-03-31T05:41:01.149347+00:00 | 2022-03-31T05:41:01.149378+00:00 | 1,126 | false | ```swift\nclass AuthenticationManager {\n \n private struct Token {\n let id: String\n let time: Int\n }\n \n private let timeToLive:Int\n private var tokens: [Token] = []\n private var unexpTokens: [String:Int] = [:]\n \n init(_ timeToLive: Int) {\n self.timeToLive = timeToLive\n }\n \n func generate(_ id: String, _ ct: Int) {\n cleanTokens(ct)\n insert(Token(id: id, time: ct + timeToLive))\n }\n \n func renew(_ id: String, _ ct: Int) {\n cleanTokens(ct)\n guard let tm = unexpTokens[id] else { return }\n if let idx = binarySearch(Token(id: id, time: tm)) {\n tokens.remove(at: idx)\n insert(Token(id: id, time: ct + timeToLive))\n }\n }\n \n func countUnexpiredTokens(_ ct: Int) -> Int {\n cleanTokens(ct)\n return tokens.count\n }\n \n \n private func insert(_ tk: Token) {\n unexpTokens[tk.id] = tk.time\n guard !tokens.isEmpty else {\n tokens.append(tk)\n return\n }\n if let idx = binarySearch(tk) {\n if idx == tokens.count {\n tokens.append(tk)\n } else {\n tokens.insert(tk, at: idx)\n }\n }\n }\n private func binarySearch(_ tk: Token) -> Int? {\n guard !tokens.isEmpty else { return nil }\n guard tokens[0].time <= tk.time else { return 0 }\n guard tokens.last!.time >= tk.time else { return tokens.count }\n var lhs = 0, rhs = tokens.count - 1\n while lhs < rhs {\n let mid = (lhs + rhs) >> 1\n if tokens[mid].time >= tk.time {\n rhs = mid\n } else {\n lhs = mid + 1\n }\n }\n return lhs\n }\n \n private func cleanTokens(_ tm: Int) {\n while !tokens.isEmpty && tokens[0].time <= tm {\n unexpTokens.removeValue(forKey: tokens[0].id)\n tokens.removeFirst()\n }\n }\n}\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * let obj = AuthenticationManager(timeToLive)\n * obj.generate(tokenId, currentTime)\n * obj.renew(tokenId, currentTime)\n * let ret_3: Int = obj.countUnexpiredTokens(currentTime)\n*/\n``` | 1 | 0 | ['Swift'] | 0 |
design-authentication-manager | Java TimeMap and AuthMap using TreeMap | java-timemap-and-authmap-using-treemap-b-dxa6 | \nclass AuthenticationManager {\n int ttl;\n TreeMap<String,Integer>authMap;\n TreeMap<Integer,String>timeMap;\n public AuthenticationManager(int ti | vikas_belida_09 | NORMAL | 2022-03-30T03:26:07.581865+00:00 | 2022-03-30T03:26:07.581906+00:00 | 116 | false | ```\nclass AuthenticationManager {\n int ttl;\n TreeMap<String,Integer>authMap;\n TreeMap<Integer,String>timeMap;\n public AuthenticationManager(int timeToLive) {\n ttl=timeToLive;\n authMap=new TreeMap<>();\n timeMap=new TreeMap<>();\n }\n \n public void generate(String tokenId, int currentTime) {\n authMap.put(tokenId,currentTime);\n timeMap.put(currentTime,tokenId);\n }\n \n public void renew(String tokenId, int currentTime) {\n if(!authMap.containsKey(tokenId))return;\n int time=authMap.get(tokenId);\n if(time+ttl > currentTime){\n timeMap.remove(time);\n authMap.put(tokenId,currentTime);\n timeMap.put(currentTime,tokenId);\n }\n }\n \n public int countUnexpiredTokens(int currentTime) {\n return timeMap.subMap(currentTime-ttl+1,currentTime).size();\n }\n}\n``` | 1 | 0 | ['Java'] | 1 |
design-authentication-manager | Java Clean Code | java-clean-code-by-fllght-kc96 | ```\nprivate final int timeToLive;\n private final Map tokens;\n\n public AuthenticationManager(int timeToLive) {\n this.timeToLive = timeToLive;\n | FLlGHT | NORMAL | 2022-03-19T11:22:44.271583+00:00 | 2022-03-19T11:22:44.271630+00:00 | 73 | false | ```\nprivate final int timeToLive;\n private final Map<String, Integer> tokens;\n\n public AuthenticationManager(int timeToLive) {\n this.timeToLive = timeToLive;\n this.tokens = new HashMap<>();\n }\n\n public void generate(String tokenId, int currentTime) {\n tokens.put(tokenId, currentTime);\n }\n\n public void renew(String tokenId, int currentTime) {\n if (!tokens.containsKey(tokenId)) return;\n\n if (currentTime - tokens.get(tokenId) >= timeToLive) return;\n tokens.put(tokenId, currentTime);\n }\n\n public int countUnexpiredTokens(int currentTime) {\n int counter = 0;\n for (int timeStart : tokens.values()) {\n if (currentTime - timeStart < timeToLive)\n counter++;\n }\n\n return counter;\n } | 1 | 0 | ['Java'] | 0 |
design-authentication-manager | Python | SortedList | python-sortedlist-by-lyili-8wsk | \nfrom sortedcontainers import SortedList\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.timeToLive = timeToLive\n | lyili | NORMAL | 2022-01-24T04:59:56.071618+00:00 | 2022-01-24T04:59:56.071666+00:00 | 117 | false | ```\nfrom sortedcontainers import SortedList\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.timeToLive = timeToLive\n self.tokenExpireTime = defaultdict(int)\n self.sortedExpireTime = SortedList()\n \n\n def generate(self, tokenId: str, currentTime: int) -> None:\n self.tokenExpireTime[tokenId] = currentTime + self.timeToLive\n self.sortedExpireTime.add(currentTime + self.timeToLive)\n \n\n def renew(self, tokenId: str, currentTime: int) -> None:\n if tokenId not in self.tokenExpireTime:\n return\n if currentTime < self.tokenExpireTime[tokenId]:\n expireTime = self.tokenExpireTime[tokenId]\n self.sortedExpireTime.remove(expireTime)\n \n expireTime = currentTime + self.timeToLive\n self.tokenExpireTime[tokenId] = expireTime\n self.sortedExpireTime.add(expireTime)\n \n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n index = self.sortedExpireTime.bisect_right(currentTime)\n return len(self.sortedExpireTime) - index\n \n\n\n# Your AuthenticationManager object will be instantiated and called as such:\n# obj = AuthenticationManager(timeToLive)\n# obj.generate(tokenId,currentTime)\n# obj.renew(tokenId,currentTime)\n# param_3 = obj.countUnexpiredTokens(currentTime)\n``` | 1 | 0 | [] | 0 |
design-authentication-manager | Java Solution | java-solution-by-jxie418-zy2o | \nclass AuthenticationManager {\n private int timeToLive = 0;\n private Map<String, Integer> map = new HashMap<>();\n\n public AuthenticationManager(in | jxie418 | NORMAL | 2021-08-07T17:43:42.515523+00:00 | 2021-08-07T17:43:42.515551+00:00 | 143 | false | ```\nclass AuthenticationManager {\n private int timeToLive = 0;\n private Map<String, Integer> map = new HashMap<>();\n\n public AuthenticationManager(int timeToLive) {\n this.timeToLive = timeToLive;\n }\n \n public void generate(String tokenId, int currentTime) {\n map.put(tokenId, currentTime + timeToLive);\n }\n \n public void renew(String tokenId, int currentTime) {\n if (map.containsKey(tokenId) && map.get(tokenId) > currentTime)\n generate(tokenId, currentTime);\n }\n \n public int countUnexpiredTokens(int currentTime) {\n map.entrySet().removeIf(e-> e.getValue() <= currentTime);\n return map.size();\n }\n}\n``` | 1 | 0 | [] | 1 |
design-authentication-manager | C++ single map solution | c-single-map-solution-by-aparna_g-vvbi | \nclass AuthenticationManager {\npublic:\n int lifetime;\n unordered_map<string , int> id_time; \n //id , time it expires \n AuthenticationManager(i | aparna_g | NORMAL | 2021-07-10T19:36:36.054878+00:00 | 2021-07-10T19:36:36.054922+00:00 | 136 | false | ```\nclass AuthenticationManager {\npublic:\n int lifetime;\n unordered_map<string , int> id_time; \n //id , time it expires \n AuthenticationManager(int timeToLive) {\n lifetime = timeToLive;\n }\n \n void generate(string tokenId, int curr) {\n id_time[tokenId] = curr + lifetime;\n }\n \n void renew(string tokenId, int currentTime) {\n\t//first check if it is possible to renew\n if(id_time.find(tokenId) == id_time.end() || id_time[tokenId] <= currentTime) \n return;\n id_time[tokenId] = currentTime + lifetime;\n }\n \n int countUnexpiredTokens(int currentTime) {\n int ans = 0;\n for(auto m : id_time) {\n if(m.second > currentTime)\n ans++;\n }\n return ans;\n }\n};\n``` | 1 | 0 | ['C', 'C++'] | 0 |
design-authentication-manager | My Java Solution using HashMap Straight forward approach | my-java-solution-using-hashmap-straight-dh2fg | \nclass AuthenticationManager {\n\n private Map<String, Integer> map;\n private int timeToLive;\n public AuthenticationManager(int timeToLive) {\n | vrohith | NORMAL | 2021-03-31T07:33:33.831336+00:00 | 2021-03-31T07:33:33.831365+00:00 | 148 | false | ```\nclass AuthenticationManager {\n\n private Map<String, Integer> map;\n private int timeToLive;\n public AuthenticationManager(int timeToLive) {\n map = new HashMap<>(); \n this.timeToLive = timeToLive;\n }\n \n public void generate(String tokenId, int currentTime) {\n map.put(tokenId, timeToLive + currentTime);\n }\n \n public void renew(String tokenId, int currentTime) {\n if (map.containsKey(tokenId) && map.get(tokenId) > currentTime) {\n map.put(tokenId, timeToLive + currentTime);\n }\n }\n \n public int countUnexpiredTokens(int currentTime) {\n map.entrySet().removeIf(x -> x.getValue() <= currentTime); // prevent ConcurrentModificationException\n return map.size();\n }\n}\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * AuthenticationManager obj = new AuthenticationManager(timeToLive);\n * obj.generate(tokenId,currentTime);\n * obj.renew(tokenId,currentTime);\n * int param_3 = obj.countUnexpiredTokens(currentTime);\n */\n``` | 1 | 0 | ['Design', 'Java'] | 0 |
design-authentication-manager | Python using LinkedHashmap | python-using-linkedhashmap-by-msk200-733g | \nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.ttl = timeToLive\n self.cache = OrderedDict() #linkedHashmap usi | msk200 | NORMAL | 2021-03-25T18:28:55.471848+00:00 | 2021-03-25T18:28:55.471880+00:00 | 157 | false | ```\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.ttl = timeToLive\n self.cache = OrderedDict() #linkedHashmap using in LRU cache\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n self.cache[tokenId] = currentTime + self.ttl\n \n def renew(self, tokenId: str, currentTime: int) -> None:\n if tokenId not in self.cache:\n return\n expiryTime = self.cache[tokenId]\n if expiryTime > currentTime:\n self.cache[tokenId] = currentTime + self.ttl\n self.cache.move_to_end(tokenId)\n \n def countUnexpiredTokens(self, currentTime: int) -> int:\n while self.cache and next(iter(self.cache.values())) <= currentTime:\n self.cache.popitem(last=False)\n return len(self.cache)\n \n \n# Your AuthenticationManager object will be instantiated and called as such:\n# obj = AuthenticationManager(timeToLive)\n# obj.generate(tokenId,currentTime)\n# obj.renew(tokenId,currentTime)\n# param_3 = obj.countUnexpiredTokens(currentTime)\n``` | 1 | 0 | [] | 0 |
design-authentication-manager | Java Simple code using HashMap | java-simple-code-using-hashmap-by-champd-uho8 | \nclass AuthenticationManager {\n int time;\n HashMap<String,Integer> arr=new HashMap<String,Integer>();\n public AuthenticationManager(int timeToLive) | champdev | NORMAL | 2021-03-21T03:20:32.269779+00:00 | 2021-03-21T03:20:32.269805+00:00 | 94 | false | ```\nclass AuthenticationManager {\n int time;\n HashMap<String,Integer> arr=new HashMap<String,Integer>();\n public AuthenticationManager(int timeToLive) {\n time=timeToLive;\n }\n \n public void generate(String tokenId, int currentTime) {\n arr.put(tokenId,currentTime+time);//put tokenId,expiryTime in map\n }\n \n public void renew(String tokenId, int currentTime) {\n if(arr.containsKey(tokenId))\n if(currentTime<arr.get(tokenId))\n arr.put(tokenId,currentTime+time);//update expiryTime\n }\n \n public int countUnexpiredTokens(int currentTime) {\n int k=0;\n for(int i:arr.values()){\n if(i>currentTime)\n k++;\n }\n return k;\n }\n}\n``` | 1 | 0 | ['Java'] | 0 |
design-authentication-manager | C++ simple code | easy to understand |using map | c-simple-code-easy-to-understand-using-m-04na | \nclass AuthenticationManager {\npublic:\n int live;\n map<string,int>m;\n AuthenticationManager(int timeToLive) {\n live = timeToLive;\n }\n | srinivasteja18 | NORMAL | 2021-03-21T02:17:20.664610+00:00 | 2021-03-21T02:17:20.664641+00:00 | 37 | false | ```\nclass AuthenticationManager {\npublic:\n int live;\n map<string,int>m;\n AuthenticationManager(int timeToLive) {\n live = timeToLive;\n }\n void generate(string t, int time) {\n m[t] = time;\n }\n void renew(string t, int time) {\n if(m.find(t) != m.end()){\n if(m[t]+live > time) m[t]=time;\n }\n }\n int countUnexpiredTokens(int time) {\n int cnt=0;\n for(auto it:m){\n if(it.second+live > time) cnt++;\n }\n return cnt;\n }\n};\n```\nPlease upvote if you like the code | 1 | 0 | [] | 0 |
design-authentication-manager | CPP||easy solution ||fast | cppeasy-solution-fast-by-ashish_200088-yf3x | \nclass AuthenticationManager {\npublic:\n int t;\n map<string,int>m1;\n AuthenticationManager(int timeToLive) {\n t=timeToLive;\n }\n \n | ashish_200088 | NORMAL | 2021-03-20T18:25:55.346752+00:00 | 2021-03-20T18:25:55.346782+00:00 | 48 | false | ```\nclass AuthenticationManager {\npublic:\n int t;\n map<string,int>m1;\n AuthenticationManager(int timeToLive) {\n t=timeToLive;\n }\n \n void generate(string tokenId, int currentTime) {\n m1[tokenId]=currentTime+t;\n }\n \n void renew(string tokenId, int currentTime) {\n if(m1[tokenId]!=0)\n {\n if(m1[tokenId]>currentTime)\n {\n m1[tokenId]=t+currentTime;\n }\n }\n }\n \n int countUnexpiredTokens(int currentTime) {\n int c=0;\n for(auto a:m1)\n {\n if(a.second>currentTime)\n c++;\n }\n return c;\n }\n};\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * AuthenticationManager* obj = new AuthenticationManager(timeToLive);\n * obj->generate(tokenId,currentTime);\n * obj->renew(tokenId,currentTime);\n * int param_3 = obj->countUnexpiredTokens(currentTime);\n */\n``` | 1 | 0 | [] | 0 |
design-authentication-manager | Java Solution Using HashMap | java-solution-using-hashmap-by-sriram-nu-qffk | Note: Make sure to remove the unnecessary tokens in the renew function and countUnexpiredTokens function to avoid TLE.\n\nclass AuthenticationManager {\n Map | sriram-nuthi | NORMAL | 2021-03-20T17:51:45.908940+00:00 | 2021-03-20T17:51:45.908989+00:00 | 62 | false | Note: Make sure to remove the unnecessary tokens in the renew function and countUnexpiredTokens function to avoid TLE.\n```\nclass AuthenticationManager {\n Map<String, Integer> tokens=new HashMap<>();\n int timeToLive;\n public AuthenticationManager(int timeToLive) {\n this.timeToLive=timeToLive;\n }\n \n public void generate(String tokenId, int currentTime) {\n if(!tokens.containsKey(tokenId)){\n tokens.put(tokenId,currentTime+timeToLive);\n }\n }\n \n public void renew(String tokenId, int currentTime) {\n if(!tokens.containsKey(tokenId)){\n return;\n }\n if(tokens.get(tokenId)>currentTime){\n tokens.put(tokenId,currentTime+timeToLive);\n }else{\n tokens.remove(tokenId);\n }\n }\n \n public int countUnexpiredTokens(int currentTime) {\n int count=0;\n System.out.print(tokens.size()+" ");\n for(Map.Entry entry: tokens.entrySet()){\n System.out.print(entry.getValue());\n if((int)(entry.getValue()) > currentTime){\n // System.out.print("test");\n count++;\n }else{\n tokens.remove(entry);\n }\n }\n return count;\n }\n}\n``` | 1 | 0 | [] | 0 |
design-authentication-manager | [Python] Priority queue O(NlogN) / deque O(N) | python-priority-queue-onlogn-deque-on-by-h78b | During the contest I used priority que but then I realized time is strictly increasing\ncan just use deque to make it faster ( and the logic is the same)\n\ncla | b99202050 | NORMAL | 2021-03-20T16:23:40.496607+00:00 | 2021-03-20T17:09:51.470412+00:00 | 66 | false | During the contest I used priority que but then I realized time is strictly increasing\ncan just use deque to make it faster ( and the logic is the same)\n```\nclass AuthenticationManager:\n def __init__(self, timeToLive: int):\n self.state = defaultdict(int) ### self.state[tokenId] > 0 means active \n self.PQ = [] ###priority queue (expired time, tokenId)\n self.t = timeToLive\n self.active = 0\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n self.state[tokenId] = 1\n\t\t### push the new tokenId into priority queue with expired time (currentTime+self.t)\n heapq.heappush(self.PQ,(currentTime+self.t,tokenId))\n self.active += 1\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n\t\t### first pop the expired terms in priority que\n while self.PQ and self.PQ[0][0] <= currentTime:\n tokenID = heapq.heappop(self.PQ)[1]\n self.state[tokenID] -= 1\n if self.state[tokenID] == 0: ### state goes from 1 to 0 means an active token has expired\n self.active -= 1\n if self.state[tokenId] > 0:\n self.state[tokenId] += 1\n heapq.heappush(self.PQ,(currentTime+self.t,tokenId))\n\t\t\t###note that we "update" the expired time for the given tokenId so the number of active tokens remains\n\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n while self.PQ and self.PQ[0][0] <= currentTime:\n tokenID = heapq.heappop(self.PQ)[1]\n self.state[tokenID] -= 1\n if self.state[tokenID] == 0:\n self.active -= 1\n return self.active\n```\n\n```\nclass AuthenticationManager:\n def __init__(self, timeToLive: int):\n self.state = defaultdict(int)\n self.que = deque([])\n self.t = timeToLive\n self.active = 0\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n self.state[tokenId] = 1\n self.que.append([currentTime+self.t,tokenId])\n self.active += 1\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n while self.que and self.que[0][0] <= currentTime:\n tokenID = self.que.popleft()[1]\n self.state[tokenID] -= 1\n if self.state[tokenID] == 0:\n self.active -= 1\n if self.state[tokenId] > 0:\n self.state[tokenId] += 1\n self.que.append([currentTime+self.t,tokenId])\n\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n while self.que and self.que[0][0] <= currentTime:\n tokenID = self.que.popleft()[1]\n self.state[tokenID] -= 1\n if self.state[tokenID] == 0:\n self.active -= 1\n return self.active | 1 | 0 | [] | 0 |
design-authentication-manager | Single map Very easy C++ solution | single-map-very-easy-c-solution-by-anike-pl7c | ```\nclass AuthenticationManager {\npublic:\n int time;\n unordered_mapm;\n AuthenticationManager(int timeToLive) {\n time = timeToLive;\n }\ | aniket_jain_ | NORMAL | 2021-03-20T16:08:25.711950+00:00 | 2021-03-20T16:08:41.633546+00:00 | 58 | false | ```\nclass AuthenticationManager {\npublic:\n int time;\n unordered_map<string,int>m;\n AuthenticationManager(int timeToLive) {\n time = timeToLive;\n }\n \n void generate(string tokenId, int currentTime) {\n m[tokenId] = currentTime;\n }\n \n void renew(string tokenId, int currentTime) {\n if(m.find(tokenId)!=m.end() && m[tokenId] + time > currentTime){\n m[tokenId] = currentTime;\n }\n }\n \n int countUnexpiredTokens(int currentTime) {\n int ans = 0;\n for(auto x:m){\n if(x.second + time > currentTime){\n ans++;\n }\n }\n return ans;\n \n }\n};\n\n/**\n * Your AuthenticationManager object will be instantiated and called as such:\n * AuthenticationManager* obj = new AuthenticationManager(timeToLive);\n * obj->generate(tokenId,currentTime);\n * obj->renew(tokenId,currentTime);\n * int param_3 = obj->countUnexpiredTokens(currentTime);\n */ | 1 | 1 | [] | 0 |
design-authentication-manager | Java solution - straight forward | java-solution-straight-forward-by-akiram-iuda | \nclass AuthenticationManager {\n int ttl = 0;\n Map<String, Integer> map;\n\n public AuthenticationManager(int timeToLive) {\n this.ttl = timeT | akiramonster | NORMAL | 2021-03-20T16:07:52.763040+00:00 | 2021-03-20T16:07:52.763090+00:00 | 75 | false | ```\nclass AuthenticationManager {\n int ttl = 0;\n Map<String, Integer> map;\n\n public AuthenticationManager(int timeToLive) {\n this.ttl = timeToLive;\n this.map = new HashMap<>();\n }\n\n public void generate(String tokenId, int currentTime) {\n map.put(tokenId, currentTime);\n }\n\n public void renew(String tokenId, int currentTime) {\n if (!map.containsKey(tokenId)) return;\n if (currentTime - map.get(tokenId) < ttl) {\n map.put(tokenId, currentTime);\n }\n }\n\n public int countUnexpiredTokens(int currentTime) {\n int count = 0;\n for (int t : map.values()) {\n if (currentTime - t < ttl) {\n count++;\n }\n }\n return count;\n }\n}\n``` | 1 | 1 | [] | 0 |
design-authentication-manager | Unordered Map Solution C++ | unordered-map-solution-c-by-kunalsuri-5tha | \nclass AuthenticationManager {\npublic:\n unordered_map<string, int> map;\n int expired, tol;\n AuthenticationManager(int timeToLive) {\n this- | kunalsuri | NORMAL | 2021-03-20T16:07:24.757833+00:00 | 2021-03-20T16:07:24.757895+00:00 | 95 | false | ```\nclass AuthenticationManager {\npublic:\n unordered_map<string, int> map;\n int expired, tol;\n AuthenticationManager(int timeToLive) {\n this->tol = timeToLive;\n expired = 0;\n }\n \n void generate(string tokenId, int currentTime) {\n map[tokenId] = currentTime + this->tol;\n }\n \n void renew(string tokenId, int currentTime) {\n auto itr = map.find(tokenId);\n if (itr != map.end() && map[tokenId] > currentTime) {\n generate(tokenId, currentTime);\n }\n }\n \n int countUnexpiredTokens(int currentTime) {\n expired = 0;\n for (auto itr = map.begin(); itr != map.end(); itr++ ) {\n if (itr->second > currentTime) {\n expired++;\n }\n }\n return expired;\n }\n};\n\n``` | 1 | 0 | ['C'] | 0 |
design-authentication-manager | [Python3] dict(HashMap) | python3-dicthashmap-by-zonda_yang-tptf | python\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.timeToLive = timeToLive\n self.tokens = dict()\n \n | zonda_yang | NORMAL | 2021-03-20T16:04:45.612223+00:00 | 2021-03-20T16:04:45.612250+00:00 | 135 | false | ```python\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.timeToLive = timeToLive\n self.tokens = dict()\n \n def generate(self, tokenId: str, currentTime: int) -> None:\n self.tokens[tokenId] = currentTime + self.timeToLive\n \n def renew(self, tokenId: str, currentTime: int) -> None:\n if tokenId in self.tokens:\n token_time = self.tokens[tokenId]\n if token_time > currentTime:\n self.tokens[tokenId] = currentTime + self.timeToLive\n else:\n del self.tokens[tokenId]\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n count = 0\n for tokenId, token_time in self.tokens.copy().items():\n if token_time <= currentTime:\n del self.tokens[tokenId]\n else:\n count += 1\n\n return count\n``` | 1 | 0 | [] | 1 |
design-authentication-manager | [Python3] hash map | python3-hash-map-by-ye15-bpvt | \n\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.timeToLive = timeToLive\n self.tokens = {}\n\n def generate | ye15 | NORMAL | 2021-03-20T16:01:25.776672+00:00 | 2021-03-21T00:36:20.277368+00:00 | 146 | false | \n```\nclass AuthenticationManager:\n\n def __init__(self, timeToLive: int):\n self.timeToLive = timeToLive\n self.tokens = {}\n\n def generate(self, tokenId: str, currentTime: int) -> None:\n self.tokens[tokenId] = currentTime + self.timeToLive\n\n def renew(self, tokenId: str, currentTime: int) -> None:\n if tokenId in self.tokens and self.tokens[tokenId] > currentTime: \n self.tokens[tokenId] = currentTime + self.timeToLive\n\n def countUnexpiredTokens(self, currentTime: int) -> int:\n for token in self.tokens.copy(): \n if self.tokens[token] <= currentTime: # not expired yet \n self.tokens.pop(token)\n return len(self.tokens)\n``` | 1 | 0 | ['Python3'] | 0 |
design-authentication-manager | 🗺 C++ 2 maps (time + name) | c-2-maps-time-name-by-claytonjwong-1797 | \nclass AuthenticationManager {\n int K; // time-to-live\n using Set = unordered_set<string>;\n using TimeMap = map<int, Set>;\n using NameMap = uno | claytonjwong | NORMAL | 2021-03-20T16:00:55.862982+00:00 | 2021-03-20T17:22:26.542068+00:00 | 170 | false | ```\nclass AuthenticationManager {\n int K; // time-to-live\n using Set = unordered_set<string>;\n using TimeMap = map<int, Set>;\n using NameMap = unordered_map<string, int>;\n TimeMap timeMap;\n NameMap nameMap;\n void processExpiry(int t) {\n auto last = timeMap.upper_bound(t); // < t\n for (auto it = timeMap.begin(); it != last; ++it) {\n auto [_, ids] = tie(it->first, it->second);\n for (auto& id: ids)\n nameMap.erase(id);\n }\n timeMap.erase(timeMap.begin(), last);\n }\npublic:\n AuthenticationManager(int K) : K{ K } {\n }\n void generate(string id, int t) {\n timeMap[t + K].insert(id);\n nameMap[id] = t + K;\n }\n void renew(string id, int t) {\n processExpiry(t);\n if (nameMap.find(id) == nameMap.end()) // has it expired?\n return;\n auto last = nameMap[id];\n auto it = timeMap.lower_bound(last);\n auto [_, ids] = tie(it->first, it->second);\n ids.erase(id);\n generate(id, t);\n }\n int countUnexpiredTokens(int t) {\n processExpiry(t);\n return nameMap.size();\n }\n};\n``` | 1 | 0 | [] | 1 |
design-authentication-manager | Java HashMap | java-hashmap-by-vikrant_pc-h40f | \nclass AuthenticationManager {\n int timeToLive;\n Map<String, Integer> map = new HashMap<>();\n\n public AuthenticationManager(int timeToLive) {\n | vikrant_pc | NORMAL | 2021-03-20T16:00:55.589953+00:00 | 2021-03-20T16:00:55.589981+00:00 | 125 | false | ```\nclass AuthenticationManager {\n int timeToLive;\n Map<String, Integer> map = new HashMap<>();\n\n public AuthenticationManager(int timeToLive) {\n this.timeToLive=timeToLive;\n }\n \n public void generate(String tokenId, int currentTime) {\n map.put(tokenId, currentTime);\n }\n \n public void renew(String tokenId, int currentTime) {\n if(map.containsKey(tokenId) && currentTime >= map.get(tokenId) && currentTime < map.get(tokenId) + timeToLive) \n map.put(tokenId, currentTime);\n }\n \n public int countUnexpiredTokens(int currentTime) {\n int result = 0;\n for(Map.Entry<String, Integer> e: map.entrySet())\n if(currentTime >= e.getValue() && currentTime < e.getValue() + timeToLive)\n result++;\n return result; \n }\n}\n``` | 1 | 1 | [] | 0 |
design-authentication-manager | Java AC Solution | HashMap | java-ac-solution-hashmap-by-kyuhiladaala-5vww | IntuitionApproachComplexity
Time complexity:
generate() - O(1)
renew() - O(1)
countUnexpiredTokens() - O(n), where n is the number of distinct tokens stored in | kyuHilaDaalaNa | NORMAL | 2025-04-11T06:07:17.171554+00:00 | 2025-04-11T06:07:17.171554+00:00 | 1 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
# Approach
<!-- Describe your approach to solving the problem. -->
# Complexity
- Time complexity:
generate() - O(1)
renew() - O(1)
countUnexpiredTokens() - O(n), where n is the number of distinct tokens stored in tokenExpiryTime
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity:
O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```java []
class AuthenticationManager {
private int ttL;
private Map<String, Integer> tokenExpiryTime;
public AuthenticationManager(int timeToLive) {
this.ttL = timeToLive;
this.tokenExpiryTime = new HashMap<>();
}
public void generate(String tokenId, int currentTime) {
tokenExpiryTime.put(tokenId, currentTime+ttL);
}
public void renew(String tokenId, int currentTime) {
Integer ttE = tokenExpiryTime.get(tokenId);
if (ttE != null) {
if (ttE > currentTime) {
tokenExpiryTime.put(tokenId, currentTime+ttL);
} else {
tokenExpiryTime.remove(tokenId);
}
}
}
public int countUnexpiredTokens(int currentTime) {
return (int) tokenExpiryTime.keySet().stream()
.filter(t -> tokenExpiryTime.get(t) > currentTime)
.count();
}
}
/**
* 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);
*/
``` | 0 | 0 | ['Java'] | 0 |
design-authentication-manager | Design of Authentication Manager || CPP | design-of-authentication-manager-cpp-by-878si | Complexity
Time complexity:
O(1) for all the methods of AuthenticationManager
Space complexity:
O(1)
Code | ShashidharAngadi | NORMAL | 2025-04-03T19:23:42.257851+00:00 | 2025-04-03T19:23:42.257851+00:00 | 3 | false | # Complexity
- Time complexity:
O(1) for all the methods of AuthenticationManager
- Space complexity:
O(1)
# Code
```cpp []
class AuthenticationManager {
private:
int timeToLive;
unordered_map<string,pair<int,int>> tokenTime;
public:
AuthenticationManager(int timeToLive) {
this->timeToLive = timeToLive;
}
void generate(string tokenId, int currentTime) {
tokenTime[tokenId] = {currentTime,currentTime+this->timeToLive};
}
void renew(string tokenId, int currentTime) {
auto it = tokenTime.find(tokenId);
if(it!=tokenTime.end()){
pair<int,int> duration = this->tokenTime[tokenId];
if(currentTime>=duration.first && currentTime<duration.second){
duration.second = currentTime+this->timeToLive;
this->tokenTime[tokenId] = duration;
}
}
}
int countUnexpiredTokens(int currentTime) {
int count = 0;
for(auto p: this->tokenTime){
pair<int,int> duration = p.second;
if(currentTime>=duration.first && currentTime<duration.second){
count++;
}
}
return count;
}
};
/**
* 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);
*/
``` | 0 | 0 | ['C++'] | 0 |
design-authentication-manager | Simple Python Solution - Dictionary and Queue | simple-python-solution-dictionary-and-qu-7i7r | null | kschinella | NORMAL | 2025-03-29T11:13:34.871009+00:00 | 2025-03-29T11:13:34.871009+00:00 | 2 | false | ```python []
class AuthenticationManager(object):
def __init__(self, timeToLive):
"""
:type timeToLive: int
"""
self.timeToLive = timeToLive
self.tokens = deque()
self.tokensMap = {}
def generate(self, tokenId, currentTime):
"""
:type tokenId: str
:type currentTime: int
:rtype: None
"""
self.tokensMap[tokenId] = currentTime
self.tokens.append((tokenId, currentTime))
def renew(self, tokenId, currentTime):
"""
:type tokenId: str
:type currentTime: int
:rtype: None
"""
if tokenId in self.tokensMap:
if currentTime - self.tokensMap[tokenId] < self.timeToLive:
self.tokensMap[tokenId] = currentTime
self.tokens.append((tokenId, currentTime))
def countUnexpiredTokens(self, currentTime):
"""
:type currentTime: int
:rtype: int
"""
while self.tokens and (currentTime - self.tokens[0][1]) >= self.timeToLive:
expiredToken, _ = self.tokens.popleft()
if expiredToken in self.tokensMap and (currentTime - self.tokensMap[expiredToken]) >= self.timeToLive:
del self.tokensMap[expiredToken]
return len(self.tokensMap)
# Your AuthenticationManager object will be instantiated and called as such:
# obj = AuthenticationManager(timeToLive)
# obj.generate(tokenId,currentTime)
# obj.renew(tokenId,currentTime)
# param_3 = obj.countUnexpiredTokens(currentTime)
``` | 0 | 0 | ['Python'] | 0 |
design-authentication-manager | Python solution O(n) | python-solution-on-by-kavya_171998-aisx | IntuitionFollow the question line by lineComplexity
Time complexity: O(n)
Space complexity: O(n)
Code | kavya_171998 | NORMAL | 2025-03-23T13:17:21.938748+00:00 | 2025-03-23T13:17:21.938748+00:00 | 4 | false | # Intuition
<!-- Describe your first thoughts on how to solve this problem. -->
Follow the question line by line
# Complexity
- Time complexity: O(n)
<!-- Add your time complexity here, e.g. $$O(n)$$ -->
- Space complexity: O(n)
<!-- Add your space complexity here, e.g. $$O(n)$$ -->
# Code
```python3 []
class AuthenticationManager:
def __init__(self, timeToLive: int):
self.ttl = timeToLive
self.tokenMap = {}
def generate(self, tokenId: str, currentTime: int) -> None:
self.tokenMap[tokenId] = currentTime+self.ttl
def renew(self, tokenId: str, currentTime: int) -> None:
if tokenId in self.tokenMap and self.tokenMap[tokenId]>currentTime:
self.tokenMap[tokenId] = currentTime+self.ttl
def countUnexpiredTokens(self, currentTime: int) -> int:
count = 0
for token, time in self.tokenMap.items():
if time>currentTime:
count+=1
return count
# Your AuthenticationManager object will be instantiated and called as such:
# obj = AuthenticationManager(timeToLive)
# obj.generate(tokenId,currentTime)
# obj.renew(tokenId,currentTime)
# param_3 = obj.countUnexpiredTokens(currentTime)
``` | 0 | 0 | ['Python3'] | 0 |
design-authentication-manager | My Java solution using HashMap | my-java-solution-using-hashmap-by-pooja2-hg19 | IntuitionCould n't understand why is this listed in Linkedlist
The first thought that came up is to use a map to store token id and expiration time of each toke | pooja2345 | NORMAL | 2025-03-21T12:13:06.197557+00:00 | 2025-03-21T12:15:23.466535+00:00 | 6 | false | # Intuition
Could n't understand why is this listed in Linkedlist
The first thought that came up is to use a map to store token id and expiration time of each token
** do not forget to check its expiration time before renewing the token **
# Approach
1. Use a hashmap
2. store its tokenId as key & expiration time as value
3. while asked to calculate number of unexpired tokens
given that the expiration preceeds everything other operation
check for expiration time to be more than currentTime.
# Complexity
to iterate each key in the map, where n is the number of token present at time t
to store each key in the map, where n is the number of tokens present at time t
- Time complexity:
O(n)
- Space complexity:
O(n)
# Code
```java []
class AuthenticationManager {
int timeToLive;
HashMap<String,Integer> hm;
public AuthenticationManager(int timeToLive) {
hm=new HashMap<>();
this.timeToLive=timeToLive;
}
public void generate(String tokenId, int currentTime) {
hm.put(tokenId,currentTime+timeToLive);
}
public void renew(String tokenId, int currentTime) {
if(hm.containsKey(tokenId)&&hm.get(tokenId)>currentTime)
hm.put(tokenId,currentTime+timeToLive);
}
public int countUnexpiredTokens(int currentTime) {
int cnt=0;
for(String i:hm.keySet()){
if(hm.get(i)>currentTime)
cnt++;
}
return cnt;
}
}
/**
* 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);
*/
``` | 0 | 0 | ['Java'] | 0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.