Use a stack. While iterating through the characters, do the following: - for an opening brace, push it onto the stack - for a closing brace, immediately return false if the stack is empty or the character at the top is not the matching opening brace; otherwise remive the character at the top of the stack Post iteration, return true on whether the stack is empty.
This and this problem is legit high school introductory to CS tier difficulty >here's your 300k starting salary to work at a college campus for 3 hours a day unreal
Nicholas Harris
That's not an improvement unless they said fastest execution time. You get bonus points for simplicity/elegance in your solution.
Brayden James
#!/usr/bin/env python3
import sys
pairs = {'(':')', '[':']', '{':'}'} def ops_homework(s): while len(s) > 0 and s[0] in pairs: p = pairs[s[0]]
def isWellFormed(bracketString): """ Given a string of round, curly, and square open and closing brackets, return whether the brackets are balanced (well-formed). """ stack = [] for el in bracketString: # do brackets open? if el in BRACKETS: stack.append(BRACKETS[el]) # do the matching brackets close? elif (not stack) or stack.pop() != el: return 0 return len(stack) == 0
if __name__ == "__main__": # read in the expression and strip whitespaces bracketString = sys.stdin.read().strip() print(isWellFormed(bracketString))
Daniel Price
>This problem was asked by Facebook. Stopped reading.
Nathan Allen
it's not my home work. It's actual code challenges I've been taking. I'll try to post whenever I can. I'll post the challenge and later I come back and post my solution.
Jaxson Carter
-module(balanced).
-define(is_opening(C), C =:= 40 orelse C =:= 91 orelse C =:= 123).
i would just like to point out that any balanced string must have a "{}", "[]" or "()" substring somewhere in it so recursively remove the above substrings until you have nothing left (return true) or there are no such substrings left to remove (return false)
Joshua Price
but that's an O(whatever the fuck n) operation because you're going through the string however many times depending on how long it is
don't call us, we'll call you
Angel Diaz
Ez Pz Have a counter Iterate through the string by characters Increase counter when '{' is encountered Decrease the counter when '}' is encountered If the counter is not 0 at the end, it's malformed. If the counter goes below 0 at any time, then it's malformed.
Eli Jones
read the instructions. it's three different kinds of brackets. counters are not enough here.
James Roberts
don't you need 3 counters? one for each type?
"([)]" should return false. yours return true
Anthony Foster
upgrade your PC bro
Tyler Fisher
It's the same problem but for whatever you want to count. Have separate counter for each kind of bracket. Yes, you would need a separate counter for each. There might be a way to do it via one counter, but this is the simplest naive solution which seems ok by me.
Levi Bailey
Stack definitely makes the most sense here
Landon Diaz
"([)]" should return false. yours return true
Dylan Ortiz
don't call us... ([)]
Ayden Roberts
>Use a stack
Stack overflow
Jayden Diaz
Ah, couldn't read it properly from the Jow Forums formatting. Code tags actually made it legible. Yeah, it would break in that case.
Lincoln Wood
Stack is simpler than counters only acceptable solution ITT
Zachary Roberts
You make counters that increase for each opening and decrease for each closing One for (), one for [] and one for {} Then you move from the beginning of the string to the end and increment or decrement the counters If the string has an odd number of chars at the start, you by default return false If any of your counters is not 0 you return false Otherwise true
Brody Anderson
...
Josiah Thomas
what compels you to write such hard to read code?
Gavin Carter
I think you can still keep using counters but somehow you have to keep track of what was counted beforehand and where it does go below the beforehand counter.
while !s.is_empty() { for (num, c) in s.clone().iter().enumerate() { let scpy = s.clone(); let next_c = scpy.get(&num+1);
if next_c.is_none() { return false // EOL }
let next_c = next_c.unwrap().to_string();
match c { '{' => { if next_c.contains('}') { s.drain(num..num+2); break } } '(' => { if next_c.contains(')') { s.drain(num..num+2); break } } '[' => { if next_c.contains(']') { s.drain(num..num+2); break } } _ => (), } } }
true }
bit ugly but can't be bothered to make it more pretty
Carson Scott
As it should, dumb ass
Charles Clark
Hey Jow Forums I legit got this question in an interview and they gave me 15 minutes to write out code on a whiteboard to solve if it's balanced. They had the starting strings:
I hit the time limit and the IT lead said they didn't need someone who couldn't find a O(1) solution to the problem. Nor do they need liars as I said I was an expert in C# and somehow thought "string reversed = s.Reverse();" was compilable code, they had been typing along in Visual Studio and it clearly wasn't.
I've been beating myself up because now I've been unemployed for 2 months since the last company I worked for went out of business, and now I'm really starting to feel the pain. So Jow Forums, I know that the answers were wrong, but do I really deserve to be unable to find even minimum wage programming work? I'd kill to get a programming job at this rate, but do I even deserve minimum wage if I'm this much of a failure?
The easiest solution is usually the least verbose and most correct one: fn balanced(string): for char in string: if (char in []): balance += 1 if (char in []): balance -= 1 balance == 0 ? true : false
Note: This is partly pseudocode, i don't remember how to tokenize a string.
Kayden Collins
How can it be a O(1) problem? If anything it would be O(n) where n is the number of characters in the string.
Angel Sullivan
>O(1) solution not possible >dumb mistake in C# while under stress >"do i even deserve minimum wage if i'm this much of a failure" come the fuck on mate it's not that bad, your life isn't over because you fucked an interview
Jason Phillips
This would return true for "([)]"
Bentley White
Basically the stack method would be your best bet.
Have a stack meant for characters or pairs of brackets(orwhateveryoucallit) Iterate through the string character by character Push onto the stack when you encounter opening characters Every time you come across a closing character, pop the stack, if the popped element doesn't match its corresponding closing character, then return false If the stack size is not 0 by the end, return false Return true
Andrew Russell
Or you can the stack meant for closing characters only where you compare the popped character against the closing character you came across. And when you come across opening characters, you push its corresponding closing character onto the stack.
Angel Flores
By the sound of that I would say the guy that interviewed you is a fucking psycopath
Matthew Wood
user there are lots of "seniors" and "leads" that don't deserve the title, don't beat yourself up and just keep trying
Noah Brooks
bool testBalancedBrackets(char* str){ int bracketsNormal = 1; int bracketsSquare = 1; int bracketsCurvy = 1; do{ switch(*str){ case '(' : ++bracketsNormal; break; case ')' : --bracketsNormal; break; case '[' : ++bracketsSquare; break; case ']' : --bracketsSquare; break; case '{' : ++bracketsCurvy; break; case '}' : --bracketsCurvy; break; defualt: break; } if (!(bracketsNormal && bracketsSquare && bracketsCurvy)) return false; }while(++str != '\0'); if ( (bracketsNormal == 1) && (bracketsSquare == 1) && (bracketsCurvy == 1)) return true; return false; }
Liam Reyes
fuck, missed this ([)] case, but now it's fixed: bool testBalancedBrackets(char* str){ char bracketBuffer[512]; char* bracketIterator = bracketBuffer; do{ switch(*str){ case '(' : case '[' : case '{' : *(bracketIterator++) = *str; break; case ')' : if ( bracketIterator == bracketBuffer || *(--bracketIterator) != '(' ) return false; case ']' : if ( bracketIterator == bracketBuffer || *(--bracketIterator) != '[' ) return false; case '}' : if ( bracketIterator == bracketBuffer || *(--bracketIterator) != '{' ) return false; defualt: break; } }while(++str != '\0'); if ( bracketIterator == bracketBuffer ) return true; return false; }
This should be very fast also, but it only works for a maximum of 512 open brackets, lol.
Lincoln Perez
bool testBalancedBrackets(char* str){ char bracketBuffer[512]; char* bracketIterator = bracketBuffer; do{ switch(*str){ case '(' : case '[' : case '{' : *(bracketIterator++) = *str; break; case ')' : if ( (bracketIterator == bracketBuffer) || (*(--bracketIterator) != '(') ) return false; break; case ']' : if ( (bracketIterator == bracketBuffer) || (*(--bracketIterator) != '[') ) return false; break; case '}' : if ( (bracketIterator == bracketBuffer) || (*(--bracketIterator) != '{') ) return false; break; defualt: break; } }while(*(++str) != '\0'); if ( bracketIterator == bracketBuffer ) return true; return false; }
ok, now its also fixed to compile correctly and no more bugs...
Do I get hired?
Nathan Murphy
feel free to tell me what you would improve about
Dominic Hill
oh i shat myself. this is failed on "()()" sorry, here is the fixed solution static Dictionary brackets = new Dictionary { { '(', ')' }, { '[', ']' }, { '{', '}' } };
public static bool IsBalancedBrackets(string s) { for (int i = 0; i < s.Length; i++) if (!IsOpenBracket(s[i]) || !HasClosedBracket(s, ref i)) return false; return true; }
static bool IsOpenBracket(char c) => c == '(' || c == '{' || c == '[';
static bool HasClosedBracket(string s, ref int i) { var match = brackets[s[i]]; for (i++; i < s.Length; i++) { if (s[i] == match) return true; if (IsOpenBracket(s[i]) && !HasClosedBracket(s, ref i)) return false; } return false; }
def balanced(s): counter = collections.Counter() cs = set(list('{}[]()')) for c in s: if c not in cs: continue counter[c] += 1 return ( counter['('] == counter[')'] and counter['{'] == counter['}'] and counter['['] == counter[']'])
print(balanced('{hel[l]o}'))
Oliver Martin
true
they probably just wanted to get rid of him quickly
Michael Edwards
My mistake, they said O(n), I recall them saying I was going for a new record with O(n*4) or something like that.
I've had 2~ interviews a week for a couple months now. Literally sitting down in offices where there's 12~ people around the table and they're doing "group interviews." We're all sitting around the table doing personality tests and competency tests, and having to grab answers from other people like "What did group H person 5 put for their question #6? Do you think it's correct, and write how you would help them get to a better answer." It's hell, the competition for minumum wage has never ever been like this, not since they raised minimum wage to $15/h in Alberta.
(Also we were all referred to as group H, implying they get 100~ people for positions like this. This was for a job posting where they said they had 3 openings.)
It's hard to say maybe I'm OK when the objective evidence is me facing a huge rejection rate. The only thing that makes me reconsider is that I applied with my Resume to some places in Maryland and got invited to interviews for jobs around $140k/yr USD with the exact same skillset as what I'm fighting against other people for $20k/yr USD in Alberta. Then I have to tell them I'm a remote-only worker and they pass me over for an American. Happens every time, even though I incorporated alongside a bunch of my friends who are moving out of Canada for work.
checked. pretty much my solution to the problem as well
Jonathan Reed
why would that work?
Jeremiah Rodriguez
He means it returns true when it should return false IE his function failed
Gabriel Perez
Seems easy to solve with a stack if I'm not mistaken. Process the string sequentially, push any open bracket to the stack. When you encounter a closing bracket, pop an element from the stack. If there's nothing to pop or you get an open bracket of a different type, return false immediately. If you manage to go through the whole string, return true since it means the string is balanced.
Matthew Stewart
If you manage to go through the whole string, return true since it means the string is balanced. Only if the stack is empty at the end. ((((((((((((((()))
Tyler Foster
Actually, that's not right. After the loop you'd have to check whether the stack is empty. The string is only balanced if it is, otherwise you have more opening brackets than closing.
Eli Mitchell
Yeah, I realized that.
Jayden Johnson
lmao this would never pass code review
Julian Wilson
sounds like they were dicks, just keep applying to jobs dude
Hudson Clark
Fancypants optimizations if you're trying to show off: When you encounter an opener, push the matching closer onto the stack, not the opener. Why? It saves a couple lines later, that's all. (next iteration, if the top of the stack and the new input character match, you can just pop and move on without actually checking what the new character is) If you're using an array as a stack, it only needs to be half the length of the input; if the stack fills up, you can immediately return false, because you already know there aren't enough closing brackets. Likewise, keep track of your stack depth and the remaining length of the input; if the stack is ever deeper than the remaining string, you can immediately return false, because you already know there aren't enough closing brackets.
Julian Roberts
what if you just did a reverse string check like the ones for checking string palindromes but with the condition that the character checks are not equals but equals to ascii value plus 2 cause ascii goes {, |, } and [,\,]
Noah Rivera
You could use a stack, but why not just a counter for each type that increments on open brackets, deincrements and closed brackets, and is checked if it's 0 at the end of the string?
Cooper Sanders
Because using counters would fail on strings like "([)]" which isn't correct but still has the same number of opening and closing brackets of each type.
Austin Brooks
I said a counter for each type
Xavier Brown
Yes, I know. It still doesn't help.
Bentley Brooks
oh, mb, I'm a retard. I see the problem.
Bentley Brown
seriously though is there any best website for these dumb challenges? I'm tired of ranking bullshit and subscriptions, I just want the questions and then example solutions
Connor Cook
hackerrank
Nolan Garcia
Leetcode. Hackerrank is a close 2nd but it is nissing some features Leetcode had for ages and its interview prep questions are better.
Christopher Wood
public int solution(string S) { if(string.IsNullOrEmpty(S)) return 1; if(S.Length % 2 != 0) return 0;
private static final Map brackets = new HashMap() {{ put('(', ')'); put('{', '}'); put('[', ']'); }};
static boolean isBracket(char c) { return isLeft(c) || isRight(c); }
static boolean isLeft(char c) { return brackets.keySet().contains(c); }
static boolean isRight(char c) { return brackets.values().contains(c); }
static boolean areOpposite(char a, char b) { return Objects.equals(brackets.get(a), b); }
static boolean canFollow(char c, char prev) { if (isRight(prev)) return true; // anything can follow and opening bracket return isLeft(c) || areOpposite(prev, c); // a right paren can not follow a left square bracket }
static boolean balanced(String str) { Stack stack = new Stack(); // only push never pop
int openBrackets = 0; for (int i = 0; i < str.length(); i++) { final char c = str.charAt(i); if (!isBracket(c)) continue; if (isLeft(c)) openBrackets++; if (isRight(c)) openBrackets--;
if (stack.empty()) { stack.push(c); continue; }
char prev = stack.peek(); if (!canFollow(c, prev)) return false;
stack.push(c); } return openBrackets == 0; }
this is probably the only correct solution ITT
Brandon Nelson
>C No one uses this @ facebook.
Eli Sanchez
You responded to the wrong user but also no shit
Noah Green
Based and erlangpilled.
Christian Howard
No time to code, but I figure you'd push the opening symbols ( { [ on a stack, and if a closing one appears ) } ] you pop the top of the stack.
If it doesn't match the same type it's not balanced, right?
Justin Green
you cant pop because the opening bracket could be anywhere in the stack
Sebastian Evans
That was my solution too fren
Luis Cox
import balanced.isBalanced as myFunc
EXAMPLE = "(()()[])"
print(myFunc(EXAMPLE))
Jordan Roberts
just realized that the single counter allows a square bracket to close a paren which makes "( [ ] ]" return true