"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: Flip one bit from 0 to 1 to maximize the longest sequence of 1s.\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",
"* Is the input an int, base 2?\n",
" * Yes\n",
"* Can we assume the input is a 32 bit number?\n",
" * Yes\n",
"* Do we have to validate the length of the input?\n",
" * No\n",
"* Is the output an int?\n",
" * Yes\n",
"* Can we assume the inputs are valid?\n",
" * No\n",
"* Can we assume we are using a positive number since Python doesn't have an >>> operator?\n",
" * This will be 0 length if the input has trailing ones\n",
" * Add sequence length to seen\n",
" * Look for 1's\n",
" * Add sequence length to seen\n",
"* Find the largest sequence of ones looking at seen\n",
" * Loop through seen\n",
" * On each iteration of the loop, flip what we are looking for from 0 to 1 and vice versa\n",
" * If seen[i] represents 1's, continue, we only want to process 0's\n",
" * If this is our first iteration:\n",
" * max_result = seen[i+1] + 1 if seen[i] > 0\n",
" * continue\n",
" * If we are looking at leading zeroes (i == len(seen)-1):\n",
" * result = seen[i-1] + 1\n",
" * If we are looking at one zero:\n",
" * result = seen[i+1] + seen[i-1] + 1\n",
" * If we are looking at multiple zeroes:\n",
" * result = max(seen[i+1], seen[i-1]) + 1\n",
" * Update max_result based on result\n",
"\n",
"We should make a note that Python does not have a logical right shift operator built in. We can either use a positive number or implement one for a 32 bit number:\n",