Challenge: Valid Parentheses
Welcome to Day 6 of our 100 Days DSA Challenge! 🚀 Today’s challenge takes us into the realm of valid parentheses – a classic problem that tests our understanding of balancing and sequencing brackets.
The Challenge:
Given a string containing the characters ‘(‘, ‘)’, ‘{‘, ‘}’, ‘[‘, and ‘]’, our task is to determine if the input string is valid according to the following rules:
- Open brackets must be closed by the same type of brackets.
- Open brackets must be closed in the correct order.
Example:
const s = "()[]{}";
// Output: true
Challenge Yourself:
Before exploring the solution, challenge yourself to think about how you would approach this problem. Can you optimize the code further?
The Solution:
const validParentheses = (str) => {
const openParentheses = [];
const openClose = {
")": "(",
"]": "[",
"}": "{"
};
for (let i = 0; i < str.length; i++) {
if (str[i] == "(" || str[i] == "[" || str[i] == "{") {
openParentheses.push(str[i]);
} else {
const openBracket = openParentheses.pop();
if (openBracket != openClose[str[i]]) {
return false;
}
}
}
return true;
}
Solution Logic:
Initialize Stacks and Mapping:
- We use an array (
openParentheses
) as a stack to keep track of open brackets. - We create a mapping (
openClose
) that associates closing brackets with their corresponding opening brackets.
Iterate Through the String:
- We iterate through the input string and process each character.
Handle Opening Brackets:
- If the character is an opening bracket, we push it onto the stack.
Handle Closing Brackets:
- If the character is a closing bracket, we pop the last item from the stack and check if it matches the expected opening bracket.
Check for Validity:
- If the brackets are valid, the stack will be empty at the end of the iteration.
Return the Result:
- We return
true
if the brackets are valid andfalse
otherwise.
Conclusion:
Congratulations on completing Day 6 of our DSA Challenge! Validating parentheses is a crucial skill in coding, and mastering it enhances your algorithmic abilities. Stay tuned for tomorrow’s challenge, and keep the coding spirit alive!
Happy coding! 🌟💻
#100DaysDSAChallenge #DataStructures #Algorithms #ProgrammingCommunity #CodeNewbie