0% found this document useful (0 votes)
2 views

Data Structure Problems

The document outlines various data structure problems, including linked list manipulations, stack operations, and queue implementations. It provides detailed problem statements, examples, and expected outputs for each problem. Key topics include pairwise swapping in linked lists, browser history management, and evaluating postfix expressions.

Uploaded by

24022476
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Data Structure Problems

The document outlines various data structure problems, including linked list manipulations, stack operations, and queue implementations. It provides detailed problem statements, examples, and expected outputs for each problem. Key topics include pairwise swapping in linked lists, browser history management, and evaluating postfix expressions.

Uploaded by

24022476
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Data Structure Problems

Nguyen Tien Dat


March 7, 2025

Linked List Problems


1 Pairwise Swap Elements in a Linked List
Given a singly linked list, the task is to swap linked list elements pairwise.

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

2 Browser History Implementation


You have a browser of one tab where you start on the homepage and you can visit another URL,
get back in the history number of steps or move forward in the history number of steps. The
task is to design a data structure and implement the functionality of visiting a URL starting
from the homepage and moving back and forward in the history. The following functionalities
should be covered:

• visit(url): Visits a URL given as string

• forward(steps): Takes ’steps’ forward.

• back(steps): Takes ’steps’ backward.

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.

// C ++ implementation of browser history


// using Doubly Linked List
# include < bits / stdc ++. h >
using namespace std ;

class Node {
public :
string data ;
Node * prev ;
Node * next ;

Node ( string x ) {
data = x ;

2
prev = nullptr ;
next = nullptr ;
}
};

