Menu

The Lion's Den

I write stuff sometimes

The Weekly Roar: Competitive Programming is Awesome

Learning new stuff can be frustrating sometimes, especially if you don’t immediately understand the material. I’m currently taking a class called Competitive Programming, which holds weekly “contests” (that acts as homework) and we learn how to write fast, efficient code. There are around 4-5 questions per week per contest, and the questions are interesting and really make you think.

For example, last week’s contest included a question about balancing brackets. Here’s the solution I came up with:

static String isBalanced(String s) {
    Stack<Character> stack = new Stack<>();
    for (int i = 0; i < s.length(); i++) {
        char c = s.charAt(i);
        if (c == '{' || c == '[' || c == '(') {
            stack.push(c);
        }
        else if (c == '}') {
            if (!stack.empty() && stack.peek() == '{') {
                stack.pop();
            }
            else {
                return "NO";
            }
        }
        else if (c == ']') {
            if (!stack.empty() && stack.peek() == '[') {
                stack.pop();
            }
            else {
                return "NO";
            }
        }
        else if (c == ')') {
            if (!stack.empty() && stack.peek() == '(') {
                stack.pop();
            }
            else {
                return "NO";
            }
        }
    }
    
    if (stack.empty()) {
        return "YES";
    }
    else {
        return "NO";
    }
}

I could definitely improve this method, and that’s the best part: you’re constantly learning from the code you write. You can see different ways to solve a problem after you’ve solved it once. That’s what’s really cool about the competitive programming class.

Leave a Reply