Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
66 changes: 66 additions & 0 deletions c++ problems asked in interview/Valid_Parentheses.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
/*
* C++ Solution for the "Valid Parentheses" Problem
*
* Problem: Given a string s containing just the characters '(', ')',
* '{', '}', '[' and ']', determine if the input string is valid.
* An input string is valid if:
* 1. Open brackets must be closed by the same type of brackets.
* 2. Open brackets must be closed in the correct order.
*
* Contributor: Priyanka Anand
* Submitted for Hacktoberfest 2025
*/

#include <iostream>
#include <string>
#include <stack>
#include <unordered_map>

class Solution {
public:
bool isValid(std::string s) {
std::stack<char> charStack;
// Map to hold the valid pairs
std::unordered_map<char, char> pairs = {
{')', '('},
{']', '['},
{'}', '{'}
};

for (char c : s) {
// If it's a closing bracket
if (pairs.count(c)) {
// Check if stack is empty or top element doesn't match
if (charStack.empty() || charStack.top() != pairs[c]) {
return false; // Invalid
}
charStack.pop(); // It's a valid pair, pop the opening bracket
} else {
// It's an opening bracket, push onto stack
charStack.push(c);
}
}

// If the stack is empty, all brackets were matched
return charStack.empty();
}
};

// Main function to test the solution
int main() {
Solution sol;
std::string str1 = "()[]{}";
std::string str2 = "([)]";
std::string str3 = "{[]}";

std::cout << "String \"" << str1 << "\" is valid: "
<< (sol.isValid(str1) ? "true" : "false") << std::endl;

std::cout << "String \"" << str2 << "\" is valid: "
<< (sol.isValid(str2) ? "true" : "false") << std::endl;

std::cout << "String \"" << str3 << "\" is valid: "
<< (sol.isValid(str3) ? "true" : "false") << std::endl;

return 0;
}