Chat app~25 min2s · 256 MBtarget O(n) time, O(n) spacehashing
A chat app keeps every active session token in a hash table. The table starts with 8 buckets. When a new token makes the table too full, the table doubles in size, and every stored token is moved to a bucket of the new table.
The rule is exact. After a new token is stored, if the number of stored tokens is more than three quarters of the buckets, the table doubles. A token that is already stored only refreshes the session, and nothing grows.
Write growth_cost(tokens).
tokens[i] is the session token of the i-th login. Tokens are large numbers, and the same token can log in again.4 × stored > 3 × buckets, double the table. Every stored token, including the new one, moves once.[resizes, moves, buckets]: how many times the table doubled, how many token moves happened in all, and the final number of buckets.Input: tokens = [5, 12, 5, 33, 41, 17, 9, 23, 41, 8, 60, 71, 2, 19, 88, 33]
Output: [2, 20, 32]The table doubles when a new token pushes the stored count past three quarters of the buckets. The table below shows the new tokens that matter.
| New token | Stored after | Buckets | 4 × stored | 3 × buckets | Action |
|---|---|---|---|---|---|
| 5 (first) | 1 | 8 | 4 | 24 | nothing |
| 5 (again) | 1 | 8 | already stored: nothing | ||
| 9 | 6 | 8 | 24 | 24 | 24 is not more than 24: nothing |
| 23 | 7 | 8 | 28 | 24 | double to 16, and move 7 tokens |
| 19 | 12 | 16 | 48 | 48 | 48 is not more than 48: nothing |
| 88 | 13 | 16 | 52 | 48 | double to 32, and move 13 tokens |
| 33 (again) | 13 | 32 | already stored: nothing |
There are 13 distinct tokens. The table doubled twice, moved 7 + 13 = 20 tokens, and ends with 32 buckets.
Input: tokens = [1, 1, 1]
Output: [0, 0, 8]Only one token is stored, so the table never doubles.
Input: tokens = [1, 2, 3, 4, 5, 6, 7]
Output: [1, 7, 16]The seventh distinct token makes 28 more than 24, so the table doubles once and moves 7 tokens.
1 ≤ tokens.length ≤ 100,000 (logins in one batch)1 ≤ tokens[i] ≤ 10^12 (session tokens)Checking each new token against all stored tokens costs about n × n / 2 comparisons. At n = 100,000 that is about 5 × 10^9: far over the budget of about 10^8 simple operations a second. A hash set checks a token in one step on average.
Read the values too. A token reaches 10^12, which does not fit in a 32-bit integer, so store tokens as long in Java and long long in C++. The counts stay small: resizes, moves and buckets all fit in an int.