Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to push an opening bracket onto the stack.
DSA Typescript
if (char === '(') { stack.[1](char); }
Attempts:
3 left
š” Hint
Common Mistakes
Using pop instead of push removes elements instead of adding.
Using shift or unshift changes the wrong end of the array.
ā Incorrect
We use push() 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 Typescript
if (stack.[1] === 0) { return false; }
Attempts:
3 left
š” Hint
Common Mistakes
Using size or count which are not valid array properties in TypeScript.
Using empty which is not a property.
ā Incorrect
The length property gives the number of elements in an array.
3fill in blank
hardFix the error in the code to pop the top element from the stack.
DSA Typescript
const top = stack.[1]();Attempts:
3 left
š” Hint
Common Mistakes
Using push which adds instead of removes.
Using shift or unshift which affect the start of the array.
ā Incorrect
pop() removes and returns the last element from the array, which is the top of the stack.
4fill in blank
hardFill both blanks to check if the popped bracket matches the current closing bracket.
DSA Typescript
if (top !== [1]) { return false; } const pairs = { ')': '(', [2]: '[' };
Attempts:
3 left
š” Hint
Common Mistakes
Mixing up opening and closing brackets.
Using wrong bracket types in pairs.
ā Incorrect
We compare top with '(' for ')' and define pairs with ']' for '['.
5fill in blank
hardFill all three blanks to complete the function that checks balanced parentheses.
DSA Typescript
function isBalanced(s: string): boolean {
const stack: string[] = [];
const pairs: { [key: string]: string } = { ')': '(', ']': '[1]', '[2]': '{' };
for (const char of s) {
if (char === '(' || char === '[' || char === '[3]') {
stack.push(char);
} else {
if (stack.length === 0) return false;
const top = stack.pop();
if (top !== pairs[char]) return false;
}
}
return stack.length === 0;
}Attempts:
3 left
š” Hint
Common Mistakes
Confusing opening and closing brackets in pairs.
Missing '{' in the opening brackets check.
ā Incorrect
Pairs map closing brackets to openings: ']' to '[', '}' to '{'. Opening brackets include '{'.
