Data Structure Problems
Data Structure Problems
Examples:
• Input: 1 → 2 → 3 → 4 → 5 → 6 → NULL
Output: 2 → 1 → 4 → 3 → 6 → 5 → NULL
• Input: 1 → 2 → 3 → 4 → 5 → NULL
Output: 2 → 1 → 4 → 3 → 5 → NULL
Note: The starting page of the tab will always be the homepage.
Examples:
Example 1:
• Input:
homepage = ”geeksforgeeks.org”
visit(”amazon.com”);
back(2);
• Output: geeksforgeeks.org
1
• Explanation: We need to move 2 steps back but since only 1 step is available we would
land up at the homepage, i.e., geeksforgeeks.org
Example 2:
• Input:
homepage = ”gfg.org”
visit(”google.com”);
visit(”facebook.com”);
visit(”youtube.com”);
back(1);
back(1);
forward(1);
visit(”linkedin.com”);
forward(2);
back(2);
back(7);
• Output:
facebook.com
google.com
facebook.com
linkedin.com
google.com
gfg.org
• Explanation:
visit(”google.com”): We are at google.com
visit(”facebook.com”): Now, we are at facebook.com
visit(”youtube.com”): We are at youtube.com
back(1): We would land up at facebook.com, if we move one step back.
back(1): Moving one step back, takes us to google.com
forward(1): Moving a step forward we would be at facebook.com
visit(”linkedin.com”): We are at linkedin.com
forward(2): We are still at linkedin.com since visiting clears the forward history. When
we are at the current URL, there is no URL to move forward to.
back(2): Moving two steps back, takes us to google.com
back(7): We need to move 7 steps back, but only 1 url is available. Therefore we would
return gfg.org.
class Node {
public :
string data ;
Node * prev ;
Node * next ;
Node ( string x ) {
data = x ;
2
prev = nullptr ;
next = nullptr ;
}
};
class BrowserHistory {
public :
}
};
int main () {
3
obj . visit ( " linkedin . com " ) ;
return 0;
}
Examples:
• Input: Linked List = 11 → 11 → 11 → 21 → 43 → 43 → 60
Output: 11 → 21 → 43 → 60
Examples:
• Input: head1 = 1 → 2 → 3 → 4 → 6, head2 = 2 → 4 → 6 → 8
Output: 2 4 6
Explanation: For the given two linked list, 2, 4 and 6 are the elements in the intersection.
4
Examples:
• Input: 1 → 4 → 3 → 2 → 5 → 2 → 3, x = 3
Output: 1 → 2 → 2 → 3 → 3 → 4 → 5
Explanation: In the below linked list, all nodes with value less than 3 are on the left
and rest of the nodes on the right by maintaining the relative order.
• Input: 10 → 4 → 20 → 10 → 3, x = 3
Output: 3 → 10 → 4 → 20 → 10
Example:
• Input:
head1: 5 → 7 → 10 → 15 → 30
head2: 4 → 9 → 17 → 40
• Output: 4 → 5 → 7 → 9 → 10 → 15 → 17 → 30 → 40
5
Stack Problems
1. Reverse a string using a stack
Problem Statement: Given a string, reverse it using a stack.
Example:
• Input: "GeeksQuiz"
Output: "ziuQskeeG"
• Input: "abc"
Output: "cba"
• Input: "[{()}]"
Output: true
• Input: "[()()]{}"
Output: true
• Input: "([]"
Output: false
• Input: "([{]})"
Output: false
• Input: "azxxzy"
Output: "ay"
Removal of “xx” modifies the string to “azzy”.
Now, the removal of “zz” modifies the string to “ay”.
Since the string “ay” doesn’t contain duplicates, the output is ay.
• Input: "aaccdd"
Output: Empty String
6
5. Evaluate a postfix expression using a stack
Problem Statement: Given a postfix expression, evaluate it using stack operations.
Example:
• Input: "((a+b))"
Output: true (redundant)
• Input: "(a+(b)/c)"
Output: false (not redundant)
7
9. Nearest smaller element to the left
Problem Statement: Given an array of integers, for each element, find the nearest
smaller integer on the left.
Example:
8
Queue Problems
1. Reverse a queue
Problem Statement: Given a queue Q, reverse the queue using only the standard
operations: enqueue(x), dequeue(), and empty().
Example:
• Input: [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Output: [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
• Input: [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]
2. Reverse the first k elements of a queue
Problem Statement: Given an integer k and a queue of integers, reverse the first k
elements of the queue, leaving the other elements in the same relative order.
Only following standard operations are allowed on queue.
• enqueue(x) : Add an item x to rear of queue
• dequeue() : Remove an item from front of queue
• size() : Returns number of elements in queue.
• front() : Finds front item.
3. Implement a queue using two stacks
Problem Statement: Implement a queue using two stacks (stack1 and stack2). The
queue should support standard enqueue and dequeue operations.
4. Implement a stack using queues
Problem Statement: Given a queue data structure that supports enqueue() and
dequeue() operations, implement a stack.
9
• Explanation
First negative integer for each window of size k:
{-8, 2} = -8
{2, 3} = 0 (does not contain a negative integer)
{3, -6} = -6
{-6, 10} = -6
• Input: [12, −1, −7, 8, −15, 30, 16, 28], k = 3
Output: [−1, −1, −7, −15, −15, 0]
• Input: [4, 3, 2, 6]
Output: 29
• Explanation: We can connect the ropes in following ways.
1) First connect ropes of lengths 2 and 3. Which makes the array [4, 5, 6]. Cost of
this operation 2 + 3 = 5.
2) Now connect ropes of lengths 4 and 5. Which makes the array [9, 6]. Cost of this
operation 4 + 5 = 9.
3) Finally connect the two ropes and all ropes have connected. Cost of this operation
9 + 6 =15. Total cost is 5 + 9 + 15 = 29. This is the optimized cost for connecting
ropes.
Other ways of connecting ropes would always have same or more cost. For example,
if we connect 4 and 6 first (we get three rope of 3, 2 and 10), then connect 10 and 3
(we gettwo rope of 13 and 2). Finally we connect 13 and 2. Total cost in this way
is 10 + 13 + 15 = 38.
• Input: [10]
Output: 0
• Explanation: Since there is only one rope, no connections are needed, so the cost is
0.
10
Graph: DFS and BFS problems
1. Rotten Oranges Given a matrix of dimension M * N, where each cell in the matrix can
have values 0, 1 or 2 which has the following meaning:
• 0: Empty cell
• 1: Cells have fresh oranges
• 2: Cells have rotten oranges
The task is to find the minimum time required so that all the oranges become rotten. A
rotten orange at index (i,j) can rot other fresh oranges which are its neighbors (up, down,
left, and right).
Note: If it is impossible to rot every orange then simply return -1.
Examples:
Example 1:
• Input: arr[][] = { {2, 1, 0, 2, 1}, {1, 0, 1, 2, 1}, {1, 0, 0, 2, 1}};
• Output: 2
• Explanation:
At 0th time frame:
{2, 1, 0, 2, 1}
{1, 0, 1, 2, 1}
{1, 0, 0, 2, 1}
Example 2:
• Input: arr[][] = { {2, 1, 0, 2, 1}, {0, 0, 1, 2, 1}, {1, 0, 0, 2, 1}}
• Output: -1
• Explanation:
At 0th time frame:
{2, 1, 0, 2, 1}
{0, 0, 1, 2, 1}
{1, 0, 0, 2, 1}
11
At 1st time frame:
{2, 2, 0, 2, 2}
{0, 0, 2, 2, 2}
{1, 0, 0, 2, 2}
Examples:
Example 1:
• Input:
M[][] = {{’1’, ’1’, ’0’, ’0’, ’0’},
{’0’, ’1’, ’0’, ’0’, ’1’},
{’1’, ’0’, ’0’, ’1’, ’1’},
{’0’, ’0’, ’0’, ’0’, ’0’},
{’1’, ’0’, ’1’, ’1’, ’0’}}
• Output: 4
• Explanation: The image below shows all the 4 islands in the graph
12
Example 2:
• Input:
M[][] = {{’1’, ’1’},
{’1’, ’1’}}
• Output: 1
• Explanation: All elements are 1, hence there is only one island
Example 3:
• Input:
M[][] = {{’0’, ’0’},
{’0’, ’0’}}
• Output: 0
• Explanation: All elements are 0, hence no islands.
3. Flood Fill Algorithm Given a 2D image image[][] where each image[i][j] is an integer
representing the color of that pixel also given a coordinate (sr, sc) representing the starting
pixel (row and column) of the flood fill, and a pixel value newColor. ”flood fill” the image.
The task is to replace the existing color of the given pixel and all the adjacent same-colored
pixels with the given newColor.
Examples:
Example 1:
Example 2:
4. Word Ladder Given an array of strings arr[], and two different strings start and target,
representing two words. The task is to find the length of the smallest chain from string
start to target, such that only one character of the adjacent words differs and each word
exists in arr[].
Note: Print 0 if it is not possible to form a chain. Each word in array arr[] is of same size
m and contains only lowercase English alphabets.
13
Examples:
Example 1:
• Input: start = ”toon”, target = ”plea”, arr[] = [”poon”, ”plee”, ”same”, ”poie”,
”plea”, ”plie”, ”poin”]
• Output: 7
• Explanation: toon → poon → poin → poie → plie → plee → plea
Example 2:
• Input: start = ”abcv”, target = ”ebad”, arr[] = [”abcd”, ”ebad”, ”ebcd”, ”xyza”]
• Output: 4
• Explanation: abcv → abcd → ebcd → ebad
5. Snake and Ladder Problem Given a snake and ladder board, find the minimum number
of dice throws required to reach the destination or last cell from the source or 1st cell.
Basically, the player has total control over the outcome of the dice throw and wants to
find out the minimum number of throws required to reach the last cell.
If the player reaches a cell which is the base of a ladder, the player has to climb up that
ladder and if reaches a cell is the mouth of the snake, and has to go down to the tail of
the snake without a dice throw.
Example:
• Input:
• Output: 3
• Explanation: Following are the steps:
– First throw two dice to reach cell number 3 and then ladder to reach 22
– Then throw 6 to reach 28.
– Finally through 2 to reach 30.
There can be other solutions as well like (2, 2, 6), (2, 4, 4), (2, 3, 5).. etc.
14
BST problems
1. Given a BST, the task is to search a node in this BST. For searching a value in BST,
consider it as a sorted array. Now we can easily perform search operation in BST using
Binary Search Algorithm.
Examples:
• Input:
Output: True
• Input:
Output: False
2. Given a Binary Search Tree, the task is to find the second largest element in the
given BST.
Examples:
15
• Input:
Output: 7
Explanation: The Second Largest value in the given BST is 7.
• Input:
Output: 20
Explanation: The Second Largest value in the given BST is 20.
3. Given Binary Search Tree. The task is to find the sum of all elements smaller than and
equal to k-th smallest element.
Examples:
• Input:
16
Output: 17
Explanation: kth smallest element is 8 so sum of all element smaller than or equal
to 8 are 2 + 7 + 8 = 17.
• Input:
Output: 25
Explanation: kth smallest element is 8 so sum of all element smaller than or equal
to 8 are 8 + 5 + 7 + 2 + 3 = 25.
4. Given two values n1 and n2 where n1 <n2 and a root pointer to a Binary Search Tree.
The task is to find all the keys of the tree in the range n1 to n2 in increasing order.
Examples:
• Input: n1 = 10, n2 = 22
17
Output: 12, 20 and 22.
Explanation: The keys are 4, 8, 12, 20, and 22, So keys in range 10 to 22 is 12, 20
and 22.
• Input: n1 = 1, n2 = 10
Output: 8
Explanation: The key 8 is in the range 1 to 10.
5. Given two Binary Search Trees consisting of unique positive elements, the task is to check
whether the two BSTs contain the same set of elements or not. The structure of the two
given BSTs can be different.
Examples:
Input:
18
Output: True
Explanation: The above two BSTs contains same set of elements 5, 10, 12, 15, 20, 25
6. Given a Singly Linked List which has data members sorted in ascending order. Construct
a Balanced Binary Search Tree which has same data members as the given Linked List.
Examples:
Input: Linked List 1 → 2 → 3
Output: A Balanced BST
2
/ \
1 3
4
/ \
2 6
/ \ / \
1 3 5 7
3
/ \
2 4
/
1
4
/ \
2 6
/ \ /
1 3 5
19