class BrowserHistory {
public :

// Pointer to the current URL


Node * curr ;

// Constructor to initialize with the homepage


BrowserHistory ( string homepage ) {
curr = new Node ( homepage ) ;
}

// Function to visit a new URL


void visit ( string url ) {

// Function to move back by ’ step ’ times


string back ( int step ) {

// Function to move forward by ’ step ’ times


string forward ( int step ) {

}
};

int main () {

// Initialize with the homepage


string homepage = " gfg . org " ;
BrowserHistory obj ( homepage ) ;

string url = " google . com " ;


obj . visit ( url ) ;

url = " facebook . com " ;


obj . visit ( url ) ;

url = " youtube . com " ;


obj . visit ( url ) ;

cout << obj . back (1) << endl ;

cout << obj . back (1) << endl ;

cout << obj . forward (1) << endl ;

3
obj . visit ( " linkedin . com " ) ;

cout << obj . forward (2) << endl ;

cout << obj . back (2) << endl ;

cout << obj . back (7) << endl ;

return 0;
}

3 Remove Duplicates from Sorted Linked List


Given a linked list sorted in non-decreasing order. Return the list by deleting the duplicate
nodes from the list. The returned list should also be in non-decreasing order.

Examples:
• Input: Linked List = 11 → 11 → 11 → 21 → 43 → 43 → 60
Output: 11 → 21 → 43 → 60

• Input: Linked List = 5 → 10 → 10 → 20


Output: 5 → 10 → 20 (After removing duplicate elements)

4 Intersection of Two Sorted Linked Lists


Given the head of two sorted linked lists, the task is to create a new linked list that represents the
intersection of the two original lists. The new linked list should be created without modifying
the original lists.
Note: The elements in the linked lists are not necessarily distinct.

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.

• Input: head1 = 10 → 20 → 40 → 50, head2 = 15 → 40


Output: 40

5 Partition Linked List


Given a linked list and a value x, partition it such that all nodes less than x come first, then
all nodes with a value equal to x, and finally nodes with a value greater than x. The original
relative order of the nodes in each of the three partitions should be preserved.

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

6 Merge Two Sorted Linked Lists


Given two sorted linked lists consisting of n and m nodes respectively. The task is to merge
both of the lists and return the head of the merged list.

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"

2. Check balanced brackets in a string


Problem Statement: Given a string s representing an expression containing brackets:
{}, (), and [], determine whether the brackets in the expression are balanced.
Example:

• Input: "[{()}]"
Output: true
• Input: "[()()]{}"
Output: true
• Input: "([]"
Output: false
• Input: "([{]})"
Output: false

3. Design two stacks in one array


Problem Statement: Create a data structure twoStacks that uses a single array for
two stacks. The class should support the following operations:

• push1(int x) : Push x to the first stack.


• push2(int x) : Push x to the second stack.
• pop1() : Pop an element from the first stack and return it.
• pop2() : Pop an element from the second stack and return it.

Ensure space efficiency.

4. Remove all adjacent duplicates in a string


Problem Statement: Given a string str, remove all adjacent duplicate characters.
Example:

• 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: [”2”, ”3”, ”1”, ” ∗ ”, ” + ”, ”9”, ” − ”]


Output: −4
Explanation: If the expression is converted into an infix expression, it will be 2 +
(3 * 1) – 9 = 5 – 9 = -4.
• Input: [”100”, ”200”, ” + ”, ”2”, ”/”, ”5”, ” ∗ ”, ”7”, ” + ”]
Output: 757
Explanation: If the expression is converted into an infix expression, it will be ((100
+ 200) / 2) * 5 + 7 = 150 * 5 + 7 = 757.

6. Compare two strings with backspace (#) operations


Problem Statement: Given two strings s1 and s2, which contain backspace characters
# indicating that the character before it should be removed, determine if the final pro-
cessed strings are equal.
Example:

• Input: s1 = "geee#e#ks", s2 = "gee##eeks"


Output: true
• Input: s1 = "equ#ual", s2 = "ee#quaal#"

7. Check for redundant parentheses


Problem Statement: Given a string of a balanced expression, find if it contains redun-
dant parentheses.
Example:

• Input: "((a+b))"
Output: true (redundant)
• Input: "(a+(b)/c)"
Output: false (not redundant)

8. Find the maximum depth of balanced parentheses


Problem Statement: Given a string with parentheses, determine the maximum depth
if the parentheses are balanced. Otherwise, return −1.
Example:

• Input: "( ((X)) (((Y))) )"


Output: 4
• Input: "( a(b) (c) (d(e(f)g)h) I (j(k)l)m)"
Output: 4
• Input: ""
Output: 0
• Input: "b) (c) ()"
Output: −1
• Input: "(b) ((c) ()"
Output: −1

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:

• Input: [1, 6, 4, 10, 2, 5]


Output: [ , 1, 1, 4, 1, 2]
• Input: [1, 3, 0, 2, 5]
Output: [ , 1, , 0, 2]

10. Sort a stack using another temporary stack


Problem Statement: Given a stack of integers, sort it in ascending order using another
temporary stack.
Example:

• Input: [34, 3, 31, 98, 92, 23]


Output: [3, 23, 31, 34, 92, 98]
• Input: [3, 5, 1, 4, 2, 8]
Output: [1, 2, 3, 4, 5, 8]

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.

5. First negative integer in every window of size k


Problem Statement: Given an array and a positive integer k, find the first negative
integer in every contiguous subarray of size k. If no negative integer is present, print 0.
Example:
• Input: [−8, 2, 3, −6, 10], k = 2
Output: [−8, 0, −6, −6]

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]

6. Connect ropes with minimum cost


Problem Statement: Given an array of rope lengths, connect them into a single rope
with the minimum total cost. The cost to connect two ropes is the sum of their lengths.
Example:

• 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}

At 1st time frame:


{2, 2, 0, 2, 2}
{2, 0, 2, 2, 2}
{1, 0, 0, 2, 2}

At 2nd time frame:


{2, 2, 0, 2, 2}
{2, 0, 2, 2, 2}
{2, 0, 0, 2, 2}

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}

At 2nd time frame:


{2, 2, 0, 2, 2}
{0, 0, 2, 2, 2}
{1, 0, 0, 2, 2}

The 1 at the bottom left corner of the matrix is never rotten.


2. Number of Islands Given a binary 2D matrix of size n*m, find the number of islands. A
group of connected 1s forms an island.

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:

• Input: image = [[1,1,1],[1,1,0],[1,0,1]], sr = 1, sc = 1, newColor = 2


• Output: [[2,2,2],[2,2,0],[2,0,1]]
• Explanation: From the center of the image (with position (sr, sc) = (1, 1)), all
pixels connected by a path of the same color as the starting pixel are colored with the
new color. Note the bottom corner is not colored 2, because it is not 4-directionally
connected to the starting pixel.

Example 2:

• Input: image = [[0,0,0],[0,0,0]], sr = 0, sc = 0, newColor = 0


• Output: [[0,0,0],[0,0,0]]
• Explanation: The starting pixel is already colored with 0, which is the same as the
target color. Therefore, no changes are made to the image.

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

Input: Linked List 1 → 2 → 3 → 4 → 5 → 6 → 7


Output: A Balanced BST

4
/ \
2 6
/ \ / \
1 3 5 7

Input: Linked List 1 → 2 → 3 → 4


Output: A Balanced BST

3
/ \
2 4
/
1

Input: Linked List 1 → 2 → 3 → 4 → 5 → 6


Output: A Balanced BST

4
/ \
2 6
/ \ /
1 3 5

19

You might also like