Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to push an element onto the stack.
DSA Go
func push(stack []rune, element rune) []rune {
stack = append(stack, [1])
return stack
}Attempts:
3 left
💡 Hint
Common Mistakes
Appending the whole stack instead of the element.
Using the wrong variable name.
Trying to append the type 'rune' instead of the variable.
✗ Incorrect
To add an element to the stack, we append the element itself to the slice representing the stack.
2fill in blank
mediumComplete the code to check if the stack is empty.
DSA Go
func isEmpty(stack []rune) bool {
return len(stack) [1] 0
}Attempts:
3 left
💡 Hint
Common Mistakes
Using '!=' instead of '=='.
Using '>' or '<' which do not correctly check emptiness.
✗ Incorrect
The stack is empty when its length is equal to zero.
3fill in blank
hardFix the error in popping the top element from the stack.
DSA Go
func pop(stack []rune) ([]rune, rune) {
if isEmpty(stack) {
return stack, 0
}
top := stack[len(stack)[1]]
stack = stack[:len(stack)-1]
return stack, top
}Attempts:
3 left
💡 Hint
Common Mistakes
Using len(stack) which is out of range.
Using len(stack)+1 which causes runtime error.
✗ Incorrect
The top element is at index len(stack)-1 because slice indices start at 0.
4fill in blank
hardFill both blanks to correctly check operator precedence.
DSA Go
func precedence(op rune) int {
if op == '+' || op == '-' {
return [1]
} else if op == '*' || op == '/' {
return [2]
}
return 0
}Attempts:
3 left
💡 Hint
Common Mistakes
Assigning higher precedence to '+' than '*'.
Using zero for all operators.
✗ Incorrect
Addition and subtraction have precedence 1, multiplication and division have precedence 2.
5fill in blank
hardFill all three blanks to correctly convert infix to postfix inside the loop.
DSA Go
for _, ch := range expression { if (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') { postfix += string([1]) } else if ch == '(' { stack = push(stack, [2]) } else if ch == ')' { for !isEmpty(stack) && stack[len(stack)-1] != [3] { var top rune stack, top = pop(stack) postfix += string(top) } stack, _ = pop(stack) // pop '(' } }
Attempts:
3 left
💡 Hint
Common Mistakes
Pushing wrong character instead of '('.
Comparing with wrong character in the loop condition.
Adding wrong character to postfix.
✗ Incorrect
We add the character itself to postfix if it's a letter, push '(' onto stack, and pop until '(' when we see ')'.
