diff --git a/strings/parenthesis.ipynb b/strings/parenthesis.ipynb index 497f145..5c1214e 100644 --- a/strings/parenthesis.ipynb +++ b/strings/parenthesis.ipynb @@ -11,9 +11,18 @@ "For example, given the string \"()())()\", you should return 1. Given the string \")(\", you should return 2, since we must remove all of them." ] }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "### Approach\n", + "For each opening parenthesis to be considered valid, they should eventually be matched with an closing parenthesis. If not, they are counted as invalid.\n", + "Whenever we encounter an unmatched closing parenthesis, we count as invalid. Eventually, we'll add the unmatched open count to the invalid one." + ] + }, { "cell_type": "code", - "execution_count": 26, + "execution_count": 32, "metadata": {}, "outputs": [], "source": [ @@ -21,10 +30,10 @@ " invalid = 0\n", " opened = 0\n", " \n", - " for parenthesis in string:\n", - " if parenthesis == \"(\":\n", + " for char in string:\n", + " if char == \"(\":\n", " opened += 1\n", - " elif parenthesis == \")\":\n", + " elif char == \")\":\n", " if opened > 0:\n", " opened -= 1\n", " else:\n", @@ -34,7 +43,7 @@ }, { "cell_type": "code", - "execution_count": 28, + "execution_count": 33, "metadata": {}, "outputs": [ { @@ -43,7 +52,7 @@ "2" ] }, - "execution_count": 28, + "execution_count": 33, "metadata": {}, "output_type": "execute_result" } @@ -52,6 +61,33 @@ "count_invalid_parenthesis(\"((()(())\")" ] }, + { + "cell_type": "code", + "execution_count": 34, + "metadata": {}, + "outputs": [ + { + "data": { + "text/plain": [ + "0" + ] + }, + "execution_count": 34, + "metadata": {}, + "output_type": "execute_result" + } + ], + "source": [ + "count_invalid_parenthesis(\"()()()\")" + ] + }, + { + "cell_type": "markdown", + "metadata": {}, + "source": [ + "This solution runs at O(N) time, where N = number of characters in the string." + ] + }, { "cell_type": "code", "execution_count": null,