
Hi! My name is Nhut Nguyen. I am a software engineer and a writer in Copenhagen, Denmark.
Learn more about me at nhutnguyen.com
Search for a command to run...

Hi! My name is Nhut Nguyen. I am a software engineer and a writer in Copenhagen, Denmark.
Learn more about me at nhutnguyen.com
No comments yet. Be the first to comment.
A simple example of using C++ switch

Two dynamic programming techniques to solve Leetcode 120. Triangle. One has space complexity O(n^2). The other is O(n).

An example of using a sliding window approach and an unordered map to track character positions

A simple C++ solution to Leetcode 1695. Maximum Erasure Value using a sliding window approach and prefix sums.

Strategies to avoid them will help you excel in your following technical interview

Given a string s containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.
An input string is valid if:
Open brackets must be closed by the same type of brackets.
Open brackets must be closed in the correct order.
Input: s = "()"
Output: true
Input: s = "()[]{}"
Output: true
Input: s = "(]"
Output: false
1 <= s.length <= 10^4.
s consists of parentheses only '()[]{}'.
For each character c of s:
If it is an open parenthesis ('(', '{', or '['), push it into the stack.
If it is a closed parenthesis (')', '}', or ']') but its previous character is not the corresponding open one, return false. End.
Otherwise (i.e. match open-closed), erase the pair.
Continue the process until all characters of s are visited.
Return true if the stack is empty, i.e. all valid pairs are erased.
#include <iostream>
#include <stack>
using namespace std;
bool isValid(string s) {
stack<char> stk;
for (char c : s) {
if (c == '(' || c == '[' || c == '{') {
stk.push(c);
} else if (stk.empty()) {
return false;
} else if (c == ')' && stk.top() != '(' ||
c == ']' && stk.top() != '[' ||
c == '}' && stk.top() != '{') {
return false;
} else {
stk.pop();
}
}
return stk.empty();
}
int main() {
cout << isValid("()") << endl;
cout << isValid("(){}[]") << endl;
cout << isValid("(]") << endl;
cout << isValid("([)]") << endl;
}
Output:
1
1
0
0
Runtime: O(N), where N = s.length.
Extra space: O(N/2).
Thanks for reading. Feel free to share your thought about my content and check out my FREE book “10 Classic Coding Challenges”.