"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: Given an array of (unix_timestamp, num_people, EventType.ENTER or EventType.EXIT), find the busiest period.\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 input array is valid?\n",
" * Check for None\n",
"* Can we assume the elements of the input array are valid?\n",
" * Yes\n",
"* Is the input sorted by time?\n",
" * No\n",
"* Can you have enter and exit elements for the same timestamp?\n",
" * Yes you can, order of enter and exit is not guaranteed\n",
"* Could we have multiple enter events (or multiple exit events) for the same timestamp?\n",
" * No\n",
"* What is the format of the output?\n",
" * An array of timestamps [t1, t2]\n",
"* Can we assume the starting number of people is zero?\n",
" * Yes\n",
"* Can we assume the inputs are valid?\n",
" * No\n",
"* Can we assume this fits memory?\n",
" * Yes"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Test Cases\n",
"\n",
"* None -> TypeError\n",
"* [] -> None\n",
"* General case\n",
"\n",
"<pre>\n",
"timestamp num_people event_type\n",
"3 2 EventType.EXIT\n",
"1 2 EventType.ENTER\n",
"3 1 EventType.ENTER\n",
"7 3 EventType.ENTER\n",
"9 2 EventType.EXIT\n",
"8 2 EventType.EXIT\n",
"\n",
"result = Period(7, 8)\n",
"</pre>"
]
},
{
"cell_type":"markdown",
"metadata":{},
"source":[
"## Algorithm\n",
"\n",
"Since the input is not sorted, we'll need to sort it first by timestamp, ascending.\n",
"\n",
"For each interval in the data set:\n",
"\n",
"* If this is an \"enter\" event, increment `curr_people`, else, decrement\n",
"* Since we can have an \"enter\" and \"exit\" event for the same timestamp, we'll need to look ahead one\n",
" * If the next element has the same timestamp, hold off (continue) on updating `max_people` and `max_period`\n",
" * Watch out for indexing out-of-bounds at the end of the array\n",