Check whether string of braces, brackets, and parentheses is balanced The 2019 Stack Overflow Developer Survey Results Are InBalanced parenthesesCheck for balanced parenthesesBalance braces methodChecking for balanced parenthesesBalanced bracesSwift HackerRank Balanced BracketsCheck for balanced parentheses in JavaScriptCheck balanced brackets in a textCheck if brackets are balancedLeetcode: Valid parentheses
APIPA and LAN Broadcast Domain
Is it okay to consider publishing in my first year of PhD?
Slides for 30 min~1 hr Skype tenure track application interview
Falsification in Math vs Science
How can I define good in a religion that claims no moral authority?
Straighten subgroup lattice
Output the Arecibo Message
Cooking pasta in a water boiler
If I can cast sorceries at instant speed, can I use sorcery-speed activated abilities at instant speed?
What is the motivation for a law requiring 2 parties to consent for recording a conversation
Merge two greps into single one
How do I free up internal storage if I don't have any apps downloaded?
Why doesn't UInt have a toDouble()?
How to display lines in a file like ls displays files in a directory?
How to type a long/em dash `—`
Why does the nucleus not repel itself?
Dropping list elements from nested list after evaluation
Is it possible for absolutely everyone to attain enlightenment?
Why isn't the circumferential light around the M87 black hole's event horizon symmetric?
Is it safe to harvest rainwater that fell on solar panels?
Star Trek - X-shaped Item on Regula/Orbital Office Starbases
Flight paths in orbit around Ceres?
What is the most efficient way to store a numeric range?
What is the meaning of Triage in Cybersec world?
Check whether string of braces, brackets, and parentheses is balanced
The 2019 Stack Overflow Developer Survey Results Are InBalanced parenthesesCheck for balanced parenthesesBalance braces methodChecking for balanced parenthesesBalanced bracesSwift HackerRank Balanced BracketsCheck for balanced parentheses in JavaScriptCheck balanced brackets in a textCheck if brackets are balancedLeetcode: Valid parentheses
.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;
$begingroup$
The Task
is taken from codewars:
Write a function that takes a string of braces, and determines if the
order of the braces is valid. It should returntrueif the string is
valid, andfalseif it's invalid.
All input strings will be nonempty, and will only consist of
parentheses, brackets and curly braces:()[].
What is considered Valid? A string of braces is considered valid if
all braces are matched with the correct brace.
Examples
()[]=>True
([])=>True
(}=>False
[(])=>False
[()](]=>False
My solution
const areBracesBalanced = brc => {
const brace = Object.freeze({
"(": [],
"[": [],
"": [],
);
const removeBrace = b => brace[b].splice(-1, 1);
const getLastBraceIndex = b => brace[b][brace[b].length - 1]
const braceExists = b => !brace[b].length;
const isBraceBeforeClosed = (before, current) => braceExists(before) || getLastBraceIndex(before) < getLastBraceIndex(current);
const braceIsBalanced = (b, i) => {
switch (b) {
case "(":
case "[":
case "{":
return brace[b].push(i);
case ")":
return isBraceBeforeClosed("[", "(") &&
isBraceBeforeClosed("
$begingroup$
The Task
is taken from codewars:
Write a function that takes a string of braces, and determines if the
order of the braces is valid. It should returntrueif the string is
valid, andfalseif it's invalid.
All input strings will be nonempty, and will only consist of
parentheses, brackets and curly braces:()[].
What is considered Valid? A string of braces is considered valid if
all braces are matched with the correct brace.
Examples
()[]=>True
([])=>True
(=>False
[(])=>False
[()](]=>False
My solution
const areBracesBalanced = brc => {
const brace = Object.freeze({
"(": [],
"[": [],
"": [],
);
const removeBrace = b => brace[b].splice(-1, 1);
const getLastBraceIndex = b => brace[b][brace[b].length - 1]
const braceExists = b => !brace[b].length;
const isBraceBeforeClosed = (before, current) => braceExists(before) || getLastBraceIndex(before) < getLastBraceIndex(current);
const braceIsBalanced = (b, i) => {
switch (b) {
case "(":
case "[":
case "improve this answer
$endgroup$
I'm not very good at Javascript, but I do know how to make an algorithm.
In the code below I use the fact that correct or [] or () will always touch and can be removed. Just taken these away until there aren't any left and if you've got an empty string it was balanced, if it is not empty then clearly it must be unbalanced.
function isBalanced(input)
while (input.length > 0)
var output = input.replace("", "").replace("[]", "").replace("()", "");
if (input == output) return false;
input = output;
return true;
function test(input)
alert("'"+input+"' = "+(isBalanced(input) ? "Correct" : "Incorrect"));
test("()[]");
test("([])");
test("(");
test("[(])");
test("[()](]");
test("()[]");
Someone with a bit more knowledge of Javascript might be able to further optimize this code.
To make it slightly more efficient there's a version with a regular expression:
function isBalanced(input)
while (input.length > 0) []/, "");
if (input == output) return false;
input = output;
return true;
I think this short code is elegant, but here it is somewhat at the expense of clarity.
edited 58 mins ago
answered 3 hours ago
KIKO SoftwareKIKO Software
1,722512
1,722512
add a comment |
$begingroup$
I don't see why your suggested algorithm is better than the original code, and you haven't told us why. Repeated string replacement is a poor strategy for performance.
$endgroup$
– 200_success
3 hours ago
$begingroup$
@200_success I'm sorry, I didn't know I had to explain that, and as I pointed out, I am not a Javascript expert.
$endgroup$
– KIKO Software
3 hours ago
$begingroup$
@200_success I saw it as a coding challenge, I'm sorry. Still think that it is a clear and, above all, comprehensible answer.
$endgroup$
– KIKO Software
3 hours ago
$begingroup$
I don't see why your suggested algorithm is better than the original code, and you haven't told us why. Repeated string replacement is a poor strategy for performance.
$endgroup$
– 200_success
3 hours ago
$begingroup$
I don't see why your suggested algorithm is better than the original code, and you haven't told us why. Repeated string replacement is a poor strategy for performance.
$endgroup$
– 200_success
3 hours ago
$begingroup$
@200_success I'm sorry, I didn't know I had to explain that, and as I pointed out, I am not a Javascript expert.
$endgroup$
– KIKO Software
3 hours ago
$begingroup$
@200_success I'm sorry, I didn't know I had to explain that, and as I pointed out, I am not a Javascript expert.
$endgroup$
– KIKO Software
3 hours ago
$begingroup$
@200_success I saw it as a coding challenge, I'm sorry. Still think that it is a clear and, above all, comprehensible answer.
$endgroup$
– KIKO Software
3 hours ago
$begingroup$
@200_success I saw it as a coding challenge, I'm sorry. Still think that it is a clear and, above all, comprehensible answer.
$endgroup$
– KIKO Software
3 hours ago
add a comment |
Thanks for contributing an answer to Code Review Stack Exchange!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
Use MathJax to format equations. MathJax reference.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f217275%2fcheck-whether-string-of-braces-brackets-and-parentheses-is-balanced%23new-answer', 'question_page');
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
var $window = $(window),
onScroll = function(e)
var $elem = $('.new-login-left'),
docViewTop = $window.scrollTop(),
docViewBottom = docViewTop + $window.height(),
elemTop = $elem.offset().top,
elemBottom = elemTop + $elem.height();
if ((docViewTop elemBottom))
StackExchange.using('gps', function() StackExchange.gps.track('embedded_signup_form.view', location: 'question_page' ); );
$window.unbind('scroll', onScroll);
;
$window.on('scroll', onScroll);
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
$begingroup$
I don't see why your suggested algorithm is better than the original code, and you haven't told us why. Repeated string replacement is a poor strategy for performance.
$endgroup$
– 200_success
3 hours ago
$begingroup$
@200_success I'm sorry, I didn't know I had to explain that, and as I pointed out, I am not a Javascript expert.
$endgroup$
– KIKO Software
3 hours ago
$begingroup$
@200_success I saw it as a coding challenge, I'm sorry. Still think that it is a clear and, above all, comprehensible answer.
$endgroup$
– KIKO Software
3 hours ago