Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to push an opening parenthesis onto the stack.
DSA Java
if (ch == '(') { stack.[1](ch); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using pop instead of push removes elements instead of adding.
Using peek only looks at the top element without adding.
✗ Incorrect
We use stack.push(ch) to add an element to the top of the stack.
2fill in blank
mediumComplete the code to check if the stack is empty before popping.
DSA Java
if (stack.[1]()) { return false; } else { stack.pop(); }
Attempts:
3 left
💡 Hint
Common Mistakes
Using peek() to check emptiness causes errors if stack is empty.
Using size() returns a number, not a boolean.
✗ Incorrect
The method stack.empty() returns true if the stack has no elements.
3fill in blank
hardFix the error in the condition to match the correct closing parenthesis.
DSA Java
if (ch == '}' && stack.peek() != [1]) { return false; }
Attempts:
3 left
💡 Hint
Common Mistakes
Checking for '(' or '[' instead of '{' causes wrong matching.
Using ')' is incorrect because it is a closing bracket.
✗ Incorrect
A closing '}' must match an opening '{' on top of the stack.
4fill in blank
hardFill both blanks to check matching pairs for ')' and ']' respectively.
DSA Java
if ((ch == ')' && stack.peek() != [1]) || (ch == ']' && stack.peek() != [2]) ) { return false; }
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing up brackets causes false negatives.
Using closing brackets in the check is incorrect.
✗ Incorrect
')' matches '(' and ']' matches '[' on the stack top.
5fill in blank
hardFill all three blanks to complete the code that counts parentheses types.
DSA Java
Map<Character, Integer> counts = new HashMap<>(); for (char ch : input.toCharArray()) { if (ch == '(' || ch == ')' || ch == '{') { counts.put(ch, counts.getOrDefault([1], [2]) + 1); } } return counts.getOrDefault([3], 0);
Attempts:
3 left
💡 Hint
Common Mistakes
Using wrong keys or default values causes errors.
Not incrementing counts properly leads to wrong results.
✗ Incorrect
We use 'ch' as key, default 0 count, and get count for '(' character.
