Skip to content

Commit

Permalink
refactor solution, add approach explanation and time complexity
Browse files Browse the repository at this point in the history
  • Loading branch information
gitgik committed Jan 12, 2021
1 parent 15c5979 commit 6d15255
Showing 1 changed file with 42 additions and 6 deletions.
48 changes: 42 additions & 6 deletions strings/parenthesis.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,29 @@
"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": [
"def count_invalid_parenthesis(string) -> int:\n",
" 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",
Expand All @@ -34,7 +43,7 @@
},
{
"cell_type": "code",
"execution_count": 28,
"execution_count": 33,
"metadata": {},
"outputs": [
{
Expand All @@ -43,7 +52,7 @@
"2"
]
},
"execution_count": 28,
"execution_count": 33,
"metadata": {},
"output_type": "execute_result"
}
Expand All @@ -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,
Expand Down

0 comments on commit 6d15255

Please sign in to comment.