{ "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "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: Find the longest increasing subsequence.\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", "* Are duplicates possible?\n", " * Yes\n", "* Can we assume the inputs are integers?\n", " * Yes\n", "* Can we assume the inputs are valid?\n", " * No\n", "* Do we expect the result to be an array of the longest increasing subsequence?\n", " * Yes\n", "* Can we assume this fits memory?\n", " * Yes" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Test Cases\n", "\n", "* None -> Exception\n", "* [] -> []\n", "* [3, 4, -1, 0, 6, 2, 3] -> [-1, 0, 2, 3]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Algorithm\n", "\n", "We'll use bottom up dynamic programming to build a table.\n", "\n", "
\n",
    "Init a temp array of size len(input) to 1.  \n",
    "We'll use l and r to iterate through the input.\n",
    "Array prev will hold the index of the prior smaller value, used to reconstruct the final sequence.\n",
    "\n",
    "if input[l] < input[r]:\n",
    "    if temp[r] < temp[l] + 1:\n",
    "        temp[r] = temp[l] + 1\n",
    "        prev[r] = l\n",
    "\n",
    "        l  r\n",
    "index:  0  1  2  3  4  5  6\n",
    "---------------------------\n",
    "input:  3  4 -1  0  6  2  3\n",
    "temp:   1  2  1  1  1  1  1\n",
    "prev:   x  x  x  x  x  x  x\n",
    "\n",
    "End result:\n",
    "\n",
    "index:  0  1  2  3  4  5  6\n",
    "---------------------------\n",
    "input:  3  4 -1  0  6  2  3\n",
    "temp:   1  2  1  2  3  3  4\n",
    "prev:   x  0  x  2  1  3  5\n",
    "
\n", "\n", "Complexity:\n", "* Time: O(n^2)\n", "* Space: O(n)" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Code" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "class Subsequence(object):\n", "\n", " def longest_inc_subseq(self, seq):\n", " if seq is None:\n", " raise TypeError('seq cannot be None')\n", " if not seq:\n", " return []\n", " temp = [1] * len(seq)\n", " prev = [None] * len(seq)\n", " for r in range(1, len(seq)):\n", " for l in range(r):\n", " if seq[l] < seq[r]:\n", " if temp[r] < temp[l] + 1:\n", " temp[r] = temp[l] + 1\n", " prev[r] = l\n", " max_val = 0\n", " max_index = -1\n", " results = []\n", " for index, value in enumerate(temp):\n", " if value > max_val:\n", " max_val = value\n", " max_index = index\n", " curr_index = max_index\n", " while curr_index is not None:\n", " results.append(seq[curr_index])\n", " curr_index = prev[curr_index]\n", " return results[::-1]" ] }, { "cell_type": "markdown", "metadata": {}, "source": [ "## Unit Test" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Overwriting test_longest_increasing_subseq.py\n" ] } ], "source": [ "%%writefile test_longest_increasing_subseq.py\n", "import unittest\n", "\n", "\n", "class TestLongestIncreasingSubseq(unittest.TestCase):\n", "\n", " def test_longest_increasing_subseq(self):\n", " subseq = Subsequence()\n", " self.assertRaises(TypeError, subseq.longest_inc_subseq, None)\n", " self.assertEqual(subseq.longest_inc_subseq([]), [])\n", " seq = [3, 4, -1, 0, 6, 2, 3]\n", " expected = [-1, 0, 2, 3]\n", " self.assertEqual(subseq.longest_inc_subseq(seq), expected)\n", " print('Success: test_longest_increasing_subseq')\n", "\n", "\n", "def main():\n", " test = TestLongestIncreasingSubseq()\n", " test.test_longest_increasing_subseq()\n", "\n", "\n", "if __name__ == '__main__':\n", " main()" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Success: test_longest_increasing_subseq\n" ] } ], "source": [ "%run -i test_longest_increasing_subseq.py" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "codemirror_mode": { "name": "ipython", "version": 3 }, "file_extension": ".py", "mimetype": "text/x-python", "name": "python", "nbconvert_exporter": "python", "pygments_lexer": "ipython3", "version": "3.7.2" } }, "nbformat": 4, "nbformat_minor": 1 }