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
How do you keep chess fun when your opponent constantly defeats?
How do PCB vias affect signal quality?
Geography at the pixel level
Can a flute soloist sit?
Correct punctuation for showing a character's confusion
What to do when moving next to a bird sanctuary with a loosely-domesticated cat?
Button changing its text & action. Good or terrible?
What is the light source in the black hole images?
Worn-tile Scrabble
Keeping a retro style to sci-fi spaceships?
Deal with toxic manager when you can't quit
Old scifi movie from the 50s or 60s with men in solid red uniforms who interrogate a spy from the past
Can withdrawing asylum be illegal?
What is this business jet?
How to translate "being like"?
Did any laptop computers have a built-in 5 1/4 inch floppy drive?
Straighten subgroup lattice
"as much details as you can remember"
If a sorcerer casts the Banishment spell on a PC while in Avernus, does the PC return to their home plane?
Why didn't the Event Horizon Telescope team mention Sagittarius A*?
Is it correct to say the Neural Networks are an alternative way of performing Maximum Likelihood Estimation? if not, why?
What is this sharp, curved notch on my knife for?
How do I free up internal storage if I don't have any apps downloaded?
Flight paths in orbit around Ceres?
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("improve this question
$endgroup$
add a comment =>
False[(]) => False[()](] => FalseMy 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 39 mins ago
answered 3 hours ago
KIKO SoftwareKIKO Software
1,722512
1,722512
$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$
Well, if you don't say anything about the original code, then it's not a code review, and hence not a valid answer.
$endgroup$
– 200_success
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 |
$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$
Well, if you don't say anything about the original code, then it's not a code review, and hence not a valid answer.
$endgroup$
– 200_success
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$
Well, if you don't say anything about the original code, then it's not a code review, and hence not a valid answer.
$endgroup$
– 200_success
3 hours ago
$begingroup$
Well, if you don't say anything about the original code, then it's not a code review, and hence not a valid answer.
$endgroup$
– 200_success
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