"This notebook was prepared by [Donne Martin](https://github.com/donnemartin). Source and license info is on [GitHub](https://github.com/donnemartin/interactive-coding-challenges)."
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"# Solution Notebook"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Problem: Create a class with an insert method to insert an int to a list. It should also support calculating the max, min, mean, and mode in O(1).\n",
"\n",
"* [Constraints](#Constraints)\n",
"* [Test Cases](#Test-Cases)\n",
"* [Algorithm](#Algorithm)\n",
"* [Code](#Code)\n",
"* [Unit Test](#Unit-Test)"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Constraints\n",
"\n",
"* Can we assume the inputs are valid?\n",
" * No\n",
"* Is there a range of inputs?\n",
" * 0 <= item <= 100\n",
"* Should mean return a float?\n",
" * Yes\n",
"* Should the other results return an int?\n",
" * Yes\n",
"* If there are multiple modes, what do we return?\n",
" * Any of the modes\n",
"* Can we assume this fits memory?\n",
" * Yes"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Test Cases\n",
"\n",
"* None -> TypeError\n",
"* [] -> ValueError\n",
"* [5, 2, 7, 9, 9, 2, 9, 4, 3, 3, 2]\n",
" * max: 9\n",
" * min: 2\n",
" * mean: 55\n",
" * mode: 9 or 2"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Algorithm\n",
"\n",
"* We'll init our max and min to None. Alternatively, we can init them to -sys.maxsize and sys.maxsize, respectively.\n",
"* For mean, we'll keep track of the number of items we have inserted so far, as well as the running sum.\n",
"* For mode, we'll keep track of the current mode and an array with the size of the given upper limit\n",
" * Each element in the array will be init to 0\n",
" * Each time we insert, we'll increment the element corresponding to the inserted item's value\n",
"* On each insert:\n",
" * Update the max and min\n",
" * Update the mean by calculating running_sum / num_items\n",
" * Update the mode by comparing the mode array's value with the current mode\n",
"\n",
"Complexity:\n",
"* Time: O(1)\n",
"* Space: O(1), we are treating the 101 element array as a constant O(1), we could also see this as O(k)"