Coding for Scrubs: Checking for Pairs (, {, [ (Ruby)

Welcome back to another series of Coding for Scrubs! Just in case this is your first time reading one of my posts, I am referring to myself as the scrub. The series is mainly helping me become a better developer by writing out code. If it ends up helping you too, that’s great! Let’s hop into this week’s problem!

Problem:

We want to develop a function that will check if (, [, or { has its closing pair or vice versa. So if you were to pass in a string that was like, “(){[]”, we know we should get false because { does not have its closing pair. “(([{}]))” would return true.

Pseudocode:

Let’s write out our code in plain English first!

1. Define opening tags
2. Define unpaired tags
3. Iterate forward through string
4. Impossible to fail on an opener until you reach the end of the string. Can only fail on a closer
5. Simply track the openers and only scrutinize the closers

Let’s Code!

First, let’s write out our function and create our variables that will define our opening tags. Then write another variable that will keep track of the tags without a pair.

def isBalanced(string)
openers = ["(", "[", "{"]
unpaired = []
end

Now, we are going to break the string up by using the .split() function and then iterate through each character. While we are iterating through each character, we are going to check if our openers array matches the character. If it does, we are going to move that character into our unpaired array. Else, we are going to create another variable called partner and this will check to see if the character has its closing tag and remove it from the unpaired array. We do so by using the .pop() function.

def isBalanced(string)
openers ["(", "[", "{"]
unpaired = []
string.split('').each do |char|
if openers.include?(char)
unpaired << char
else
partner = unpaired.pop
case char
when ")"
if partner != "("
return false
end
when "]"
if partner != "["
return false
end
when "}"
if partner != "{"
return false
end
else
return nil
end
end
end

We then create a case statement that will check if the closing pair is in our string. If that closing tag does not have its partner, then we want our code to return false.

The last step is to check the length of our unpaired array and see if it is 0. We do this by using the .size() function. If the length is 0, that means all of the tags have their closing pairs and we can return true! Else, we would want the code to return false.

def isBalanced(string)
openers ["(", "[", "{"]
unpaired = []
string.split('').each do |char|
if openers.include?(char)
unpaired << char
else
partner = unpaired.pop
case char
when ")"
if partner != "("
return false
end
when "]"
if partner != "["
return false
end
when "}"
if partner != "{"
return false
end
else
return nil
end
end
end
if unpaired.size == 0
return true
end
end

And that’s it! Thank you guys for tuning into another series. Catch you next week!

Software Engineer in the making.