23CSE203 Data Structures and Algorithms
Tutorial Questions on Stack
1. Given a string, str, the task is to remove all the duplicate adjacent characters from the given
string.
Examples:
Input: str= “azxxzy”
Output: ay
Input: "aaccdd"
Output: Empty String
2. Consider an array A of size n. Write an efficient algorithm to implement two stacks in A.
3. Given an array arr[] of integers, write an algorithm using stack to determine the Next
Greater Element (NGE) for every element in the array, maintaining the order of appearance.
The Next Greater Element for an element x is defined as the first element to the right of x in
the array that is strictly greater than x. If no such element exists for an element, its Next
Greater Element is -1.
4. Given an array arr[] of integers, write an algorithm using stack to determine the Next Lesser
Element (NLE) for every element in the array, maintaining the order of appearance.
The Next Lesser Element for an element x is defined as the first element to the left of x in the
array that is strictly lesser than [Link] no such element exists for an element, its Next Lesser
Element is -1.
5. In a school, there are n students. You are given a matrix mat[][] of size n x n, where:
mat[i][j] == 1 means student i respects student j.
mat[i][j] == 0 means student i does not respect student j.
A popular student is defined as someone who:
a. Is respected by all the other students.
b. Does not respect anyone else (except themselves).
Implement using Stack and your task is to return the index of the popular student if one
exists, otherwise return -1.
It is guaranteed that mat[i][i] == 1 for all students (a student respects themselves).
Examples:
Input: mat[][] = [[1, 1, 0],
[0, 1, 0],
[0, 1, 1]]
Output: 1
Explanation: Both student 0 and student 2 respect student 1. Student 1 respects no one else
→ Student 1 is the popular student.
Input: mat[][] = [[1, 1],
[1, 1]]
Output: -1
Explanation: Both students respect each other, so no one is the popular student
.Input: mat[][] = [[1]]
Output: 0