Last active
January 28, 2024 06:35
-
-
Save godswillumukoro/254f39d3a4d01be590dea7a093e53b4e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!DOCTYPE html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<meta name="viewport" content="width=device-width, initial-scale=1.0"> | |
<title>My Solution</title> | |
</head> | |
<body> | |
<h1>Algorithm Challenge</h1> | |
<p>Make pairs of bracket supplied to the function. Ensure that all brackets are correctly closed.</p> | |
<h2>My Solution</h2> | |
<p>My algorithm pushes a “[“ to the output array whenever its encountered. | |
However, for every “]”, the algorithm checks for two conditions: | |
<ol> | |
<li>Is the output array empty?</li> | |
<li>Hey, I just popped the previous element, was it a “]” | |
If the to either question is “true”, then return false</li> | |
</ol> | |
Lastly, after the end of the loop, return true if the length of the output array is 0 | |
Then i realized that the output array is literally a stack data structure at play. | |
</p> | |
</body> | |
<script> | |
function checkBrackets(input) { | |
let output=[] | |
for (let i=0; i < input.length; i++) { | |
if( input[i] === "[") { | |
output.push(input[i]) | |
} else if(input[i] === "]") { | |
if(output.length === 0 || output.pop() == "]") { | |
return false | |
} | |
} | |
} | |
return output.length === 0 | |
} | |
if(checkBrackets("[[][[][]]]")) { | |
console.log("Every opening bracket is correctly closed") | |
} else { | |
console.log("Brackets are not closed correctly") | |
} | |
</script> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment