Queue
Queue
1
Contents
22 Find the first circular tour that visits all petrol pumps 120
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125
2
Contents
33 Interleave the first half of the queue with second half 195
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197
39 Level order traversal in spiral form | Using one stack and one queue 244
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246
40 Level order traversal line by line | Set 2 (Using Two Queues) 247
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 253
41 Level order traversal with direction change after every two levels 254
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261
3
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291
51 Print Binary Tree levels in sorted order | Set 2 (Using set) 308
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 310
4
Contents
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 381
75 Zig Zag Level order traversal of a tree using single queue 438
Source . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 441
5
Chapter 1
An Interesting Method to
Generate Binary Numbers from
1 to n
Input: n = 2
Output: 1, 10
Input: n = 5
Output: 1, 10, 11, 100, 101
A simple method is to run a loop from 1 to n, call decimal to binary inside the loop.
Following is an interesting method that uses queue data structureto print binary numbers.
Thanks to Vivekfor suggesting this approach.
1) Create an empty queue of strings
2) Enqueue the first binary number “1” to queue.
3) Now run a loop for generating and printing n binary numbers.
……a) Dequeue and Print the front of queue.
……b) Append “0” at the end of front item and enqueue it.
……c) Append “1” at the end of front item and enqueue it.
Following is implementation of above algorithm.
C++
6
Chapter 1. An Interesting Method to Generate Binary Numbers from 1 to n
Java
7
Chapter 1. An Interesting Method to Generate Binary Numbers from 1 to n
public class GenerateBNo
{
// This function uses queue data structure to print binary numbers
static void generatePrintBinary(int n)
{
// Create an empty queue of strings
Queue<String> q = new LinkedList<String>();
// Enqueue the first binary number
q.add("1");
// This loops is like BFS of a tree with 1 as root
// 0 as left child and 1 as right child and so on
while(n-- > 0)
{
// print the front of queue
String s1 = q.peek();
q.remove();
System.out.println(s1);
// Store s1 before changing it
String s2 = s1;
// Append "0" to s1 and enqueue it
q.add(s1 + "0");
// Append "1" to s2 and enqueue it. Note that s2 contains
// the previous front
q.add(s2 + "1");
}
}
// Driver program to test above function
public static void main(String[] args)
{
int n=10;
generatePrintBinary(n);
}
}
//This code is contributed by Sumit Ghosh
Python
8
Chapter 1. An Interesting Method to Generate Binary Numbers from 1 to n
def generatePrintBinary(n):
# Create an empty queue
from Queue import Queue
q = Queue()
# Enqueu the first binary number
q.put("1")
# This loop is like BFS of a tree with 1 as root
# 0 as left child and 1 as right child and so on
while(n>0):
n-= 1
# Print the front of queue
s1 = q.get()
print s1
s2 = s1 # Store s1 before changing it
# Append "0" to s1 and enqueue it
q.put(s1+"0")
# Append "1" to s2 and enqueue it. Note that s2
# contains the previous front
q.put(s2+"1")
# Driver program to test above function
n = 10
generatePrintBinary(n)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
1
10
11
100
101
110
111
1000
1001
1010
This article is contributed by Abhishek. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above
9
Chapter 1. An Interesting Method to Generate Binary Numbers from 1 to n
Source
https://www.geeksforgeeks.org/interesting-method-generate-binary-numbers-1-n/
10
Chapter 2
Source
https://www.geeksforgeeks.org/applications-priority-queue/
11
Chapter 3
Source
https://www.geeksforgeeks.org/applications-of-queue-data-structure/
12
Chapter 4
Input :
4
/ \
2 9
/ \ \
3 5 7
Output : [4 5.5 5]
The average value of nodes on level 0 is 4,
on level 1 is 5.5, and on level 2 is 5.
Hence, print [4 5.5 5].
The idea is based on Level order traversal line by line | Set 2 (Using Two Queues)
1. Start by pushing the root node into the queue. Then, remove a node from the front
of the queue.
2. For every node removed from the queue, push all its children into a new temporary
queue.
3. Keep on popping nodes from the queue and adding these node’ s children to the
temporary queue till queue becomes empty.
4. Every time queue becomes empty, it indicates that one level of the tree has been
considered.
13
Chapter 4. Averages of Levels in Binary Tree
5. While pushing the nodes into temporary queue, keep a track of the sum of the nodes
along with the number of nodes pushed and find out the average of the nodes on each
level by making use of these sum and count values.
6. After each level has been considered, again initialize the queue with temporary queue
and continue the process till both queues become empty.
14
Chapter 4. Averages of Levels in Binary Tree
}
/* Helper function that allocates a
new node with the given data and
NULL left and right pointers. */
Node* newNode(int data)
{
Node* temp = new Node;
temp->val = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver code
int main()
{
/* Let us construct a Binary Tree
4
/ \
2 9
/ \ \
3 5 7 */
Node* root = NULL;
root = newNode(4);
root->left = newNode(2);
root->right = newNode(9);
root->left->left = newNode(3);
root->left->right = newNode(8);
root->right->right = newNode(7);
averageOfLevels(root);
return 0;
}
Output:
Average of levels:
[4 5.5 5]
Complexity Analysis:
15
Chapter 4. Averages of Levels in Binary Tree
Source
https://www.geeksforgeeks.org/averages-levels-binary-tree/
16
Chapter 5
Bank Of America (BA Continuum India Pvt. Ltd.) Campus Recruitment - GeeksforGeeks
Approved Offer.
Bank Of America has visited our college for on campus recruitment . The recruitment
consisted of 4 Rounds in total.
The recruitment was for BA Continuum India Pvt Ltd. the technical field of BOA
Round 1:
This round was a general aptitude test, English proficiency, quantitative analysis and the
logical questions. This was time specific f0r each and every section. Try practicing from
GFG, indiabix and careerride youtube videos.
Round 2: TECHNICAL 1
This was a face to face technical interview. I was asked to submit my resume and then was
asked to wait until my name was called out. The interview went around 30-40 minutes.
The interviewer started with a very basic aptitude problem( dices probability) and then he
asked me a puzzle of water jug problem. Then he asked me to explain my projects in the
resume and about the experience I had in the previous organization.
After that he went forward with the technical questions consisting of CODING problems .
17
Chapter 5. Bank Of America (BA Continuum India Pvt. Ltd.) Campus Recruitment
Round 3: TECHNICAL 2
It was another technical round. This round was based on advanced coding.
The interviewers above solely focused on the approach or the pseudo code and helped if we
got stuck somewhere.
Round 4: HR ROUND
Here the HR was very friendly and asked about whether you are able to relocate if asked?
At last I was given a feedback by the interviewers as strong logical and coding skills . I
received the offer letter on that day itself at night.
Position: Senior Tech Associate, Bank Of America
Source
https://www.geeksforgeeks.org/bank-of-america-ba-continuum-india-pvt-ltd-campus-recruitment/
18
Chapter 6
Following are the implementations of simple Breadth First Traversal from a given source.
The implementation uses adjacency list representation of graphs. STL‘s list container is
used to store lists of adjacent nodes and queue of nodes needed for BFS traversal.
C++
19
Chapter 6. Breadth First Search or BFS for a Graph
#include<iostream>
#include <list>
using namespace std;
// This class represents a directed graph using
// adjacency list representation
class Graph
{
int V; // No. of vertices
// Pointer to an array containing adjacency
// lists
list<int> *adj;
public:
Graph(int V); // Constructor
// function to add an edge to graph
void addEdge(int v, int w);
// prints BFS traversal from a given source s
void BFS(int s);
};
Graph::Graph(int V)
{
this->V = V;
adj = new list<int>[V];
}
void Graph::addEdge(int v, int w)
{
adj[v].push_back(w); // Add w to v’s list.
}
void Graph::BFS(int s)
{
// Mark all the vertices as not visited
bool *visited = new bool[V];
for(int i = 0; i < V; i++)
visited[i] = false;
// Create a queue for BFS
list<int> queue;
// Mark the current node as visited and enqueue it
visited[s] = true;
queue.push_back(s);
20
Chapter 6. Breadth First Search or BFS for a Graph
// 'i' will be used to get all adjacent
// vertices of a vertex
list<int>::iterator i;
while(!queue.empty())
{
// Dequeue a vertex from queue and print it
s = queue.front();
cout << s << " ";
queue.pop_front();
// Get all adjacent vertices of the dequeued
// vertex s. If a adjacent has not been visited,
// then mark it visited and enqueue it
for (i = adj[s].begin(); i != adj[s].end(); ++i)
{
if (!visited[*i])
{
visited[*i] = true;
queue.push_back(*i);
}
}
}
}
// Driver program to test methods of graph class
int main()
{
// Create a graph given in the above diagram
Graph g(4);
g.addEdge(0, 1);
g.addEdge(0, 2);
g.addEdge(1, 2);
g.addEdge(2, 0);
g.addEdge(2, 3);
g.addEdge(3, 3);
cout << "Following is Breadth First Traversal "
<< "(starting from vertex 2) \n";
g.BFS(2);
return 0;
}
Java
21
Chapter 6. Breadth First Search or BFS for a Graph
22
Chapter 6. Breadth First Search or BFS for a Graph
Python3
23
Chapter 6. Breadth First Search or BFS for a Graph
24
Chapter 6. Breadth First Search or BFS for a Graph
print ("Following is Breadth First Traversal"
" (starting from vertex 2)")
g.BFS(2)
# This code is contributed by Neelam Yadav
Output:
Illustration :
25
Chapter 6. Breadth First Search or BFS for a Graph
26
Chapter 6. Breadth First Search or BFS for a Graph
Note that the above code traverses only the vertices reachable from a given source vertex.
All the vertices may not be reachable from a given vertex (example Disconnected graph).
To print all the vertices, we can modify the BFS function to do traversal starting from all
nodes one by one (Like the DFS modified version) .
Time Complexity: O(V+E) where V is number of vertices in the graph and E is number of
edges in the graph.
You may like to see below also :
27
Chapter 6. Breadth First Search or BFS for a Graph
Source
https://www.geeksforgeeks.org/breadth-first-search-or-bfs-for-a-graph/
28
Chapter 7
Check if a queue can be sorted into another queue using a stack - GeeksforGeeks
Given a Queue consisting of first n natural numbers (in random order). The task is to check
whether the given Queue elements can be arranged in increasing order in another Queue
using a stack. The operation allowed are:
1. Push and pop elements from the stack
2. Pop (Or enqueue) from the given Queue.
3. Push (Or Dequeue) in the another Queue.
Examples :
Input : Queue[] = { 5, 1, 2, 3, 4 }
Output : Yes
Pop the first element of the given Queue i.e 5.
Push 5 into the stack.
Now, pop all the elements of the given Queue and push them to
second Queue.
Now, pop element 5 in the stack and push it to the second Queue.
Input : Queue[] = { 5, 1, 2, 6, 3, 4 }
Output : No
Push 5 to stack.
Pop 1, 2 from given Queue and push it to another Queue.
Pop 6 from given Queue and push to stack.
Pop 3, 4 from given Queue and push to second Queue.
Now, from using any of above operation, we cannot push 5
into the second Queue because it is below the 6 in the stack.
Observe, second Queue (which will contain the sorted element) takes inputs (or enqueue
elements) either from given Queue or Stack. So, next expected (which will initially be 1)
29
Chapter 7. Check if a queue can be sorted into another queue using a stack
element must be present as a front element of given Queue or top element of the Stack. So,
simply simulate the process for the second Queue by initializing the expected element as 1.
And check if we can get expected element from the front of the given Queue or from the
top of the Stack. If we cannot take it from the either of them then pop the front element of
given Queue and push it in the Stack.
Also, observe, that the stack must also be sorted at each instance i.e the element at the top
of the stack must be smallest in the stack. For eg. let x > y, then x will always be expected
before y. So, x cannot be pushed before y in the stack. Therefore, we cannot push element
with the higher value on the top of the element having lesser value.
Algorithm:
1. Initialize the expected_element = 1
2. Check if either front element of given Queue or top element of the stack have ex-
pected_element
….a) If yes, increment expected_element by 1, repeat step 2.
….b) Else, pop front of Queue and push it to the stack. If the popped element is greater
than top of the Stack, return “No”.
Below is the implementation of this approach:
C++
30
Chapter 7. Check if a queue can be sorted into another queue using a stack
st.push(fnt);
}
// if top element is less than element which
// need to be pushed, then return fasle.
else if (!st.empty() && st.top() < fnt) {
return false;
}
// else push into the stack.
else
st.push(fnt);
}
// while expected element are coming from
// stack, pop them out.
while (!st.empty() && st.top() == expected) {
st.pop();
expected++;
}
}
// if the final expected element value is equal
// to initial Queue size and the stack is empty.
if (expected - 1 == n && st.empty())
return true;
return false;
}
// Driven Program
int main()
{
queue<int> q;
q.push(5);
q.push(1);
q.push(2);
q.push(3);
q.push(4);
int n = q.size();
(checkSorted(n, q) ? (cout << "Yes") :
(cout << "No"));
return 0;
}
31
Chapter 7. Check if a queue can be sorted into another queue using a stack
Java
32
Chapter 7. Check if a queue can be sorted into another queue using a stack
33
Chapter 7. Check if a queue can be sorted into another queue using a stack
C#
34
Chapter 7. Check if a queue can be sorted into another queue using a stack
35
Chapter 7. Check if a queue can be sorted into another queue using a stack
// This code is contributed by
// Manish Shaw(manishshaw1)
Output :
Yes
Source
https://www.geeksforgeeks.org/check-queue-can-sorted-another-queue-using-stack/
36
Chapter 8
Tree 1:
Level 0 : 1
Level 1 : 3, 2
Level 2 : 5, 4
Tree 2:
Level 0 : 1
Level 1 : 2, 3
Level 2 : 4, 5
As we can clearly see all the levels of above two binary trees are anagrams of each other,
hence return true.
Naive Approach: Below is the step by step explanation of the naive approach to do this:
37
Chapter 8. Check if all levels of two trees are anagrams or not
C++
38
Chapter 8. Check if all levels of two trees are anagrams or not
39
Chapter 8. Check if all levels of two trees are anagrams or not
Java
40
Chapter 8. Check if all levels of two trees are anagrams or not
left = null;
right = null;
}
}
// Returns true if trees with root1 and root2
// are level by level anagram, else returns false.
static boolean areAnagrams(Node root1, Node root2)
{
// Base Cases
if (root1 == null && root2 == null)
return true;
if (root1 == null || root2 == null)
return false;
// start level order traversal of two trees
// using two queues.
Queue<Node> q1 = new LinkedList<Node>();
Queue<Node> q2 = new LinkedList<Node>();
q1.add(root1);
q2.add(root2);
while (true)
{
// n1 (queue size) indicates number of
// Nodes at current level in first tree
// and n2 indicates number of nodes in
// current level of second tree.
int n1 = q1.size(), n2 = q2.size();
// If n1 and n2 are different
if (n1 != n2)
return false;
// If level order traversal is over
if (n1 == 0)
break;
// Dequeue all Nodes of current level and
// Enqueue all Nodes of next level
ArrayList<Integer> curr_level1 = new
ArrayList<>();
ArrayList<Integer> curr_level2 = new
ArrayList<>();
while (n1 > 0)
{
Node node1 = q1.peek();
q1.remove();
41
Chapter 8. Check if all levels of two trees are anagrams or not
42
Chapter 8. Check if all levels of two trees are anagrams or not
}
}
// This code is contributed by Sumit Ghosh
Output:
Yes
Note: In the above program we are comparing the vectors storing each level of a tree
directly using not equal to function ‘ != ‘ which compares the vectors first on the basis
of their size and then on the basis of their content, hence saving our work of iteratively
comparing the vectors.
Source
https://www.geeksforgeeks.org/check-if-all-levels-of-two-trees-are-anagrams-or-not/
43
Chapter 9
C++
44
Chapter 9. Check if two trees are Mirror
/* A binary tree node has data, pointer to
left child and a pointer to right child */
struct Node
{
int data;
Node* left, *right;
};
/* Given two trees, return true if they are
mirror of each other */
int areMirror(Node* a, Node* b)
{
/* Base case : Both empty */
if (a==NULL && b==NULL)
return true;
// If only one is empty
if (a==NULL || b == NULL)
return false;
/* Both non-empty, compare them recursively
Note that in recursive calls, we pass left
of one tree and right of other tree */
return a->data == b->data &&
areMirror(a->left, b->right) &&
areMirror(a->right, b->left);
}
/* Helper function that allocates a new node */
Node* newNode(int data)
{
Node* node = new Node;
node->data = data;
node->left = node->right = NULL;
return(node);
}
/* Driver program to test areMirror() */
int main()
{
Node *a = newNode(1);
Node *b = newNode(1);
a->left = newNode(2);
a->right = newNode(3);
a->left->left = newNode(4);
a->left->right = newNode(5);
45
Chapter 9. Check if two trees are Mirror
b->left = newNode(3);
b->right = newNode(2);
b->right->left = newNode(5);
b->right->right = newNode(4);
areMirror(a, b)? cout << "Yes" : cout << "No";
return 0;
}
Java
46
Chapter 9. Check if two trees are Mirror
Python3
47
Chapter 9. Check if two trees are Mirror
return True
# If only one is empty
if a is None or b is None:
return False
# Both non-empty, compare them
# recursively. Note that in
# recursive calls, we pass left
# of one tree and right of other tree
return (a.data == b.data and
areMirror(a.left, b.right) and
areMirror(a.right , b.left))
# Driver code
root1 = Node(1)
root2 = Node(1)
root1.left = Node(2)
root1.right = Node(3)
root1.left.left = Node(4)
root1.left.right = Node(5)
root2.left = Node(3)
root2.right = Node(2)
root2.right.left = Node(5)
root2.right.right = Node(4)
if areMirror(root1, root2):
print ("Yes")
else:
print ("No")
# This code is contributed by AshishR
Output :
Yes
48
Chapter 9. Check if two trees are Mirror
Source
https://www.geeksforgeeks.org/check-if-two-trees-are-mirror/
49
Chapter 10
The idea is to use Queue and Stack to check if given N-ary tree are mirror of each other or
not.
Let first n-ary tree be t1 and second n-ary tree is t2. For each node in t1, make stack and
push its connected node in it. Now, for each node in t2, make queue and push its connected
node in it.
Now, for each corresponding node do following:
50
Chapter 10. Check mirror in n-ary tree
b = front of stack;
if (a != b)
return false;
pop element from stack and queue.
51
Chapter 10. Check mirror in n-ary tree
Output:
Yes
Reference: https://practice.geeksforgeeks.org/problems/check-mirror-in-n-ary-tree/0
Source
https://www.geeksforgeeks.org/check-mirror-n-ary-tree/
52
Chapter 11
Check whether a given Binary Tree is Complete or not | Set 1 (Iterative Solution) - Geeks-
forGeeks
Given a Binary Tree, write a function to check whether the given Binary Tree is Complete
Binary Tree or not.
A complete binary tree is a binary tree in which every level, except possibly the last, is
completely filled, and all nodes are as far left as possible. See following examples.
1
/ \
2 3
/
4
1
/ \
2 3
/ \ /
4 5 6
53
Chapter 11. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
1
/ \
2 3
\ / \
4 5 6
1
/ \
2 3
/ \
4 5
The method 2 of level order traversal post can be easily modified to check whether a tree
is Complete or not. To understand the approach, let us first define a term ‘Full Node’. A
node is ‘Full Node’ if both left and right children are not empty (or not NULL).
The approach is to do a level order traversal starting from root. In the traversal, once a
node is found which is NOT a Full Node, all the following nodes must be leaf nodes.
Also, one more thing needs to be checked to handle the below case: If a node has empty left
child, then the right child must be empty.
1
/ \
2 3
\
4
Thanks to Guddu Sharma for suggesting this simple and efficient approach.
C/C++
54
Chapter 11. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
55
Chapter 11. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
{
// If we have seen a non full node, and we see a node
// with non-empty right child, then the given tree is not
// a complete Binary Tree
if(flag == true)
return false;
enQueue(queue, &rear, temp_node->right); // Enqueue Right Child
}
else // If this a non-full node, set the flag as true
flag = true;
}
// If we reach here, then the tree is complete Bianry Tree
return true;
}
/*UTILITY FUNCTIONS*/
struct node** createQueue(int *front, int *rear)
{
struct node **queue =
(struct node **)malloc(sizeof(struct node*)*MAX_Q_SIZE);
*front = *rear = 0;
return queue;
}
void enQueue(struct node **queue, int *rear, struct node *new_node)
{
queue[*rear] = new_node;
(*rear)++;
}
struct node *deQueue(struct node **queue, int *front)
{
(*front)++;
return queue[*front - 1];
}
bool isQueueEmpty(int *front, int *rear)
{
return (*rear == *front);
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
56
Chapter 11. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
/* Let us construct the following Binary Tree which
is not a complete Binary Tree
1
/ \
2 3
/ \ \
4 5 6
*/
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(6);
if ( isCompleteBT(root) == true )
printf ("Complete Binary Tree");
else
printf ("NOT Complete Binary Tree");
return 0;
}
Java
57
Chapter 11. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
58
Chapter 11. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
59
Chapter 11. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
Python
60
Chapter 11. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
61
Chapter 11. Check whether a given Binary Tree is Complete or not | Set 1 (Iterative
Solution)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Time Complexity: O(n) where n is the number of nodes in given Binary Tree
Auxiliary Space: O(n) for queue.
Source
https://www.geeksforgeeks.org/check-if-a-given-binary-tree-is-complete-tree-or-not/
62
Chapter 12
63
Chapter 12. Circular Queue | Set 1 (Introduction and Array Implementation)
In a normal Queue, we can insert elements until queue becomes full. But once queue becomes
full, we can not insert the next element even if there is a space in front of queue.
64
Chapter 12. Circular Queue | Set 1 (Introduction and Array Implementation)
65
Chapter 12. Circular Queue | Set 1 (Introduction and Array Implementation)
{
printf("\nQueue is Full");
return;
}
else if (front == -1) /* Insert First Element */
{
front = rear = 0;
arr[rear] = value;
}
else if (rear == size-1 && front != 0)
{
rear = 0;
arr[rear] = value;
}
else
{
rear++;
arr[rear] = value;
}
}
// Function to delete element from Circular Queue
int Queue::deQueue()
{
if (front == -1)
{
printf("\nQueue is Empty");
return INT_MIN;
}
int data = arr[front];
arr[front] = -1;
if (front == rear)
{
front = -1;
rear = -1;
}
else if (front == size-1)
front = 0;
else
front++;
return data;
}
66
Chapter 12. Circular Queue | Set 1 (Introduction and Array Implementation)
67
Chapter 12. Circular Queue | Set 1 (Introduction and Array Implementation)
q.displayQueue();
q.enQueue(20);
return 0;
}
Output:
Source
https://www.geeksforgeeks.org/circular-queue-set-1-introduction-array-implementation/
68
Chapter 13
69
Chapter 13. Circular Queue | Set 2 (Circular Linked List Implementation)
Source
https://www.geeksforgeeks.org/circular-queue-set-2-circular-linked-list-implementation/
70
Chapter 14
If we observe the above problem closely, we can notice that the lengths of the ropes which
are picked first are included more than once in total cost. Therefore, the idea is to connect
smallest two ropes first and recur for remaining ropes. This approach is similar to Huffman
Coding. We put smallest ropes down the tree so that they can be repeated multiple times
rather than the longer ropes.
Following is complete algorithm for finding the minimum cost for connecting n ropes.
Let there be n ropes of lengths stored in an array len[0..n-1]
1) Create a min heap and insert all lengths into the min heap.
2) Do following while number of elements in min heap is not one.
……a) Extract the minimum and second minimum from min heap
……b) Add the above two extracted values and insert the added value to the min-heap.
……c) Maintain a variable for total cost and keep incrementing it by the sum of extracted
71
Chapter 14. Connect n ropes with minimum cost
values.
3) Return the value of this total cost.
Following is C++ implementation of above algorithm.
72
Chapter 14. Connect n ropes with minimum cost
smallest = right;
if (smallest != idx)
{
swapMinHeapNode(&minHeap->harr[smallest], &minHeap->harr[idx]);
minHeapify(minHeap, smallest);
}
}
// A utility function to check if size of heap is 1 or not
int isSizeOne(struct MinHeap* minHeap)
{
return (minHeap->size == 1);
}
// A standard function to extract minimum value node from heap
int extractMin(struct MinHeap* minHeap)
{
int temp = minHeap->harr[0];
minHeap->harr[0] = minHeap->harr[minHeap->size - 1];
--minHeap->size;
minHeapify(minHeap, 0);
return temp;
}
// A utility function to insert a new node to Min Heap
void insertMinHeap(struct MinHeap* minHeap, int val)
{
++minHeap->size;
int i = minHeap->size - 1;
while (i && (val < minHeap->harr[(i - 1)/2]))
{
minHeap->harr[i] = minHeap->harr[(i - 1)/2];
i = (i - 1)/2;
}
minHeap->harr[i] = val;
}
// A standard funvtion to build min heap
void buildMinHeap(struct MinHeap* minHeap)
{
int n = minHeap->size - 1;
int i;
for (i = (n - 1) / 2; i >= 0; --i)
minHeapify(minHeap, i);
}
// Creates a min heap of capacity equal to size and inserts all values
73
Chapter 14. Connect n ropes with minimum cost
Output:
74
Chapter 14. Connect n ropes with minimum cost
Time Complexity: Time complexity of the algorithm is O(nLogn) assuming that we use a
O(nLogn) sorting algorithm. Note that heap operations like insert and extract take O(Logn)
time.
Algorithmic Paradigm: Greedy Algorithm
A simple implementation with STL in C++
Following is a simple implementation that uses priority_queue available in STL. Thanks to
Pango89 for providing below code.
C++
#include<iostream>
#include<queue>
using namespace std;
int minCost(int arr[], int n)
{
// Create a priority queue ( http://www.cplusplus.com/reference/queue/priority_queue/ )
// By default 'less' is used which is for decreasing order
// and 'greater' is used for increasing order
priority_queue< int, vector<int>, greater<int> > pq(arr, arr+n);
// Initialize result
int res = 0;
// While size of priority queue is more than 1
while (pq.size() > 1)
{
// Extract shortest two ropes from pq
int first = pq.top();
pq.pop();
int second = pq.top();
pq.pop();
// Connect the ropes: update result and
// insert the new rope to pq
res += first + second;
pq.push(first + second);
}
return res;
}
// Driver program to test above function
75
Chapter 14. Connect n ropes with minimum cost
int main()
{
int len[] = {4, 3, 2, 6};
int size = sizeof(len)/sizeof(len[0]);
cout << "Total cost for connecting ropes is " << minCost(len, size);
return 0;
}
Java
76
Chapter 14. Connect n ropes with minimum cost
Output:
This article is compiled by Abhishek. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above
Improved By : JAGRITIBANSAL, AbhijeetSrivastava
Source
https://www.geeksforgeeks.org/connect-n-ropes-minimum-cost/
77
Chapter 15
Construct Complete Binary Tree from its Linked List Representation - GeeksforGeeks
Given Linked List Representation of Complete Binary Tree, construct the Binary tree. A
complete binary tree can be represented in an array in the following approach.
If root node is stored at index i, its left, and right children are stored at indices 2*i+1, 2*i+2
respectively.
Suppose tree is represented by a linked list in same way, how do we convert this into normal
linked representation of binary tree where every node has data, left and right pointers? In
the linked list representation, we cannot directly access the children of the current node
unless we traverse the list.
We are mainly given level order traversal in sequential access form. We know head of linked
list is always is root of the tree. We take the first node as root and we also know that the
78
Chapter 15. Construct Complete Binary Tree from its Linked List Representation
next two nodes are left and right children of root. So we know partial Binary Tree. The idea
is to do Level order traversal of the partially built Binary Tree using queue and traverse the
linked list at the same time. At every step, we take the parent node from queue, make next
two nodes of linked list as children of the parent node, and enqueue the next two nodes to
queue.
1. Create an empty queue.
2. Make the first node of the list as root, and enqueue it to the queue.
3. Until we reach the end of the list, do the following.
………a. Dequeue one node from the queue. This is the current parent.
………b. Traverse two nodes in the list, add them as children of the current parent.
………c. Enqueue the two nodes into the queue.
Below is the code which implements the same in C++.
C++
// C++ program to create a Complete Binary tree from its Linked List
// Representation
#include <iostream>
#include <string>
#include <queue>
using namespace std;
// Linked list node
struct ListNode
{
int data;
ListNode* next;
};
// Binary tree node structure
struct BinaryTreeNode
{
int data;
BinaryTreeNode *left, *right;
};
// Function to insert a node at the beginning of the Linked List
void push(struct ListNode** head_ref, int new_data)
{
// allocate node and assign data
struct ListNode* new_node = new ListNode;
new_node->data = new_data;
// link the old list off the new node
new_node->next = (*head_ref);
// move the head to point to the new node
79
Chapter 15. Construct Complete Binary Tree from its Linked List Representation
(*head_ref) = new_node;
}
// method to create a new binary tree node from the given data
BinaryTreeNode* newBinaryTreeNode(int data)
{
BinaryTreeNode *temp = new BinaryTreeNode;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// converts a given linked list representing a complete binary tree into the
// linked representation of binary tree.
void convertList2Binary(ListNode *head, BinaryTreeNode* &root)
{
// queue to store the parent nodes
queue<BinaryTreeNode *> q;
// Base Case
if (head == NULL)
{
root = NULL; // Note that root is passed by reference
return;
}
// 1.) The first node is always the root node, and add it to the queue
root = newBinaryTreeNode(head->data);
q.push(root);
// advance the pointer to the next node
head = head->next;
// until the end of linked list is reached, do the following steps
while (head)
{
// 2.a) take the parent node from the q and remove it from q
BinaryTreeNode* parent = q.front();
q.pop();
// 2.c) take next two nodes from the linked list. We will add
// them as children of the current parent node in step 2.b. Push them
// into the queue so that they will be parents to the future nodes
BinaryTreeNode *leftChild = NULL, *rightChild = NULL;
leftChild = newBinaryTreeNode(head->data);
q.push(leftChild);
head = head->next;
if (head)
80
Chapter 15. Construct Complete Binary Tree from its Linked List Representation
{
rightChild = newBinaryTreeNode(head->data);
q.push(rightChild);
head = head->next;
}
// 2.b) assign the left and right children of parent
parent->left = leftChild;
parent->right = rightChild;
}
}
// Utility function to traverse the binary tree after conversion
void inorderTraversal(BinaryTreeNode* root)
{
if (root)
{
inorderTraversal( root->left );
cout << root->data << " ";
inorderTraversal( root->right );
}
}
// Driver program to test above functions
int main()
{
// create a linked list shown in above diagram
struct ListNode* head = NULL;
push(&head, 36); /* Last node of Linked List */
push(&head, 30);
push(&head, 25);
push(&head, 15);
push(&head, 12);
push(&head, 10); /* First node of Linked List */
BinaryTreeNode *root;
convertList2Binary(head, root);
cout << "Inorder Traversal of the constructed Binary Tree is: \n";
inorderTraversal(root);
return 0;
}
Java
// Java program to create complete Binary Tree from its Linked List
// representation
81
Chapter 15. Construct Complete Binary Tree from its Linked List Representation
82
Chapter 15. Construct Complete Binary Tree from its Linked List Representation
83
Chapter 15. Construct Complete Binary Tree from its Linked List Representation
// parent
parent.left = leftChild;
parent.right = rightChild;
}
return node;
}
// Utility function to traverse the binary tree
// after conversion
void inorderTraversal(BinaryTreeNode node)
{
if (node != null)
{
inorderTraversal(node.left);
System.out.print(node.data + " ");
inorderTraversal(node.right);
}
}
// Driver program to test above functions
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.push(36); /* Last node of Linked List */
tree.push(30);
tree.push(25);
tree.push(15);
tree.push(12);
tree.push(10); /* First node of Linked List */
BinaryTreeNode node = tree.convertList2Binary(tree.root);
System.out.println("Inorder Traversal of the"+
" constructed Binary Tree is:");
tree.inorderTraversal(node);
}
}
// This code has been contributed by Mayank Jaiswal
Python
84
Chapter 15. Construct Complete Binary Tree from its Linked List Representation
85
Chapter 15. Construct Complete Binary Tree from its Linked List Representation
86
Chapter 15. Construct Complete Binary Tree from its Linked List Representation
print "Inorder Traversal of the contructed Binary Tree is:"
conv.inorderTraversal(conv.root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Time Complexity: Time complexity of the above solution is O(n) where n is the number
of nodes.
This article is compiled by Ravi Chandra Enaganti. Please write comments if you find
anything incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/given-linked-list-representation-of-complete-tree-convert-it-to-linked-representation
87
Chapter 16
88
Chapter 16. Deque | Set 1 (Introduction and Applications)
Deque in Java
Deque in Python
Implementation:
A Deque can be implemented either using a doubly linked list or circular array. In both
implementation, we can implement all operations in O(1) time. We will soon be discussing
C/C++ implementation of Deque Data structure.
Please write comments if you find the above codes/algorithms incorrect, or find other ways
to solve the same problem.
Improved By : TanmayS
Source
https://www.geeksforgeeks.org/deque-set-1-introduction-applications/
89
Chapter 17
Input : N = 3, M = 4
mat[][] = {
0, 0, 0, 1,
0, 0, 1, 1,
0, 1, 1, 0
}
Output : 3 2 1 0
2 1 0 0
1 0 0 1
C++
90
Chapter 17. Distance of nearest cell having 1 in a binary matrix
91
Chapter 17. Distance of nearest cell having 1 in a binary matrix
int mat[N][M] =
{
0, 0, 0, 1,
0, 0, 1, 1,
0, 1, 1, 0
};
printDistance(mat);
return 0;
}
Java
92
Chapter 17. Distance of nearest cell having 1 in a binary matrix
Math.min(ans[i][j],
Math.abs(i-k)
+ Math.abs(j-l));
}
}
// Printing the answer.
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
System.out.print( ans[i][j] + " ");
System.out.println();
}
}
// Driven Program
public static void main (String[] args)
{
int mat[][] = { {0, 0, 0, 1},
{0, 0, 1, 1},
{0, 1, 1, 0} };
printDistance(mat);
}
}
// This code is contributed by anuj_67.
C#
93
Chapter 17. Distance of nearest cell having 1 in a binary matrix
PHP
94
Chapter 17. Distance of nearest cell having 1 in a binary matrix
<?php
// PHP program to find distance of nearest
// cell having 1 in a binary matrix.
$N = 3;
$M = 4;
// Print the distance of nearest cell
// having 1 for each cell.
function printDistance( $mat)
{
global $N,$M;
$ans = array(array());
// Initalize the answer
// matrix with INT_MAX.
for($i = 0; $i < $N; $i++)
for ( $j = 0; $j < $M; $j++)
$ans[$i][$j] = PHP_INT_MAX;
// For each cell
for ( $i = 0; $i < $N; $i++)
for ( $j = 0; $j < $M; $j++)
{
// Traversing the whole matrix
// to find the minimum distance.
for ($k = 0; $k < $N; $k++)
for ( $l = 0; $l < $M; $l++)
{
// If cell contain 1, check
// for minimum distance.
if ($mat[$k][$l] == 1)
$ans[$i][$j] = min($ans[$i][$j],
abs($i-$k) + abs($j - $l));
}
}
// Printing the answer.
for ( $i = 0; $i < $N; $i++)
{
for ( $j = 0; $j < $M; $j++)
echo $ans[$i][$j] , " ";
echo "\n";
}
}
95
Chapter 17. Distance of nearest cell having 1 in a binary matrix
Output:
3 2 1 0
2 1 0 0
1 0 0 1
1. Create a graph with values assigned from 1 to M*N to all vertices. The purpose is to
store position and adjacent information.
2. Create an empty queue.
3. Traverse all matrix elements and insert positions of all 1s in queue.
4. Now do a BFS traversal of graph using above created queue. In BFS, we first explore
immediate adjacent of all 1’s, then adjacent of adjacent, and so on. Therefore we find
minimum distance.
96
Chapter 17. Distance of nearest cell having 1 in a binary matrix
{
private:
vector<int> g[MAX];
int n,m;
public:
graph(int a, int b)
{
n = a;
m = b;
}
// Function to create graph with N*M nodes
// considering each cell as a node and each
// boundry as an edge.
void createGraph()
{
int k = 1; // A number to be assigned to a cell
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= m; j++)
{
// If last row, then add edge on right side.
if (i == n)
{
// If not bottom right cell.
if (j != m)
{
g[k].push_back(k+1);
g[k+1].push_back(k);
}
}
// If last column, then add edge toward down.
else if (j == m)
{
g[k].push_back(k+m);
g[k+m].push_back(k);
}
// Else make edge in all four direction.
else
{
g[k].push_back(k+1);
g[k+1].push_back(k);
g[k].push_back(k+m);
g[k+m].push_back(k);
97
Chapter 17. Distance of nearest cell having 1 in a binary matrix
}
k++;
}
}
}
// BFS function to find minimum distance
void bfs(bool visit[], int dist[], queue<int> q)
{
while (!q.empty())
{
int temp = q.front();
q.pop();
for (int i = 0; i < g[temp].size(); i++)
{
if (visit[g[temp][i]] != 1)
{
dist[g[temp][i]] =
min(dist[g[temp][i]], dist[temp]+1);
q.push(g[temp][i]);
visit[g[temp][i]] = 1;
}
}
}
}
// Printing the solution.
void print(int dist[])
{
for (int i = 1, c = 1; i <= n*m; i++, c++)
{
cout << dist[i] << " ";
if (c%m == 0)
cout << endl;
}
}
};
// Find minimum distance
void findMinDistance(bool mat[N][M])
{
// Creating a graph with nodes values assigned
// from 1 to N x M and matrix adjacent.
graph g1(N, M);
98
Chapter 17. Distance of nearest cell having 1 in a binary matrix
g1.createGraph();
// To store minimum distance
int dist[MAX];
// To mark each node as visited or not in BFS
bool visit[MAX] = { 0 };
// Initalising the value of distance and visit.
for (int i = 1; i <= M*N; i++)
{
dist[i] = INT_MAX;
visit[i] = 0;
}
// Inserting nodes whose value in matrix
// is 1 in the queue.
int k = 1;
queue<int> q;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < M; j++)
{
if (mat[i][j] == 1)
{
dist[k] = 0;
visit[k] = 1;
q.push(k);
}
k++;
}
}
// Calling for Bfs with given Queue.
g1.bfs(visit, dist, q);
// Printing the solution.
g1.print(dist);
}
// Driven Progarm
int main()
{
bool mat[N][M] =
{
0, 0, 0, 1,
0, 0, 1, 1,
0, 1, 1, 0
99
Chapter 17. Distance of nearest cell having 1 in a binary matrix
};
findMinDistance(mat);
return 0;
}
Output :
3 2 1 0
2 1 0 0
1 0 0 1
Source
https://www.geeksforgeeks.org/distance-nearest-cell-1-binary-matrix/
100
Chapter 18
FIFO (First-In-First-Out)
approach in Programming
• There is a ticket counter where people come, take tickets and go.
• People enter a line (queue) to get to the Ticket Counter in an organized manner.
• The person to enter the queue first, will get the ticket first and leave the queue.
• The person entering the queue next will get the ticket after the person in front of him
• In this way, the person entering the queue last will the tickets last
101
Chapter 18. FIFO (First-In-First-Out) approach in Programming
• Therefore, the First person to enter the queue gets the ticket first and the Last person
to enter the queue gets the ticket last.
1. Data Structures
Certain data structures like Queue and other variants of Queue uses FIFO approach
for processing data.
2. Disk scheduling
Disk controllers can use the FIFO as a disk scheduling algorithm to determine the
order in which to service disk I/O requests.
3. Communications and networking
Communication network bridges, switches and routers used in computer networks use
FIFOs to hold data packets en route to their next destination.
102
Chapter 18. FIFO (First-In-First-Out) approach in Programming
// To view the head of queue
int head = q.peek();
System.out.println("head of queue-" + head);
// Rest all methods of collection interface,
// Like size and contains can be used with this
// implementation.
int size = q.size();
System.out.println("Size of queue-" + size);
}
}
Output:
Elements of queue-[0, 1, 2, 3, 4]
removed element-0
[1, 2, 3, 4]
head of queue-1
Size of queue-4
Source
https://www.geeksforgeeks.org/fifo-first-in-first-out-approach-in-programming/
103
Chapter 19
Input : 4
/ \
2 -5
/ \ /\
-1 3 -2 6
Output: 6
Explanation :
Sum of all nodes of 0'th level is 4
Sum of all nodes of 1'th level is -3
Sum of all nodes of 0'th level is 6
Hence maximum sum is 6
Input : 1
/ \
2 3
/ \ \
4 5 8
/ \
6 7
Output : 17
This problem is a variation of maximum width problem. The idea is to do level order
traversal of tree. While doing traversal, process nodes of different level separately. For
104
Chapter 19. Find maximum level sum in Binary Tree
every level being processed, compute sum of nodes in the level and keep track of maximum
sum.
105
Chapter 19. Find maximum level sum in Binary Tree
106
Chapter 19. Find maximum level sum in Binary Tree
Output :
Source
https://www.geeksforgeeks.org/find-level-maximum-sum-binary-tree/
107
Chapter 20
Input :
3
/ \
4 6
/ \ / \
-1 -2 5 10
\
8
Output : 14
Vertical level having nodes 6 and 8 has maximum
vertical sum 14.
Input :
1
/ \
5 8
/ \ \
2 -6 3
\ /
-1 -4
\
9
108
Chapter 20. Find maximum vertical sum in binary tree
Output : 4
A simple solution is to first find vertical level sum of each level starting from minimum
vertical level to maximum vertical level. Finding sum of one vertical level takes O(n) time.
In worst case time complexity of this solution is O(n^2).
An efficient solution is to do level order traversal of given binary tree and update vertical
level sum of each level while doing the traversal. After finding vertical sum of each level
find maximum vertical sum from these values.
Below is the implementation of above approach:
109
Chapter 20. Find maximum vertical sum in binary tree
int currLev;
// Queue to perform level order traversal.
// Each element of queue is a pair of node
// and its vertical level.
queue<pair<Node*, int> > q;
q.push({ root, 0 });
while (!q.empty()) {
// Extract node at front of queue
// and its vertical level.
root = q.front().first;
currLev = q.front().second;
q.pop();
// Update vertical level sum of
// vertical level to which
// current node belongs to.
verSum[currLev] += root->data;
if (root->left)
q.push({ root->left, currLev - 1 });
if (root->right)
q.push({ root->right, currLev + 1 });
}
// Find maximum vertical level sum.
for (auto it : verSum)
maxSum = max(maxSum, it.second);
return maxSum;
}
// Driver Program to test above functions
int main()
{
/*
3
/ \
4 6
/ \ / \
-1 -2 5 10
\
8
*/
110
Chapter 20. Find maximum vertical sum in binary tree
Output:
14
Source
https://www.geeksforgeeks.org/find-maximum-vertical-sum-in-binary-tree/
111
Chapter 21
10
/ \
2 6
/ \ \
8 4 5
Solution: The idea is to do level order traversal of given Binary Tree. When we find the
given key, we just check if the next node in level order traversal is of same level, if yes, we
return the next node, otherwise return NULL.
C++
112
Chapter 21. Find next right node of a given key
113
Chapter 21. Find next right node of a given key
}
if (node->right != NULL)
{
qn.push(node->right);
ql.push(level+1);
}
}
// We reach here if given key x doesn't exist in tree
return NULL;
}
// Utility function to create a new tree node
node* newNode(int key)
{
node *temp = new node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to test above functions
void test(node *root, int k)
{
node *nr = nextRight(root, k);
if (nr != NULL)
cout << "Next Right of " << k << " is " << nr->key << endl;
else
cout << "No next right node found for " << k << endl;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree given in the above example
node *root = newNode(10);
root->left = newNode(2);
root->right = newNode(6);
root->right->right = newNode(5);
root->left->left = newNode(8);
root->left->right = newNode(4);
test(root, 10);
test(root, 2);
test(root, 6);
test(root, 5);
test(root, 8);
test(root, 4);
114
Chapter 21. Find next right node of a given key
return 0;
}
Java
115
Chapter 21. Find next right node of a given key
116
Chapter 21. Find next right node of a given key
Python
117
Chapter 21. Find next right node of a given key
level = 0
# Enqueue root and its level
qn.append(root)
q1.append(level)
# Standard BFS loop
while(len(qn) > 0):
# Dequeu an node from qn and its level from q1
node = qn.pop(0)
level = q1.pop(0)
# If the dequeued node has the given key k
if node.key == k :
# If there are no more items in queue or given
# node is the rightmost node of its level,
# then return None
if (len(q1) == 0 or q1[0] != level):
return None
# Otherwise return next node from queue of nodes
return qn[0]
# Standard BFS steps: enqueue children of this node
if node.left is not None:
qn.append(node.left)
q1.append(level+1)
if node.right is not None:
qn.append(node.right)
q1.append(level+1)
# We reach here if given key x doesn't exist in tree
return None
def test(root, k):
nr = nextRight(root, k)
if nr is not None:
print "Next Right of " + str(k) + " is " + str(nr.key)
else:
print "No next right node found for " + str(k)
# Driver program to test above function
root = Node(10)
root.left = Node(2)
118
Chapter 21. Find next right node of a given key
root.right = Node(6)
root.right.right = Node(5)
root.left.left = Node(8)
root.left.right = Node(4)
test(root, 10)
test(root, 2)
test(root, 6)
test(root, 5)
test(root, 8)
test(root, 4)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
Output:
Time Complexity: The above code is a simple BFS traversal code which visits every
enqueue and dequeues a node at most once. Therefore, the time complexity is O(n) where
n is the number of nodes in the given binary tree.
Exercise: Write a function to find left node of a given node. If there is no node on the left
side, then return NULL.
Source
https://www.geeksforgeeks.org/find-next-right-node-of-a-given-key/
119
Chapter 22
Find the first circular tour that visits all petrol pumps - GeeksforGeeks
Suppose there is a circle. There are n petrol pumps on that circle. You are given two sets
of data.
1. The amount of petrol that every petrol pump has.
2. Distance from that petrol pump to the next petrol pump.
Calculate the first point from where a truck will be able to complete the circle (The truck
will stop at each petrol pump and it has infinite capacity). Expected time complexity is
O(n). Assume for 1 litre petrol, the truck can go 1 unit of distance.
For example, let there be 4 petrol pumps with amount of petrol and distance to next petrol
pump value pairs as {4, 6}, {6, 5}, {7, 3} and {4, 5}. The first point from where truck can
make a circular tour is 2nd petrol pump. Output should be “start = 1” (index of 2nd petrol
pump).
A Simple Solution is to consider every petrol pumps as starting point and see if there is
a possible tour. If we find a starting point with feasible solution, we return that starting
point. The worst case time complexity of this solution is O(n^2).
We can use a Queue to store the current tour. We first enqueue first petrol pump to the
queue, we keep enqueueing petrol pumps till we either complete the tour, or current amount
of petrol becomes negative. If the amount becomes negative, then we keep dequeueing petrol
pumps till the current amount becomes positive or queue becomes empty.
Instead of creating a separate queue, we use the given array itself as queue. We maintain
two index variables start and end that represent rear and front of queue.
C/C++
120
Chapter 22. Find the first circular tour that visits all petrol pumps
// A petrol pump has petrol and distance to next petrol pump
struct petrolPump
{
int petrol;
int distance;
};
// The function returns starting point if there is a possible solution,
// otherwise returns -1
int printTour(struct petrolPump arr[], int n)
{
// Consider first petrol pump as a starting point
int start = 0;
int end = 1;
int curr_petrol = arr[start].petrol - arr[start].distance;
/* Run a loop while all petrol pumps are not visited.
And we have reached first petrol pump again with 0 or more petrol */
while (end != start || curr_petrol < 0)
{
// If curremt amount of petrol in truck becomes less than 0, then
// remove the starting petrol pump from tour
while (curr_petrol < 0 && start != end)
{
// Remove starting petrol pump. Change start
curr_petrol -= arr[start].petrol - arr[start].distance;
start = (start + 1)%n;
// If 0 is being considered as start again, then there is no
// possible solution
if (start == 0)
return -1;
}
// Add a petrol pump to current tour
curr_petrol += arr[end].petrol - arr[end].distance;
end = (end + 1)%n;
}
// Return starting point
return start;
}
// Driver program to test above functions
int main()
121
Chapter 22. Find the first circular tour that visits all petrol pumps
{
struct petrolPump arr[] = {{6, 4}, {3, 6}, {7, 3}};
int n = sizeof(arr)/sizeof(arr[0]);
int start = printTour(arr, n);
(start == -1)? printf("No solution"): printf("Start = %d", start);
return 0;
}
Java
122
Chapter 22. Find the first circular tour that visits all petrol pumps
Python
123
Chapter 22. Find the first circular tour that visits all petrol pumps
Output:
start = 2
124
Chapter 22. Find the first circular tour that visits all petrol pumps
Time Complexity: Seems to be more than linear at first look. If we consider the items
between start and end as part of a circular queue, we can observe that every item is enqueued
at most two times to the queue. The total number of operations is proportional to total
number of enqueue operations. Therefore the time complexity is O(n).
Auxiliary Space: O(1)
Source
https://www.geeksforgeeks.org/find-a-tour-that-visits-all-stations/
125
Chapter 23
1. Create an empty DLL. Also create two arrays inDLL[] and repeated[] of size 256.
inDLL is an array of pointers to DLL nodes. repeated[] is a boolean array, repeated[x]
is true if x is repeated two or more times, otherwise false. inDLL[x] contains pointer
to a DLL node if character x is present in DLL, otherwise NULL.
2. Initialize all entries of inDLL[] as NULL and repeated[] as false.
3. To get the first non-repeating character, return character at head of DLL.
4. Following are steps to process a new character ‘x’ in stream.
126
Chapter 23. Find the first non-repeating character from a stream of characters
Note that appending a new node to DLL is O(1) operation if we maintain tail pointer.
Removing a node from DLL is also O(1). So both operations, addition of new character and
finding first non-repeating character take O(1) time.
C/C++
127
Chapter 23. Find the first non-repeating character from a stream of characters
// Note that the function may change head and tail pointers,
// that is why pointers to these pointers are passed.
void removeNode(struct node **head_ref, struct node **tail_ref,
struct node *temp)
{
if (*head_ref == NULL)
return;
if (*head_ref == temp)
*head_ref = (*head_ref)->next;
if (*tail_ref == temp)
*tail_ref = (*tail_ref)->prev;
if (temp->next != NULL)
temp->next->prev = temp->prev;
if (temp->prev != NULL)
temp->prev->next = temp->next;
delete(temp);
}
void findFirstNonRepeating()
{
// inDLL[x] contains pointer to a DLL node if x is present
// in DLL. If x is not present, then inDLL[x] is NULL
struct node *inDLL[MAX_CHAR];
// repeated[x] is true if x is repeated two or more times.
// If x is not seen so far or x is seen only once. then
// repeated[x] is false
bool repeated[MAX_CHAR];
// Initialize the above two arrays
struct node *head = NULL, *tail = NULL;
for (int i = 0; i < MAX_CHAR; i++)
{
inDLL[i] = NULL;
repeated[i] = false;
}
// Let us consider following stream and see the process
char stream[] = "geeksforgeeksandgeeksquizfor";
for (int i = 0; stream[i]; i++)
{
char x = stream[i];
cout << "Reading " << x << " from stream n";
// We process this character only if it has not occurred
// or occurred only once. repeated[x] is true if x is
128
Chapter 23. Find the first non-repeating character from a stream of characters
Java
129
Chapter 23. Find the first non-repeating character from a stream of characters
130
Chapter 23. Find the first non-repeating character from a stream of characters
}
//This code is contributed by Sumit Ghosh
Python
Output:
131
Chapter 23. Find the first non-repeating character from a stream of characters
132
Chapter 23. Find the first non-repeating character from a stream of characters
This article is contributed by Amit Jain. Please write comments if you find anything
incorrect, or you want to share more information about the topic discussed above.
Source
https://www.geeksforgeeks.org/find-first-non-repeating-character-stream-characters/
133
Chapter 24
134
Chapter 24. Find the largest multiple of 3 | Set 1 (Using Queue)
n = 100.a + 10.b + c
Since (10^x)%3 is 1 for any x, the above expression gives the same remainder as following
expression
1.a + 1.b + c
135
Chapter 24. Find the largest multiple of 3 | Set 1 (Using Queue)
// A queue node
typedef struct Queue
{
int front;
int rear;
int capacity;
int* array;
} Queue;
// A utility function to create a queue with given capacity
Queue* createQueue( int capacity )
{
Queue* queue = (Queue *) malloc (sizeof(Queue));
queue->capacity = capacity;
queue->front = queue->rear = -1;
queue->array = (int *) malloc (queue->capacity * sizeof(int));
return queue;
}
// A utility function to check if queue is empty
int isEmpty (Queue* queue)
{
return queue->front == -1;
}
// A function to add an item to queue
void Enqueue (Queue* queue, int item)
{
queue->array[ ++queue->rear ] = item;
if ( isEmpty(queue) )
++queue->front;
}
// A function to remove an item from queue
int Dequeue (Queue* queue)
{
int item = queue->array[ queue->front ];
if( queue->front == queue->rear )
queue->front = queue->rear = -1;
else
queue->front++;
return item;
}
// A utility function to print array contents
void printArr (int* arr, int size)
136
Chapter 24. Find the largest multiple of 3 | Set 1 (Using Queue)
{
int i;
for (i = 0; i< size; ++i)
printf ("%d ", arr[i]);
}
/* Following two functions are needed for library function qsort().
Refer following link for help of qsort()
http://www.cplusplus.com/reference/clibrary/cstdlib/qsort/ */
int compareAsc( const void* a, const void* b )
{
return *(int*)a > *(int*)b;
}
int compareDesc( const void* a, const void* b )
{
return *(int*)a < *(int*)b;
}
// This function puts all elements of 3 queues in the auxiliary array
void populateAux (int* aux, Queue* queue0, Queue* queue1,
Queue* queue2, int* top )
{
// Put all items of first queue in aux[]
while ( !isEmpty(queue0) )
aux[ (*top)++ ] = Dequeue( queue0 );
// Put all items of second queue in aux[]
while ( !isEmpty(queue1) )
aux[ (*top)++ ] = Dequeue( queue1 );
// Put all items of third queue in aux[]
while ( !isEmpty(queue2) )
aux[ (*top)++ ] = Dequeue( queue2 );
}
// The main function that finds the largest possible multiple of
// 3 that can be formed by arr[] elements
int findMaxMultupleOf3( int* arr, int size )
{
// Step 1: sort the array in non-decreasing order
qsort( arr, size, sizeof( int ), compareAsc );
// Create 3 queues to store numbers with remainder 0, 1
// and 2 respectively
Queue* queue0 = createQueue( size );
Queue* queue1 = createQueue( size );
Queue* queue2 = createQueue( size );
137
Chapter 24. Find the largest multiple of 3 | Set 1 (Using Queue)
// Step 2 and 3 get the sum of numbers and place them in
// corresponding queues
int i, sum;
for ( i = 0, sum = 0; i < size; ++i )
{
sum += arr[i];
if ( (arr[i] % 3) == 0 )
Enqueue( queue0, arr[i] );
else if ( (arr[i] % 3) == 1 )
Enqueue( queue1, arr[i] );
else
Enqueue( queue2, arr[i] );
}
// Step 4.2: The sum produces remainder 1
if ( (sum % 3) == 1 )
{
// either remove one item from queue1
if ( !isEmpty( queue1 ) )
Dequeue( queue1 );
// or remove two items from queue2
else
{
if ( !isEmpty( queue2 ) )
Dequeue( queue2 );
else
return 0;
if ( !isEmpty( queue2 ) )
Dequeue( queue2 );
else
return 0;
}
}
// Step 4.3: The sum produces remainder 2
else if ((sum % 3) == 2)
{
// either remove one item from queue2
if ( !isEmpty( queue2 ) )
Dequeue( queue2 );
// or remove two items from queue1
else
{
if ( !isEmpty( queue1 ) )
Dequeue( queue1 );
138
Chapter 24. Find the largest multiple of 3 | Set 1 (Using Queue)
else
return 0;
if ( !isEmpty( queue1 ) )
Dequeue( queue1 );
else
return 0;
}
}
int aux[size], top = 0;
// Empty all the queues into an auxiliary array.
populateAux (aux, queue0, queue1, queue2, &top);
// sort the array in non-increasing order
qsort (aux, top, sizeof( int ), compareDesc);
// print the result
printArr (aux, top);
return top;
}
// Driver program to test above functions
int main()
{
int arr[] = {8, 1, 7, 6, 0};
int size = sizeof(arr)/sizeof(arr[0]);
if (findMaxMultupleOf3( arr, size ) == 0)
printf( "Not Possible" );
return 0;
}
Find the largest multiple of 3 | Set 2 (In O(n) time and O(1) space)
139
Chapter 24. Find the largest multiple of 3 | Set 1 (Using Queue)
Source
https://www.geeksforgeeks.org/find-the-largest-number-multiple-of-3/
140
Chapter 25
Naive Approach: Run two loops. In the outer loop, take all subarrays(windows) of size
k. In the inner loop, get the first negative integer of the current subarray(window).
C++
141
Chapter 25. First negative integer in every window of size k
Python
142
Chapter 25. First negative integer in every window of size k
Output :
-1 -1 -7 -15 -15 0
Time Complexity : The outer loop runs n-k+1 times and the inner loop runs k times for
every iteration of outer loop. So time complexity is O((n-k+1)*k) which can also be written
as O(nk) when k is comparitively much smaller than n, otherwise when k tends to reach n,
complexity becomes O(k).
Efficient Approach: It is a variation of the problem of Sliding Window Maximum.
We create a Dequeue, Di of capacity k, that stores only useful elements of current window
143
Chapter 25. First negative integer in every window of size k
144
Chapter 25. First negative integer in every window of size k
Output:
-1 -1 -7 -15 -15 0
Source
https://www.geeksforgeeks.org/first-negative-integer-every-window-size-k/
145
Chapter 26
Create a data structure kQueues that represents k queues. Implementation of kQueues should
use only one array, i.e., k queues should use the same array for storing elements. Following
functions must be supported by kQueues.
enqueue(int x, int qn) –> adds x to queue number ‘qn’ where qn is from 0 to k-1
dequeue(int qn) –> deletes an element from queue number ‘qn’ where qn is from 0 to k-1
146
Chapter 26. How to efficiently implement k Queues in a single array?
2) rear[]: This is of size k and stores indexes of rear elements in all queues.
2) next[]: This is of size n and stores indexes of next item for all items in array arr[].
Here arr[] is actual array that stores k stacks.
Together with k queues, a stack of free slots in arr[] is also maintained. The top of this stack
is stored in a variable ‘free’.
All entries in front[] are initialized as -1 to indicate that all queues are empty. All entries
next[i] are initialized as i+1 because all slots are free initially and pointing to next slot. Top
of free stack, ‘free’ is initialized as 0.
Following is C++ implementation of the above idea.
147
Chapter 26. How to efficiently implement k Queues in a single array?
148
Chapter 26. How to efficiently implement k Queues in a single array?
149
Chapter 26. How to efficiently implement k Queues in a single array?
Output:
Source
https://www.geeksforgeeks.org/efficiently-implement-k-queues-single-array/
150
Chapter 27
Implement PriorityQueue
through Comparator in Java
Constructors :
Parameters:
capacity - the initial capacity for this priority queue
comparator - the comparator that will be used to order this priority queue.
If null, the natural ordering of the elements will be used.
151
Chapter 27. Implement PriorityQueue through Comparator in Java
Sample code provided illustrates students with high priority(based on cgpa) are served before
the students having low cgpa.
152
Chapter 27. Implement PriorityQueue through Comparator in Java
return 1;
else if (s1.cgpa > s2.cgpa)
return -1;
return 0;
}
}
class Student {
public String name;
public double cgpa;
// A parameterized student constructor
public Student(String name, double cgpa) {
this.name = name;
this.cgpa = cgpa;
}
public String getName() {
return name;
}
}
Output:
Note : This type of Priority queue is preferred in scenarios where customized ordering is
required, i.e when one wants a different sorting order, then one can define its own way of
comparing instances. Comparator can be implemented if there is a more complex comparing
algorithm, e.g. multiple fields and so on.
Source
https://www.geeksforgeeks.org/implement-priorityqueue-comparator-java/
153
Chapter 28
Now, deque can be used to implement a stack and queue. One simply needs to
understand how deque can made to work as a stack or a queue.
The functions of deque to tweak them to work as stack and queue are list below.
154
Chapter 28. Implement Stack and Queue using Deque
Examples: Stack
Input : Stack : 1 2 3
Push(4)
Output : Stack : 1 2 3 4
Input : Stack : 1 2 3
Pop()
Output : Stack : 1 2
Examples: Queue
Input: Queue : 1 2 3
Enqueue(4)
Output: Queue : 1 2 3 4
Input: Queue : 1 2 3
Dequeue()
Output: Queue : 2 3
155
Chapter 28. Implement Stack and Queue using Deque
// Implementation of deque class
class deque {
private:
// pointers to head and tail of deque
DQueNode* head;
DQueNode* tail;
public:
// constructor
deque()
{
head = tail = NULL;
}
// if list is empty
bool isEmpty()
{
if (head == NULL)
return true;
return false;
}
// count the number of nodes in list
int size()
{
// if list is not empty
if (!isEmpty()) {
DQueNode* temp = head;
int len = 0;
while (temp != NULL) {
len++;
temp = temp->next;
}
return len;
}
return 0;
}
// insert at the first position
void insert_first(int element)
{
// allocating node of DQueNode type
DQueNode* temp = new DQueNode[sizeof(DQueNode)];
temp->value = element;
// if the element is first element
156
Chapter 28. Implement Stack and Queue using Deque
157
Chapter 28. Implement Stack and Queue using Deque
{
// if list is not empty
if (!isEmpty()) {
DQueNode* temp = tail;
tail = tail->prev;
tail->next = NULL;
free(temp);
return;
}
cout << "List is Empty" << endl;
}
// displays the elements in deque
void display()
{
// if list is not empty
if (!isEmpty()) {
DQueNode* temp = head;
while (temp != NULL) {
cout << temp->value << " ";
temp = temp->next;
}
cout << endl;
return;
}
cout << "List is Empty" << endl;
}
};
// Class to implement stack using Deque
class Stack : public deque {
public:
// push to push element at top of stack
// using insert at last function of deque
void push(int element)
{
insert_last(element);
}
// pop to remove element at top of stack
// using remove at last function of deque
void pop()
{
remove_last();
}
};
// class to implement queue using deque
158
Chapter 28. Implement Stack and Queue using Deque
159
Chapter 28. Implement Stack and Queue using Deque
Output:
Stack: 7 8
Stack: 7
Queue: 12 13
Queue: 13
Size of Stack is 1
Size of Queue is 1
Source
https://www.geeksforgeeks.org/implement-stack-queue-using-deque/
160
Chapter 29
A stack can be implemented using two queues. Let stack to be implemented be ‘s’ and
queues used to implement be ‘q1’ and ‘q2’. Stack ‘s’ can be implemented in two ways:
Method 1 (By making push operation costly)
This method makes sure that newly entered element is always at the front of ‘q1’, so that
pop operation just dequeues from ‘q1’. ‘q2’ is used to put every new element at front of ‘q1’.
161
Chapter 29. Implement Stack using Queues
pop(s)
1) Dequeue an item from q1 and return it.
162
Chapter 29. Implement Stack using Queues
q1 = q2;
q2 = q;
}
void pop(){
// if no elements are there in q1
if (q1.empty())
return ;
q1.pop();
curr_size--;
}
int top()
{
if (q1.empty())
return -1;
return q1.front();
}
int size()
{
return curr_size;
}
};
// driver code
int main()
{
Stack s;
s.push(1);
s.push(2);
s.push(3);
cout << "current size: " << s.size()
<< endl;
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
cout << "current size: " << s.size()
<< endl;
return 0;
}
// This code is contributed by Chhavi
163
Chapter 29. Implement Stack using Queues
Output :
current size: 3
3
2
1
current size: 1
push(s, x)
1) Enqueue x to q1 (assuming size of q1 is unlimited).
pop(s)
1) One by one dequeue everything except the last element from q1 and enqueue to q2.
2) Dequeue the last item of q1, the dequeued item is result, store it.
3) Swap the names of q1 and q2
4) Return the item stored in step 2.
// Swapping of names is done to avoid one more movement of all elements
// from q2 to q1.
164
Chapter 29. Implement Stack using Queues
165
Chapter 29. Implement Stack using Queues
q2 = q;
return temp;
}
int size()
{
return curr_size;
}
};
// driver code
int main()
{
Stack s;
s.push(1);
s.push(2);
s.push(3);
s.push(4);
cout << "current size: " << s.size()
<< endl;
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
s.pop();
cout << s.top() << endl;
cout << "current size: " << s.size()
<< endl;
return 0;
}
// This code is contributed by Chhavi
Output :
current size: 4
4
3
2
current size: 2
References:
Implement Stack using Two Queues
This article is compiled by Sumit Jain and reviewed by GeeksforGeeks team. Please write
comments if you find anything incorrect, or you want to share more information about the
topic discussed above.
166
Chapter 29. Implement Stack using Queues
Source
https://www.geeksforgeeks.org/implement-stack-using-queue/
167
Chapter 30
168
Chapter 30. Implement a stack using single queue
// User defined stack that uses a queue
class Stack
{
queue<int>q;
public:
void push(int val);
void pop();
int top();
bool empty();
};
// Push operation
void Stack::push(int val)
{
// Get previous size of queue
int s = q.size();
// Push current element
q.push(val);
// Pop (or Dequeue) all previous
// elements and put them after current
// element
for (int i=0; i<s; i++)
{
// this will add front element into
// rear of queue
q.push(q.front());
// this will delete front element
q.pop();
}
}
// Removes the top element
void Stack::pop()
{
if (q.empty())
cout << "No elements\n";
else
q.pop();
}
// Returns top of stack
int Stack::top()
{
return (q.empty())? -1 : q.front();
169
Chapter 30. Implement a stack using single queue
}
// Returns true if Stack is empty else false
bool Stack::empty()
{
return (q.empty());
}
// Driver code
int main()
{
Stack s;
s.push(10);
s.push(20);
cout << s.top() << endl;
s.pop();
s.push(30);
s.pop();
cout << s.top() << endl;
return 0;
}
Java
170
Chapter 30. Implement a stack using single queue
171
Chapter 30. Implement a stack using single queue
Output :
20
10
Source
https://www.geeksforgeeks.org/implement-a-stack-using-single-queue/
172
Chapter 31
173
Chapter 31. Implementation of Deque using circular array
174
Chapter 31. Implementation of Deque using circular array
175
Chapter 31. Implementation of Deque using circular array
C++
176
Chapter 31. Implementation of Deque using circular array
177
Chapter 31. Implementation of Deque using circular array
178
Chapter 31. Implementation of Deque using circular array
}
else
// back to initial position
if (front == size -1)
front = 0;
else // increment front by '1' to remove current
// front value from Deque
front = front+1;
}
// Delete element at rear end of Deque
void Deque::deleterear()
{
if (isEmpty())
{
cout << " Underflow\n" << endl ;
return ;
}
// Deque has only one element
if (front == rear)
{
front = -1;
rear = -1;
}
else if (rear == 0)
rear = size-1;
else
rear = rear-1;
}
// Returns front element of Deque
int Deque::getFront()
{
// check whether Deque is empty or not
if (isEmpty())
{
cout << " Underflow\n" << endl;
return -1 ;
}
return arr[front];
}
// function return rear element of Deque
int Deque::getRear()
{
// check whether Deque is empty or not
179
Chapter 31. Implementation of Deque using circular array
Java
180
Chapter 31. Implementation of Deque using circular array
int front;
int rear;
int size;
public Deque(int size)
{
arr = new int[MAX];
front = -1;
rear = 0;
this.size = size;
}
/*// Operations on Deque:
void insertfront(int key);
void insertrear(int key);
void deletefront();
void deleterear();
bool isFull();
bool isEmpty();
int getFront();
int getRear();*/
// Checks whether Deque is full or not.
boolean isFull()
{
return ((front == 0 && rear == size-1)||
front == rear+1);
}
// Checks whether Deque is empty or not.
boolean isEmpty ()
{
return (front == -1);
}
// Inserts an element at front
void insertfront(int key)
{
// check whether Deque if full or not
if (isFull())
{
System.out.println("Overflow");
return;
}
// If queue is initially empty
if (front == -1)
{
181
Chapter 31. Implementation of Deque using circular array
front = 0;
rear = 0;
}
// front is at first position of queue
else if (front == 0)
front = size - 1 ;
else // decrement front end by '1'
front = front-1;
// insert current element into Deque
arr[front] = key ;
}
// function to inset element at rear end
// of Deque.
void insertrear(int key)
{
if (isFull())
{
System.out.println(" Overflow ");
return;
}
// If queue is initially empty
if (front == -1)
{
front = 0;
rear = 0;
}
// rear is at last position of queue
else if (rear == size-1)
rear = 0;
// increment rear end by '1'
else
rear = rear+1;
// insert current element into Deque
arr[rear] = key ;
}
// Deletes element at front end of Deque
void deletefront()
{
// check whether Deque is empty or not
182
Chapter 31. Implementation of Deque using circular array
if (isEmpty())
{
System.out.println("Queue Underflow\n");
return ;
}
// Deque has only one element
if (front == rear)
{
front = -1;
rear = -1;
}
else
// back to initial position
if (front == size -1)
front = 0;
else // increment front by '1' to remove current
// front value from Deque
front = front+1;
}
// Delete element at rear end of Deque
void deleterear()
{
if (isEmpty())
{
System.out.println(" Underflow");
return ;
}
// Deque has only one element
if (front == rear)
{
front = -1;
rear = -1;
}
else if (rear == 0)
rear = size-1;
else
rear = rear-1;
}
// Returns front element of Deque
int getFront()
{
// check whether Deque is empty or not
if (isEmpty())
183
Chapter 31. Implementation of Deque using circular array
{
System.out.println(" Underflow");
return -1 ;
}
return arr[front];
}
// function return rear element of Deque
int getRear()
{
// check whether Deque is empty or not
if(isEmpty() || rear < 0)
{
System.out.println(" Underflow\n");
return -1 ;
}
return arr[rear];
}
// Driver program to test above function
public static void main(String[] args)
{
Deque dq = new Deque(5);
System.out.println("Insert element at rear end : 5 ");
dq.insertrear(5);
System.out.println("insert element at rear end : 10 ");
dq.insertrear(10);
System.out.println("get rear element : "+ dq.getRear());
dq.deleterear();
System.out.println("After delete rear element new rear become : " +
dq.getRear());
System.out.println("inserting element at front end");
dq.insertfront(15);
System.out.println("get front element: " +dq.getFront());
dq.deletefront();
System.out.println("After delete front element new front become : " +
+ dq.getFront());
}
184
Chapter 31. Implementation of Deque using circular array
Output:
Time Complexity: Time complexity of all operations like insertfront(), insertlast(), delete-
front(), deletelast()is O(1).
In mext post we will discuss deque implementation using Doubly linked list.
Improved By : programmer2k17
Source
https://www.geeksforgeeks.org/implementation-deque-using-circular-array/
185
Chapter 32
Operations on Deque :
186
Chapter 32. Implementation of Deque using doubly linked list
187
Chapter 32. Implementation of Deque using doubly linked list
4. ELSE
5. IF rear == NULL, then
6. front = rear = newNode
7. ELSE
8. newNode->prev = rear
9. rear->next = newNode
10. rear = newNode
1. IF front == NULL
2. print "Underflow"
3. ELSE
4. Initalize temp = front
5. front = front->next
6. IF front == NULL
7. rear = NULL
8. ELSE
9. front->prev = NULL
10 Deallocate space for temp
1. IF front == NULL
2. print "Underflow"
3. ELSE
4. Initalize temp = rear
5. rear = rear->prev
6. IF rear == NULL
7. front = NULL
8. ELSE
9. rear->next = NULL
10 Deallocate space for temp
188
Chapter 32. Implementation of Deque using doubly linked list
189
Chapter 32. Implementation of Deque using doubly linked list
}
// Function to insert an element
// at the front end
void Deque::insertFront(int data)
{
Node* newNode = Node::getnode(data);
// If true then new element cannot be added
// and it is an 'Overflow' condition
if (newNode == NULL)
cout << "OverFlow\n";
else
{
// If deque is empty
if (front == NULL)
rear = front = newNode;
// Inserts node at the front end
else
{
newNode->next = front;
front->prev = newNode;
front = newNode;
}
// Increments count of elements by 1
Size++;
}
}
// Function to insert an element
// at the rear end
void Deque::insertRear(int data)
{
Node* newNode = Node::getnode(data);
// If true then new element cannot be added
// and it is an 'Overflow' condition
if (newNode == NULL)
cout << "OverFlow\n";
else
{
// If deque is empty
if (rear == NULL)
front = rear = newNode;
// Inserts node at the rear end
else
{
190
Chapter 32. Implementation of Deque using doubly linked list
newNode->prev = rear;
rear->next = newNode;
rear = newNode;
}
Size++;
}
}
// Function to delete the element
// from the front end
void Deque::deleteFront()
{
// If deque is empty then
// 'Underflow' condition
if (isEmpty())
cout << "UnderFlow\n";
// Deletes the node from the front end and makes
// the adjustment in the links
else
{
Node* temp = front;
front = front->next;
// If only one element was present
if (front == NULL)
rear = NULL;
else
front->prev = NULL;
free(temp);
// Decrements count of elements by 1
Size--;
}
}
// Function to delete the element
// from the rear end
void Deque::deleteRear()
{
// If deque is empty then
// 'Underflow' condition
if (isEmpty())
cout << "UnderFlow\n";
// Deletes the node from the rear end and makes
// the adjustment in the links
191
Chapter 32. Implementation of Deque using doubly linked list
else
{
Node* temp = rear;
rear = rear->prev;
// If only one element was present
if (rear == NULL)
front = NULL;
else
rear->next = NULL;
free(temp);
// Decrements count of elements by 1
Size--;
}
}
// Function to return the element
// at the front end
int Deque::getFront()
{
// If deque is empty, then returns
// garbage value
if (isEmpty())
return -1;
return front->data;
}
// Function to return the element
// at the rear end
int Deque::getRear()
{
// If deque is empty, then returns
// garbage value
if (isEmpty())
return -1;
return rear->data;
}
// Function to delete all the elements
// from Deque
void Deque::erase()
{
rear = NULL;
while (front != NULL)
{
Node* temp = front;
front = front->next;
192
Chapter 32. Implementation of Deque using doubly linked list
free(temp);
}
Size = 0;
}
// Driver program to test above
int main()
{
Deque dq;
cout << "Insert element '5' at rear end\n";
dq.insertRear(5);
cout << "Insert element '10' at rear end\n";
dq.insertRear(10);
cout << "Rear end element: "
<< dq.getRear() << endl;
dq.deleteRear();
cout << "After deleting rear element new rear"
<< " is: " << dq.getRear() << endl;
cout << "Inserting element '15' at front end \n";
dq.insertFront(15);
cout << "Front end element: "
<< dq.getFront() << endl;
cout << "Number of elements in Deque: "
<< dq.size() << endl;
dq.deleteFront();
cout << "After deleting front element new "
<< "front is: " << dq.getFront() << endl;
return 0;
}
Output :
193
Chapter 32. Implementation of Deque using doubly linked list
Source
https://www.geeksforgeeks.org/implementation-deque-using-doubly-linked-list/
194
Chapter 33
Interleave the first half of the queue with second half - GeeksforGeeks
Given a queue of integers of even length, rearrange the elements by interleaving the first
half of the queue with the second half of the queue.
Only a stack can be used as an auxiliary space.
Examples:
Input : 1 2 3 4
Output : 1 3 2 4
Input : 11 12 13 14 15 16 17 18 19 20
Output : 11 16 12 17 13 18 14 19 15 20
195
Chapter 33. Interleave the first half of the queue with second half
{
// To check the even number of elements
if (q.size() % 2 != 0)
cout << "Input even number of integers." << endl;
// Initialize an empty stack of int type
stack<int> s;
int halfSize = q.size() / 2;
// Push first half elements into the stack
// queue:16 17 18 19 20, stack: 15(T) 14 13 12 11
for (int i = 0; i < halfSize; i++) {
s.push(q.front());
q.pop();
}
// enqueue back the stack elements
// queue: 16 17 18 19 20 15 14 13 12 11
while (!s.empty()) {
q.push(s.top());
s.pop();
}
// dequeue the first half elements of queue
// and enqueue them back
// queue: 15 14 13 12 11 16 17 18 19 20
for (int i = 0; i < halfSize; i++) {
q.push(q.front());
q.pop();
}
// Again push the first half elements into the stack
// queue: 16 17 18 19 20, stack: 11(T) 12 13 14 15
for (int i = 0; i < halfSize; i++) {
s.push(q.front());
q.pop();
}
// interleave the elements of queue and stack
// queue: 11 16 12 17 13 18 14 19 15 20
while (!s.empty()) {
q.push(s.top());
s.pop();
q.push(q.front());
q.pop();
}
}
196
Chapter 33. Interleave the first half of the queue with second half
Output:
11 16 12 17 13 18 14 19 15 20
Source
https://www.geeksforgeeks.org/interleave-first-half-queue-second-half/
197
Chapter 34
Example Tree
Recursive method to find height of Binary Tree is discussed here. How to find height without
recursion? We can use level order traversal to find height without recursion. The idea is
to traverse level by level. Whenever move down to a level, increment height by 1 (height is
initialized as 0). Count number of nodes at each level, stop traversing when count of nodes
at next level is 0.
Following is detailed algorithm to find level order traversal using queue.
Create a queue.
198
Chapter 34. Iterative Method to find Height of Binary Tree
199
Chapter 34. Iterative Method to find Height of Binary Tree
int height = 0;
while (1)
{
// nodeCount (queue size) indicates number of nodes
// at current lelvel.
int nodeCount = q.size();
if (nodeCount == 0)
return height;
height++;
// Dequeue all nodes of current level and Enqueue all
// nodes of next level
while (nodeCount > 0)
{
node *node = q.front();
q.pop();
if (node->left != NULL)
q.push(node->left);
if (node->right != NULL)
q.push(node->right);
nodeCount--;
}
}
}
// Utility function to create a new tree node
node* newNode(int data)
{
node *temp = new node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree shown in above diagram
node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << "Height of tree is " << treeHeight(root);
200
Chapter 34. Iterative Method to find Height of Binary Tree
return 0;
}
Java
201
Chapter 34. Iterative Method to find Height of Binary Tree
height++;
// Dequeue all nodes of current level and Enqueue all
// nodes of next level
while (nodeCount > 0)
{
Node newnode = q.peek();
q.remove();
if (newnode.left != null)
q.add(newnode.left);
if (newnode.right != null)
q.add(newnode.right);
nodeCount--;
}
}
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
// Let us create a binary tree shown in above diagram
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(4);
tree.root.left.right = new Node(5);
System.out.println("Height of tree is " + tree.treeHeight(tree.root));
}
}
// This code has been contributed by Mayank Jaiswal
Python
202
Chapter 34. Iterative Method to find Height of Binary Tree
def treeHeight(root):
# Base Case
if root is None:
return 0
# Create a empty queue for level order traversal
q = []
# Enqueue Root and Initialize Height
q.append(root)
height = 0
while(True):
# nodeCount(queue size) indicates number of nodes
# at current level
nodeCount = len(q)
if nodeCount == 0 :
return height
height += 1
# Dequeue all nodes of current level and Enqueue
# all nodes of next level
while(nodeCount > 0):
node = q[0]
q.pop(0)
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
nodeCount -= 1
# Driver program to test above function
# Let us create binary tree shown in above diagram
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
print "Height of tree is", treeHeight(root)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
203
Chapter 34. Iterative Method to find Height of Binary Tree
Output:
Height of tree is 3
Source
https://www.geeksforgeeks.org/iterative-method-to-find-height-of-binary-tree/
204
Chapter 35
1. Queue which is implemented using a doubly linked list. The maximum size of the
queue will be equal to the total number of frames available (cache size).The most
recently used pages will be near front end and least recently pages will be near rear
end.
2. A Hash with page number as key and address of the corresponding queue node as
value.
When a page is referenced, the required page may be in the memory. If it is in the memory,
we need to detach the node of the list and bring it to the front of the queue.
If the required page is not in the memory, we bring that in memory. In simple words, we
add a new node to the front of the queue and update the corresponding node address in
the hash. If the queue is full, i.e. all the frames are full, we remove a node from the rear of
queue, and add the new node to the front of queue.
Example – Consider the following reference string :
1, 2, 3, 4, 1, 2, 5, 1, 2, 3, 4, 5
Find the number of page faults using least recently used (LRU) page replacement algorithm
with 3 page frames.
Explanation –
205
Chapter 35. LRU Cache Implementation
206
Chapter 35. LRU Cache Implementation
207
Chapter 35. LRU Cache Implementation
208
Chapter 35. LRU Cache Implementation
}
// present in cache
else
dq.erase(ma[x]);
// update reference
dq.push_front(x);
ma[x] = dq.begin();
}
// display contents of cache
void LRUCache::display()
{
for (auto it = dq.begin(); it != dq.end();
it++)
cout << (*it) << " ";
cout << endl;
}
// Driver program to test above functions
int main()
{
LRUCache ca(4);
ca.refer(1);
ca.refer(2);
ca.refer(3);
ca.refer(1);
ca.refer(4);
ca.refer(5);
ca.display();
return 0;
}
// This code is contributed by Satish Srinivas
209
Chapter 35. LRU Cache Implementation
210
Chapter 35. LRU Cache Implementation
211
Chapter 35. LRU Cache Implementation
// decrement the number of full frames by 1
queue->count--;
}
// A function to add a page with given 'pageNumber' to both queue
// and hash
void Enqueue( Queue* queue, Hash* hash, unsigned pageNumber )
{
// If all frames are full, remove the page at the rear
if ( AreAllFramesFull ( queue ) )
{
// remove page from hash
hash->array[ queue->rear->pageNumber ] = NULL;
deQueue( queue );
}
// Create a new node with given page number,
// And add the new node to the front of queue
QNode* temp = newQNode( pageNumber );
temp->next = queue->front;
// If queue is empty, change both front and rear pointers
if ( isQueueEmpty( queue ) )
queue->rear = queue->front = temp;
else // Else change the front
{
queue->front->prev = temp;
queue->front = temp;
}
// Add page entry to hash also
hash->array[ pageNumber ] = temp;
// increment number of full frames
queue->count++;
}
// This function is called when a page with given 'pageNumber' is referenced
// from cache (or memory). There are two cases:
// 1. Frame is not there in memory, we bring it in memory and add to the front
// of queue
// 2. Frame is there in memory, we move the frame to front of queue
void ReferencePage( Queue* queue, Hash* hash, unsigned pageNumber )
{
QNode* reqPage = hash->array[ pageNumber ];
// the page is not in cache, bring it
212
Chapter 35. LRU Cache Implementation
213
Chapter 35. LRU Cache Implementation
Output:
5 4 1 3
Source
https://www.geeksforgeeks.org/lru-cache-implementation/
214
Chapter 36
Input : ((()
Output : 2
Explanation : ()
Input: )()())
Output : 4
Explanation: ()()
Input: ()(()))))
Output: 6
Explanation: ()(())
A Simple Approach is to find all the substrings of given string. For every string, check
if it is a valid string or not. If valid and length is more than maximum length so far, then
update maximum length. We can check whether a substring is valid or not in linear time
using a stack (See this for details). Time complexity of this solution is O(n2 .
An Efficient Solution can solve this problem in O(n) time. The idea is to store indexes
of previous starting brackets in a stack. The first element of stack is a special element that
provides index before beginning of valid substring (base for next valid string).
215
Chapter 36. Length of the longest valid substring
2) Initialize result as 0.
3) Return result.
C++
216
Chapter 36. Length of the longest valid substring
Java
217
Chapter 36. Length of the longest valid substring
stk.push(-1);
// Initialize result
int result = 0;
// Traverse all characters of given string
for (int i=0; i<n; i++)
{
// If opening bracket, push index of it
if (str.charAt(i) == '(')
stk.push(i);
else // If closing bracket, i.e.,str[i] = ')'
{
// Pop the previous opening bracket's index
stk.pop();
// Check if this length formed with base of
// current valid substring is more than max
// so far
if (!stk.empty())
result = Math.max(result, i - stk.peek());
// If stack is empty. push current index as
// base for next valid substring (if any)
else stk.push(i);
}
}
return result;
}
// Driver method
public static void main(String[] args)
{
String str = "((()()";
System.out.println(findMaxLen(str));
str = "()(()))))";
System.out.println(findMaxLen(str));
}
}
Python
218
Chapter 36. Length of the longest valid substring
def findMaxLen(string):
n = len(string)
# Create a stack and push -1 as initial index to it.
stk = []
stk.append(-1)
# Initialize result
result = 0
# Traverse all characters of given string
for i in xrange(n):
# If opening bracket, push index of it
if string[i] == '(':
stk.append(i)
else: # If closing bracket, i.e., str[i] = ')'
# Pop the previous opening bracket's index
stk.pop()
# Check if this length formed with base of
# current valid substring is more than max
# so far
if len(stk) != 0:
result = max(result, i - stk[len(stk)-1])
# If stack is empty. push current index as
# base for next valid substring (if any)
else:
stk.append(i)
return result
# Driver program
string = "((()()"
print findMaxLen(string)
string = "()(()))))"
print findMaxLen(string)
# This code is contributed by Bhavya Jain
Output:
219
Chapter 36. Length of the longest valid substring
Thanks to Gaurav Ahirwar and Ekta Goel. for suggesting above approach.
Source
https://www.geeksforgeeks.org/length-of-the-longest-valid-substring/
220
Chapter 37
221
Chapter 37. Level Order Tree Traversal
for d = 1 to height(tree)
printGivenLevel(tree, d);
Implementation:
222
Chapter 37. Level Order Tree Traversal
if (level == 1)
printf("%d ", root->data);
else if (level > 1)
{
printGivenLevel(root->left, level-1);
printGivenLevel(root->right, level-1);
}
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the height of each subtree */
int lheight = height(node->left);
int rheight = height(node->right);
/* use the larger one */
if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
223
Chapter 37. Level Order Tree Traversal
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Level Order traversal of binary tree is \n");
printLevelOrder(root);
return 0;
}
Java
224
Chapter 37. Level Order Tree Traversal
Python
225
Chapter 37. Level Order Tree Traversal
226
Chapter 37. Level Order Tree Traversal
Output:
Time Complexity: O(n^2) in worst case. For a skewed tree, printGivenLevel() takes O(n)
time where n is the number of nodes in the skewed tree. So time complexity of printLevel-
Order() is O(n) + O(n-1) + O(n-2) + .. + O(1) which is O(n^2).
METHOD 2 (Use Queue)
Algorithm:
For each node, first the node is visited and then it’s child nodes are put in a FIFO queue.
printLevelorder(tree)
1) Create an empty queue q
2) temp_node = root /*start from root*/
3) Loop while temp_node is not NULL
a) print temp_node->data.
b) Enqueue temp_node’s children (first left then right children) to q
c) Dequeue a node from q and assign it’s value to temp_node
Implementation:
Here is a simple implementation of the above algorithm. Queue is implemented using an
array with maximum size of 500. We can implement queue as linked list also.
227
Chapter 37. Level Order Tree Traversal
/* A binary tree node has data, pointer to left child
and a pointer to right child */
struct node
{
int data;
struct node* left;
struct node* right;
};
/* frunction prototypes */
struct node** createQueue(int *, int *);
void enQueue(struct node **, int *, struct node *);
struct node *deQueue(struct node **, int *);
/* Given a binary tree, print its nodes in level order
using array for implementing queue */
void printLevelOrder(struct node* root)
{
int rear, front;
struct node **queue = createQueue(&front, &rear);
struct node *temp_node = root;
while (temp_node)
{
printf("%d ", temp_node->data);
/*Enqueue left child */
if (temp_node->left)
enQueue(queue, &rear, temp_node->left);
/*Enqueue right child */
if (temp_node->right)
enQueue(queue, &rear, temp_node->right);
/*Dequeue node and make it temp_node*/
temp_node = deQueue(queue, &front);
}
}
/*UTILITY FUNCTIONS*/
struct node** createQueue(int *front, int *rear)
{
struct node **queue =
(struct node **)malloc(sizeof(struct node*)*MAX_Q_SIZE);
*front = *rear = 0;
return queue;
228
Chapter 37. Level Order Tree Traversal
}
void enQueue(struct node **queue, int *rear, struct node *new_node)
{
queue[*rear] = new_node;
(*rear)++;
}
struct node *deQueue(struct node **queue, int *front)
{
(*front)++;
return queue[*front - 1];
}
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
printf("Level Order traversal of binary tree is \n");
printLevelOrder(root);
return 0;
}
C++
229
Chapter 37. Level Order Tree Traversal
// A Binary Tree Node
struct Node
{
int data;
struct Node *left, *right;
};
// Iterative method to find height of Bianry Tree
void printLevelOrder(Node *root)
{
// Base Case
if (root == NULL) return;
// Create an empty queue for level order tarversal
queue<Node *> q;
// Enqueue Root and initialize height
q.push(root);
while (q.empty() == false)
{
// Print front of queue and remove it from queue
Node *node = q.front();
cout << node->data << " ";
q.pop();
/* Enqueue left child */
if (node->left != NULL)
q.push(node->left);
/*Enqueue right child */
if (node->right != NULL)
q.push(node->right);
}
}
// Utility function to create a new tree node
Node* newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
230
Chapter 37. Level Order Tree Traversal
{
// Let us create binary tree shown in above diagram
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
cout << "Level Order traversal of binary tree is \n";
printLevelOrder(root);
return 0;
}
Java
231
Chapter 37. Level Order Tree Traversal
Python
232
Chapter 37. Level Order Tree Traversal
Output:
Source
https://www.geeksforgeeks.org/level-order-tree-traversal/
233
Chapter 38
Method 1 (Recursive)
This problem can bee seen as an extension of the level order traversal post.
To print the nodes in spiral order, nodes at different levels should be printed in alternating
order. An additional Boolean variable ltr is used to change printing order of levels. If ltr is
1 then printGivenLevel() prints nodes from left to right else from right to left. Value of ltr
is flipped in each iteration to change the order.
Function to print level order traversal of tree
printSpiral(tree)
bool ltr = 0;
for d = 1 to height(tree)
printGivenLevel(tree, d, ltr);
ltr ~= ltr /*flip ltr*/
234
Chapter 38. Level order traversal in spiral form
235
Chapter 38. Level order traversal in spiral form
printGivenLevel(root, i, ltr);
/*Revert ltr to traverse next level in opposite order*/
ltr = !ltr;
}
}
/* Print nodes at a given level */
void printGivenLevel(struct node* root, int level, int ltr)
{
if(root == NULL)
return;
if(level == 1)
printf("%d ", root->data);
else if (level > 1)
{
if(ltr)
{
printGivenLevel(root->left, level-1, ltr);
printGivenLevel(root->right, level-1, ltr);
}
else
{
printGivenLevel(root->right, level-1, ltr);
printGivenLevel(root->left, level-1, ltr);
}
}
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(struct node* node)
{
if (node==NULL)
return 0;
else
{
/* compute the height of each subtree */
int lheight = height(node->left);
int rheight = height(node->right);
/* use the larger one */
if (lheight > rheight)
return(lheight+1);
else return(rheight+1);
}
}
236
Chapter 38. Level order traversal in spiral form
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct node* newNode(int data)
{
struct node* node = (struct node*)
malloc(sizeof(struct node));
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
/* Driver program to test above functions*/
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(7);
root->left->right = newNode(6);
root->right->left = newNode(5);
root->right->right = newNode(4);
printf("Spiral Order traversal of binary tree is \n");
printSpiral(root);
return 0;
}
Java
237
Chapter 38. Level order traversal in spiral form
class BinaryTree
{
Node root;
// Function to print the spiral traversal of tree
void printSpiral(Node node)
{
int h = height(node);
int i;
/* ltr -> left to right. If this variable is set then the
given label is transversed from left to right */
boolean ltr = false;
for (i = 1; i <= h; i++)
{
printGivenLevel(node, i, ltr);
/*Revert ltr to traverse next level in opposite order*/
ltr = !ltr;
}
}
/* Compute the "height" of a tree -- the number of
nodes along the longest path from the root node
down to the farthest leaf node.*/
int height(Node node)
{
if (node == null)
return 0;
else
{
/* compute the height of each subtree */
int lheight = height(node.left);
int rheight = height(node.right);
/* use the larger one */
if (lheight > rheight)
return (lheight + 1);
else
return (rheight + 1);
}
}
/* Print nodes at a given level */
void printGivenLevel(Node node, int level, boolean ltr)
{
238
Chapter 38. Level order traversal in spiral form
Output:
Time Complexity: Worst case time complexity of the above method is O(n^2). Worst
case occurs in case of skewed trees.
Method 2 (Iterative)
We can print spiral order traversal in O(n) time and O(n) extra space. The idea is to use
two stacks. We can use one stack for printing from left to right and other stack for printing
from right to left. In every iteration, we have nodes of one level in one of the stacks. We
239
Chapter 38. Level order traversal in spiral form
print the nodes, and push nodes of next level in other stack.
C++
240
Chapter 38. Level order traversal in spiral form
{
struct node *temp = s2.top();
s2.pop();
cout << temp->data << " ";
// Note that is left is pushed before right
if (temp->left)
s1.push(temp->left);
if (temp->right)
s1.push(temp->right);
}
}
}
// A utility function to create a new node
struct node* newNode(int data)
{
struct node* node = new struct node;
node->data = data;
node->left = NULL;
node->right = NULL;
return(node);
}
int main()
{
struct node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(7);
root->left->right = newNode(6);
root->right->left = newNode(5);
root->right->right = newNode(4);
cout << "Spiral Order traversal of binary tree is \n";
printSpiral(root);
return 0;
}
Java
241
Chapter 38. Level order traversal in spiral form
class Node
{
int data;
Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
static Node root;
void printSpiral(Node node)
{
if (node == null)
return; // NULL check
// Create two stacks to store alternate levels
Stack<Node> s1 = new Stack<Node>();// For levels to be printed from right to left
Stack<Node> s2 = new Stack<Node>();// For levels to be printed from left to right
// Push first level to first stack 's1'
s1.push(node);
// Keep ptinting while any of the stacks has some nodes
while (!s1.empty() || !s2.empty())
{
// Print nodes of current level from s1 and push nodes of
// next level to s2
while (!s1.empty())
{
Node temp = s1.peek();
s1.pop();
System.out.print(temp.data + " ");
// Note that is right is pushed before left
if (temp.right != null)
s2.push(temp.right);
if (temp.left != null)
s2.push(temp.left);
}
242
Chapter 38. Level order traversal in spiral form
// Print nodes of current level from s2 and push nodes of
// next level to s1
while (!s2.empty())
{
Node temp = s2.peek();
s2.pop();
System.out.print(temp.data + " ");
// Note that is left is pushed before right
if (temp.left != null)
s1.push(temp.left);
if (temp.right != null)
s1.push(temp.right);
}
}
}
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(1);
tree.root.left = new Node(2);
tree.root.right = new Node(3);
tree.root.left.left = new Node(7);
tree.root.left.right = new Node(6);
tree.root.right.left = new Node(5);
tree.root.right.right = new Node(4);
System.out.println("Spiral Order traversal of Binary Tree is ");
tree.printSpiral(root);
}
}
// This code has been contributed by Mayank Jaiswal(mayank_24)
Output:
Please write comments if you find any bug in the above program/algorithm; or if you want
to share more information about spiral traversal.
Source
https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form/
243
Chapter 39
Level order traversal in spiral form | Using one stack and one queue - GeeksforGeeks
Write a function to print spiral order traversal of a tree. For below tree, function should
print 1, 2, 3, 4, 5, 6, 7.
244
Chapter 39. Level order traversal in spiral form | Using one stack and one queue
245
Chapter 39. Level order traversal in spiral form | Using one stack and one queue
size--;
}
// print nodes from the stack if
// reverse is true
if (reverse) {
while (!s.empty()) {
cout << s.top() << " ";
s.pop();
}
}
// the next row has to be printed as
// it is, hence change the value of
// reverse
reverse = !reverse;
}
}
/*Driver program to test the above functions*/
int main()
{
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(7);
root->left->right = newNode(6);
root->right->left = newNode(5);
root->right->right = newNode(4);
printSpiralUsingOneStack(root);
return 0;
}
Output:
1 2 3 4 5 6 7
Source
https://www.geeksforgeeks.org/level-order-traversal-in-spiral-form-using-one-stack-and-one-queue/
246
Chapter 40
Level order traversal line by line | Set 2 (Using Two Queues) - GeeksforGeeks
Given a Binary Tree, print the nodes level wise, each level on a new line.
Output:
1
2 3
4 5
247
Chapter 40. Level order traversal line by line | Set 2 (Using Two Queues)
int data;
Node *left, *right;
};
// Prints level order traversal line by line
// using two queues.
void levelOrder(Node *root)
{
queue<Node *> q1, q2;
if (root == NULL)
return;
// Pushing first level node into first queue
q1.push(root);
// Executing loop till both the queues
// become empty
while (!q1.empty() || !q2.empty())
{
while (!q1.empty())
{
// Pushing left child of current node in
// first queue into second queue
if (q1.front()->left != NULL)
q2.push(q1.front()->left);
// pushing right child of current node
// in first queue into second queue
if (q1.front()->right != NULL)
q2.push(q1.front()->right);
cout << q1.front()->data << " ";
q1.pop();
}
cout << "\n";
while (!q2.empty())
{
// pushing left child of current node
// in second queue into first queue
if (q2.front()->left != NULL)
q1.push(q2.front()->left);
// pushing right child of current
// node in second queue into first queue
if (q2.front()->right != NULL)
248
Chapter 40. Level order traversal line by line | Set 2 (Using Two Queues)
q1.push(q2.front()->right);
cout << q2.front()->data << " ";
q2.pop();
}
cout << "\n";
}
}
// Utility function to create a new tree node
Node* newNode(int data)
{
Node *temp = new Node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// Driver program to test above functions
int main()
{
Node *root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->right = newNode(6);
levelOrder(root);
return 0;
}
Java
249
Chapter 40. Level order traversal line by line | Set 2 (Using Two Queues)
Node(int data)
{
this.data = data;
left = null;
right = null;
}
}
// Prints level order traversal line by line
// using two queues.
static void levelOrder(Node root)
{
Queue<Node> q1 = new LinkedList<Node>();
Queue<Node> q2 = new LinkedList<Node>();
if (root == null)
return;
// Pushing first level node into first queue
q1.add(root);
// Executing loop till both the queues
// become empty
while (!q1.isEmpty() || !q2.isEmpty())
{
while (!q1.isEmpty())
{
// Pushing left child of current node in
// first queue into second queue
if (q1.peek().left != null)
q2.add(q1.peek().left);
// pushing right child of current node
// in first queue into second queue
if (q1.peek().right != null)
q2.add(q1.peek().right);
System.out.print(q1.peek().data + " ");
q1.remove();
}
System.out.println();
while (!q2.isEmpty())
{
250
Chapter 40. Level order traversal line by line | Set 2 (Using Two Queues)
Python
"""
Python program to do level order traversal
line by line using dual queue"""
class GFG:
"""Constructor to create a new tree node"""
def __init__(self,data):
self.val = data
self.left = None
self.right = None
"""Prints level order traversal line by
line using two queues."""
251
Chapter 40. Level order traversal line by line | Set 2 (Using Two Queues)
def levelOrder(self,node):
q1 = [] # Queue 1
q2 = [] # Queue 2
q1.append(node)
"""Executing loop till both the
queues become empty"""
while(len(q1) > 0 or len(q2) > 0):
"""Empty string to concatenate
the string for q1"""
concat_str_q1 = ''
while(len(q1) > 0):
"""Poped node at the first
pos in queue 1 i.e q1"""
poped_node = q1.pop(0)
concat_str_q1 += poped_node.val +' '
"""Pushing left child of current
node in first queue into second queue"""
if poped_node.left:
q2.append(poped_node.left)
"""Pushing right child of current node
in first queue into second queue"""
if poped_node.right:
q2.append(poped_node.right)
print( str(concat_str_q1))
concat_str_q1 = ''
"""Empty string to concatenate the
string for q1"""
concat_str_q2 = ''
while (len(q2) > 0):
"""Poped node at the first pos
in queue 1 i.e q1"""
poped_node = q2.pop(0)
concat_str_q2 += poped_node.val + ' '
"""Pushing left child of current node
in first queue into first queue"""
if poped_node.left:
q1.append(poped_node.left)
"""Pushing right child of current node
in first queue into first queue"""
252
Chapter 40. Level order traversal line by line | Set 2 (Using Two Queues)
if poped_node.right:
q1.append(poped_node.right)
print(str(concat_str_q2))
concat_str_q2 = ''
""" Driver program to test above functions"""
node = GFG("1")
node.left = GFG("2")
node.right = GFG("3")
node.left.left = GFG("4")
node.left.right = GFG("5")
node.right.right = GFG("6")
node.levelOrder(node)
# This code is contributed by Vaibhav Kumar 12
Output :
1
2 3
4 5 6
Source
https://www.geeksforgeeks.org/level-order-traversal-line-line-set-2-using-two-queues/
253
Chapter 41
Level order traversal with direction change after every two levels - GeeksforGeeks
Given a binary tree, print the level order traversal in such a way that first two levels are
printed from left to right, next two levels are printed from right to left, then next two from
left to right and so on. So, the problem is to reverse the direction of level order traversal of
binary tree after every two levels.
Examples:
Input:
1
/ \
2 3
/ \ / \
4 5 6 7
/ \ / \ / \ / \
8 9 3 1 4 2 7 2
/ / \ \
16 17 18 19
Output:
1
2 3
7 6 5 4
2 7 2 4 1 3 9 8
16 17 18 19
In the above example, first two levels
are printed from left to right, next two
254
Chapter 41. Level order traversal with direction change after every two levels
Approach:
We make use of queue and stack here. Queue is used for performing normal level order
traversal. Stack is used for reversing the direction of traversal after every two levels.
While doing normal level order traversal, first two levels nodes are printed at the time when
they are popped out from the queue. For the next two levels, we instead of printing the
nodes, pushed them onto the stack. When all nodes of current level are popped out, we
print the nodes in the stack. In this way, we print the nodes in right to left order by making
use of the stack. Now for the next two levels we again do normal level order traversal for
printing nodes from left to right. Then for the next two nodes, we make use of the stack for
achieving right to left order.
In this way, we will achieve desired modified level order traversal by making use of queue
and stack.
255
Chapter 41. Level order traversal with direction change after every two levels
/* Maintain a stack for printing nodes in reverse
order after they are popped out from queue.*/
stack<Node*> myStack;
struct Node* temp = NULL;
// sz is used for storing the count of nodes in a level
int sz;
// Used for changing the direction of level order traversal
int ct = 0;
// Used for changing the direction of level order traversal
bool rightToLeft = false;
// Push root node to the queue
myQueue.push(node);
// Run this while loop till queue got empty
while (!myQueue.empty()) {
ct++;
sz = myQueue.size();
// Do a normal level order traversal
for (int i = 0; i < sz; i++) {
temp = myQueue.front();
myQueue.pop();
/*For printing nodes from left to right,
simply print the nodes in the order in which
they are being popped out from the queue.*/
if (rightToLeft == false)
cout << temp->data << " ";
/* For printing nodes from right to left,
push the nodes to stack instead of printing them.*/
else
myStack.push(temp);
if (temp->left)
myQueue.push(temp->left);
if (temp->right)
myQueue.push(temp->right);
}
256
Chapter 41. Level order traversal with direction change after every two levels
257
Chapter 41. Level order traversal with direction change after every two levels
root->right->left->right = newNode(2);
root->right->right->left = newNode(7);
root->right->right->right = newNode(2);
root->left->right->left->left = newNode(16);
root->left->right->left->right = newNode(17);
root->right->left->right->left = newNode(18);
root->right->right->left->right = newNode(19);
modifiedLevelOrder(root);
return 0;
}
Output:
1
2 3
7 6 5 4
2 7 2 4 1 3 9 8
16 17 18 19
Time Complexity: Each node is traversed at most twice while doing level order traversal,
so time complexity would be O(n).
Approach 2:
We make use of queue and stack here, but in a different way. Using macros #define
ChangeDirection(Dir) ((Dir) = 1 – (Dir)). In following implementation directs the order of
push operations in both queue or stack.
In this way, we will achieve desired modified level order traversal by making use of queue
and stack.
258
Chapter 41. Level order traversal with direction change after every two levels
259
Chapter 41. Level order traversal with direction change after every two levels
if (temp->left)
Q.push(temp->left);
}
}
cout << endl;
// for printing the nodes in order
// from right to left
while (!Q.empty())
{
temp = Q.front();
Q.pop();
cout << temp->data << " ";
if (dir == LEFT) {
if (temp->left)
S.push(temp->left);
if (temp->right)
S.push(temp->right);
} else {
if (temp->right)
S.push(temp->right);
if (temp->left)
S.push(temp->left);
}
}
cout << endl;
// Change the direction of traversal.
ChangeDirection(dir);
}
}
// Driver program to test above functions
int main()
{
// Let us create binary tree
node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(4);
root->left->right = newNode(5);
root->right->left = newNode(6);
root->right->right = newNode(7);
root->left->left->left = newNode(8);
root->left->left->right = newNode(9);
root->left->right->left = newNode(3);
260
Chapter 41. Level order traversal with direction change after every two levels
root->left->right->right = newNode(1);
root->right->left->left = newNode(4);
root->right->left->right = newNode(2);
root->right->right->left = newNode(7);
root->right->right->right = newNode(2);
root->left->right->left->left = newNode(16);
root->left->right->left->right = newNode(17);
root->right->left->right->left = newNode(18);
root->right->right->left->right = newNode(19);
modifiedLevelOrder(root);
return 0;
}
Output:
1
2 3
7 6 5 4
2 7 2 4 1 3 9 8
16 17 18 19
Time Complexity: every node is also traversed twice. There time complexity is still O(n).
Improved By : vhinf2047
Source
https://www.geeksforgeeks.org/level-order-traversal-direction-change-every-two-levels/
261
Chapter 42
Approach :
Use a stack and a queue. First sort all the lengths and push them onto a stack. Now, take
the top element of stack, and divide by 2 and push the remaining length to queue. Now,
from next customer onwards :
1. If stack is empty, pop front queue and push back to queue. It’s half (front / 2), if non
zero.
262
Chapter 42. Maximum length of rod for Q-th person
2. If queue is empty, pop from stack and push to queue it’s half (top / 2), if non zero.
3. If both are non empty, compare top and front, which ever is larger should be popped,
divided by 2 and then pushed back.
4. If both are empty, store is empty! Stop here!
At each step above store the length available to ith customer in separate array, say “ans”.
Now, start answering the queries by giving ans[Qi ] as output.
Below is the implementation of above approach :
263
Chapter 42. Maximum length of rod for Q-th person
264
Chapter 42. Maximum length of rod for Q-th person
int query[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int size = sizeof(query) / sizeof(query[0]);
for (int i = 0; i < size; i++)
cout << ans[query[i] - 1] << " ";
return 0;
}
Output:
12 10 9 6 6 5 5 4 3 3
Source
https://www.geeksforgeeks.org/maximum-length-rod-q-th-person/
265
Chapter 43
266
Chapter 43. Minimum number of bracket reversals needed to make an expression balanced
One simple observation is, the string can be balanced only if total number of brackets is
even (there must be equal no of ‘{‘ and ‘}’)
A Naive Solution is to consider every bracket and recursively count number of reversals
by taking two cases (i) keeping the bracket as it is (ii) reversing the bracket. If we get a
balanced expression, we update result if number of steps followed for reaching here is smaller
than the minimum so far. Time complexity of this solution is O(2n ).
An Efficient Solution can solve this problem in O(n) time. The idea is to first remove
all balanced part of expression. For example, convert “}{{}}{{{” to “}{{{” by removing
highlighted part. If we take a closer look, we can notice that, after removing balanced part,
we always end up with an expression of the form }}…}{{…{, an expression that contains 0
or more number of closing brackets followed by 0 or more numbers of opening brackets.
How many minimum reversals are required for an expression of the form “}}..}{{..{” ?. Let
m be the total number of closing brackets and n be the number of opening brackets. We
need �m/2� + �n/2� reversals. For example }}}}{{ requires 2+1 reversals.
Below is implementation of above idea.
C++
267
Chapter 43. Minimum number of bracket reversals needed to make an expression balanced
else
s.push(expr[i]);
}
else
s.push(expr[i]);
}
// Length of the reduced expression
// red_len = (m+n)
int red_len = s.size();
// count opening brackets at the end of
// stack
int n = 0;
while (!s.empty() && s.top() == '{')
{
s.pop();
n++;
}
// return ceil(m/2) + ceil(n/2) which is
// actually equal to (m+n)/2 + n%2 when
// m+n is even.
return (red_len/2 + n%2);
}
// Driver program to test above function
int main()
{
string expr = "}}{{";
cout << countMinReversals(expr);
return 0;
}
Java
268
Chapter 43. Minimum number of bracket reversals needed to make an expression balanced
{
int len = expr.length();
// length of expression must be even to make
// it balanced by using reversals.
if (len%2 != 0)
return -1;
// After this loop, stack contains unbalanced
// part of expression, i.e., expression of the
// form "}}..}{{..{"
Stack<Character> s=new Stack<>();
for (int i=0; i<len; i++)
{
char c = expr.charAt(i);
if (c =='}' && !s.empty())
{
if (s.peek()=='{')
s.pop();
else
s.push(c);
}
else
s.push(c);
}
// Length of the reduced expression
// red_len = (m+n)
int red_len = s.size();
// count opening brackets at the end of
// stack
int n = 0;
while (!s.empty() && s.peek() == '{')
{
s.pop();
n++;
}
// return ceil(m/2) + ceil(n/2) which is
// actually equal to (m+n)/2 + n%2 when
// m+n is even.
return (red_len/2 + n%2);
}
// Driver method
public static void main(String[] args)
269
Chapter 43. Minimum number of bracket reversals needed to make an expression balanced
{
String expr = "}}{{";
System.out.println(countMinReversals(expr));
}
}
//This code is contributed by Sumit Ghosh
Output:
Source
https://www.geeksforgeeks.org/minimum-number-of-bracket-reversals-needed-to-make-an-expression-balanced/
270
Chapter 44
This problem can be seen as shortest path in unweighted graph. Therefore we use BFS
to solve this problem. We try all 8 possible positions where a Knight can reach from its
position. If reachable position is not already visited and is inside the board, we push this
state into queue with distance 1 more than its parent state. Finally we return distance of
target position, when it gets pop out from queue.
Below code implements BFS for searching through cells, where each cell contains its coor-
dinate and distance from starting node. In worst case, below code visits all cells of board,
making worst-case time complexity as O(N^2)
271
Chapter 44. Minimum steps to reach target by a Knight | Set 1
struct cell
{
int x, y;
int dis;
cell() {}
cell(int x, int y, int dis) : x(x), y(y), dis(dis) {}
};
// Utility method returns true if (x, y) lies
// inside Board
bool isInside(int x, int y, int N)
{
if (x >= 1 && x <= N && y >= 1 && y <= N)
return true;
return false;
}
// Method returns minimum step to reach target position
int minStepToReachTarget(int knightPos[], int targetPos[],
int N)
{
// x and y direction, where a knight can move
int dx[] = {-2, -1, 1, 2, -2, -1, 1, 2};
int dy[] = {-1, -2, -2, -1, 1, 2, 2, 1};
// queue for storing states of knight in board
queue<cell> q;
// push starting position of knight with 0 distance
q.push(cell(knightPos[0], knightPos[1], 0));
cell t;
int x, y;
bool visit[N + 1][N + 1];
// make all cell unvisited
for (int i = 1; i <= N; i++)
for (int j = 1; j <= N; j++)
visit[i][j] = false;
// visit starting state
visit[knightPos[0]][knightPos[1]] = true;
// loop untill we have one element in queue
while (!q.empty())
{
t = q.front();
q.pop();
272
Chapter 44. Minimum steps to reach target by a Knight | Set 1
// if current cell is equal to target cell,
// return its distance
if (t.x == targetPos[0] && t.y == targetPos[1])
return t.dis;
// loop for all reachable states
for (int i = 0; i < 8; i++)
{
x = t.x + dx[i];
y = t.y + dy[i];
// If reachable state is not yet visited and
// inside board, push that state into queue
if (isInside(x, y, N) && !visit[x][y]) {
visit[x][y] = true;
q.push(cell(x, y, t.dis + 1));
}
}
}
}
// Driver code to test above methods
int main()
{
int N = 30;
int knightPos[] = {1, 1};
int targetPos[] = {30, 30};
cout << minStepToReachTarget(knightPos, targetPos, N);
return 0;
}
Output:
20
Source
https://www.geeksforgeeks.org/minimum-steps-reach-target-knight/
273
Chapter 45
Minimum sum of squares of character counts in a given string after removing k characters -
GeeksforGeeks
Given a string of lowercase alphabets and a number k, the task is to print the minimum
value of the string after removal of ‘k’ characters. The value of a string is defined as the sum
of squares of the count of each distinct character. For example consider the string “saideep”,
here frequencies of characters are s-1, a-1, i-1, e-2, d-1, p-1 and value of the string is 1^2 +
1^2 + 1^2 + 1^2 + 1^1 + 2^2 = 9.
Expected Time Complexity : O(n)
Examples:
Asked In : Amazon
One clear observation is that we need to remove character with highest frequency. One trick
is the character ma
274
Chapter 45. Minimum sum of squares of character counts in a given string after removing
k characters
A Simple solution is to use sorting technique through all current highest frequency reduce
up to k times. For After every reduce again sort frequency array.
A Better Solution used to Priority Queue which has to the highest element on top.
C++
275
Chapter 45. Minimum sum of squares of character counts in a given string after removing
k characters
Java
276
Chapter 45. Minimum sum of squares of character counts in a given string after removing
k characters
@Override
public int compare(Integer arg0, Integer arg1) {
if(arg0 > arg1)
return -1;
else if(arg0 < arg1)
return 1;
else
return 0;
}
}
// Main Function to calculate min sum of
// squares of characters after k removals
static int minStringValue(String str, int k)
{
int l = str.length(); // find length of string
// if K is greater than length of string
// so reduced string will become 0
if (k >= l)
return 0;
// Else find Frequency of each character and
// store in an array
int[] frequency = new int[MAX_CHAR];
for (int i=0; i<l; i++)
frequency[str.charAt(i)-'a']++;
// creating object for comparator
Comparator<Integer> c = new IntCompare();
// creating a priority queue with comparator
// such that elements in the queue are in
// descending order.
PriorityQueue<Integer> q = new PriorityQueue<>(c);
// Push each char frequency into a priority_queue
for (int i = 0; i < MAX_CHAR; i++){
if(frequency[i] != 0)
q.add(frequency[i]);
}
// Removal of K characters
while (k != 0)
{
// Get top element in priority_queue,
277
Chapter 45. Minimum sum of squares of character counts in a given string after removing
k characters
Output:
6
2
Source
https://www.geeksforgeeks.org/minimum-sum-squares-characters-counts-given-string-removing-k-characters/
278
Chapter 46
Input: [6, 8, 4, 5, 2, 3]
Output: 604
The minimum sum is formed by numbers
358 and 246
Input: [5, 3, 0, 7, 4]
Output: 82
The minimum sum is formed by numbers
35 and 047
Since we want to minimize the sum of two numbers to be formed, we must divide all digits
in two halves and assign half-half digits to them. We also need to make sure that the
leading digits are smaller.
We build a Min Heap with the elements of the given array, which takes O(n) worst time.
Now we retrieve min values (2 at a time) of array, by polling from the Priority Queue and
append these two min values to our numbers, till the heap becomes empty, i.e., all the
elements of array get exhausted. We return the sum of two formed numbers, which is our
required answer.
C/C++
279
Chapter 46. Minimum sum of two numbers formed from digits of an array
280
Chapter 46. Minimum sum of two numbers formed from digits of an array
Java
281
Chapter 46. Minimum sum of two numbers formed from digits of an array
Output:
Source
https://www.geeksforgeeks.org/minimum-sum-two-numbers-formed-digits-array-2/
282
Chapter 47
0: Empty cell
So we have to determine what is the minimum time required so that all the oranges become
rotten. A rotten orange at index [i,j] can rot other fresh orange at indexes [i-1,j], [i+1,j],
[i,j-1], [i,j+1] (up, down, left and right). If it is impossible to rot every orange then simply
return -1.
Examples:
283
Chapter 47. Minimum time required to rot all oranges
{1, 0, 0, 2, 1}};
Output:
All oranges cannot be rotten.
1) Create an empty Q.
2) Find all rotten oranges and enqueue them to Q. Also enqueue
a delimiter to indicate beginning of next time frame.
3) While Q is not empty do following
3.a) While delimiter in Q is not reached
(i) Dequeue an orange from queue, rot all adjacent oranges.
While rotting the adjacents, make sure that time frame
is incremented only once. And time frame is not icnremented
if there are no adjacent oranges.
3.b) Dequeue the old delimiter and enqueue a new delimiter. The
oranges rotten in previous time frame lie between the two
delimiters.
284
Chapter 47. Minimum time required to rot all oranges
}
// Function to check whether there is still a fresh
// orange remaining
bool checkall(int arr[][C])
{
for (int i=0; i<R; i++)
for (int j=0; j<C; j++)
if (arr[i][j] == 1)
return true;
return false;
}
// This function finds if it is possible to rot all oranges or not.
// If possible, then it returns minimum time required to rot all,
// otherwise returns -1
int rotOranges(int arr[][C])
{
// Create a queue of cells
queue<ele> Q;
ele temp;
int ans = 0;
// Store all the cells having rotten orange in first time frame
for (int i=0; i<R; i++)
{
for (int j=0; j<C; j++)
{
if (arr[i][j] == 2)
{
temp.x = i;
temp.y = j;
Q.push(temp);
}
}
}
// Separate these rotten oranges from the oranges which will rotten
// due the oranges in first time frame using delimiter which is (-1, -1)
temp.x = -1;
temp.y = -1;
Q.push(temp);
// Process the grid while there are rotten oranges in the Queue
while (!Q.empty())
{
// This flag is used to determine whether even a single fresh
// orange gets rotten due to rotten oranges in current time
285
Chapter 47. Minimum time required to rot all oranges
286
Chapter 47. Minimum time required to rot all oranges
Java
287
Chapter 47. Minimum time required to rot all oranges
288
Chapter 47. Minimum time required to rot all oranges
int ans = 0;
// Store all the cells having rotten orange in first time frame
for (int i=0; i < R; i++)
for (int j=0; j < C; j++)
if (arr[i][j] == 2)
Q.add(new Ele(i,j));
// Separate these rotten oranges from the oranges which will rotten
// due the oranges in first time frame using delimiter which is (-1, -1)
Q.add(new Ele(-1,-1));
// Process the grid while there are rotten oranges in the Queue
while(!Q.isEmpty())
{
// This flag is used to determine whether even a single fresh
// orange gets rotten due to rotten oranges in current time
// frame so we can increase the count of the required time.
boolean flag = false;
// Process all the rotten oranges in current time frame.
while(!isDelim(Q.peek()))
{
temp = Q.peek();
// Check right adjacent cell that if it can be rotten
if(isValid(temp.x+1, temp.y+1) && arr[temp.x+1][temp.y] == 1)
{
if(!flag)
{
// if this is the first orange to get rotten, increase
// count and set the flag.
ans++;
flag = true;
}
// Make the orange rotten
arr[temp.x+1][temp.y] = 2;
// push the adjacent orange to Queue
temp.x++;
Q.add(new Ele(temp.x,temp.y));
// Move back to current cell
temp.x--;
}
// Check left adjacent cell that if it can be rotten
if (isValid(temp.x-1, temp.y) && arr[temp.x-1][temp.y] == 1)
{
289
Chapter 47. Minimum time required to rot all oranges
if (!flag)
{
ans++;
flag = true;
}
arr[temp.x-1][temp.y] = 2;
temp.x--;
Q.add(new Ele(temp.x,temp.y)); // push this cell to Queue
temp.x++;
}
// Check top adjacent cell that if it can be rotten
if (isValid(temp.x, temp.y+1) && arr[temp.x][temp.y+1] == 1) {
if(!flag)
{
ans++;
flag = true;
}
arr[temp.x][temp.y+1] = 2;
temp.y++;
Q.add(new Ele(temp.x,temp.y)); // Push this cell to Queue
temp.y--;
}
// Check bottom adjacent cell if it can be rotten
if (isValid(temp.x, temp.y-1) && arr[temp.x][temp.y-1] == 1)
{
if (!flag)
{
ans++;
flag = true;
}
arr[temp.x][temp.y-1] = 2;
temp.y--;
Q.add(new Ele(temp.x,temp.y)); // push this cell to Queue
}
Q.remove();
}
// Pop the delimiter
Q.remove();
// If oranges were rotten in current frame than separate the
// rotten oranges using delimiter for the next frame for processing.
if (!Q.isEmpty())
{
Q.add(new Ele(-1,-1));
}
290
Chapter 47. Minimum time required to rot all oranges
// If Queue was empty than no rotten oranges left to process so exit
}
// Return -1 if all arranges could not rot, otherwise -1.s
return (checkAll(arr))? -1: ans;
}
// Drive program
public static void main(String[] args)
{
int arr[][] = { {2, 1, 0, 2, 1},
{1, 0, 1, 2, 1},
{1, 0, 0, 2, 1}};
int ans = rotOranges(arr);
if(ans == -1)
System.out.println("All oranges cannot rot");
else
System.out.println("Time required for all oranges to rot = " + ans);
}
}
//This code is contributed by Sumit Ghosh
Output:
Source
https://www.geeksforgeeks.org/minimum-time-required-so-that-all-oranges-become-rotten/
291
Chapter 48
Input :
Number of Vertices = 6
Number of Edges = 9
Towns with Police Station : 1, 5
Edges:
1 2
1 6
2 6
2 3
3 6
5 4
6 5
3 4
5 3
Output :
1 0
2 1
3 1
4 1
5 0
292
Chapter 48. Multi Source Shortest Path in Unweighted Graph
6 1
Naive Approach: We can loop through the vertices and from each vertex run a BFS to
find the closest town with police station from that vertex. This will take O(V.E).
Naive approach implementation using BFS from each vertex:
293
Chapter 48. Multi Source Shortest Path in Unweighted Graph
294
Chapter 48. Multi Source Shortest Path in Unweighted Graph
int main()
{ // Number of vertices
int n = 6;
vector<int> graph[n + 1];
// Edges
addEdge(graph, 1, 2);
addEdge(graph, 1, 6);
addEdge(graph, 2, 6);
addEdge(graph, 2, 3);
addEdge(graph, 3, 6);
addEdge(graph, 5, 4);
addEdge(graph, 6, 5);
addEdge(graph, 3, 4);
addEdge(graph, 5, 3);
// Sources
int sources[] = { 1, 5 };
int S = sizeof(sources) / sizeof(sources[0]);
nearestTown(graph, n, sources, S);
return 0;
}
Output:
1 0
2 1
3 1
4 1
5 0
6 1
295
Chapter 48. Multi Source Shortest Path in Unweighted Graph
On each step, we will go to the vertex with minimum distance(d) from source, i.e, the first
element of the set (the source itself in the first step with distance = 0). We go through all
it’s adjacent vertices and if the distance of any vertex is > d + 1 we replace its entry in the
set with the new distance. Then we remove the current vertex from the set. We continue
this until the set is empty.
The idea is there cannot be a shorter path to the vertex at the front of the set than the
current one since any other path will be a sum of a longer path (>= it’s length) and a
non-negative path length (unless we are considering negative edges).
Since all the sources have a distance = 0, in the beginning, the adjacent non-source vertices
will get a distance = 1. All vertices will get distance = distance from their nearest source.
Implementation of Efficient Approach:
296
Chapter 48. Multi Source Shortest Path in Unweighted Graph
297
Chapter 48. Multi Source Shortest Path in Unweighted Graph
multiSourceBFSUtil(graph, start);
// Printing the distances
for (int i = 1; i <= n; i++)
cout << i << " " << dist[i] << endl;
}
void addEdge(vector<int> graph[], int u, int v)
{
graph[u].push_back(v);
graph[v].push_back(u);
}
// Driver Code
int main()
{
// Number of vertices
int n = 6;
vector<int> graph[n + 1];
// Edges
addEdge(graph, 1, 2);
addEdge(graph, 1, 6);
addEdge(graph, 2, 6);
addEdge(graph, 2, 3);
addEdge(graph, 3, 6);
addEdge(graph, 5, 4);
addEdge(graph, 6, 5);
addEdge(graph, 3, 4);
addEdge(graph, 5, 3);
// Sources
int sources[] = { 1, 5 };
int S = sizeof(sources) / sizeof(sources[0]);
multiSourceBFS(graph, n, sources, S);
return 0;
}
Output:
1 0
2 1
298
Chapter 48. Multi Source Shortest Path in Unweighted Graph
3 1
4 1
5 0
6 1
Source
https://www.geeksforgeeks.org/multi-source-shortest-path-in-unweighted-graph/
299
Chapter 49
Example :
Input : 30
Output : 3
300
Chapter 49. Number of siblings of a given Node in n-ary Tree
Approach : For every node in the given n-ary tree, push the children of the current node
in the queue. While adding the children of current node in queue, check if any children is
equal to the given value x or not. If yes, then return the number of siblings of x.
Below is the implementation of the above idea :
301
Chapter 49. Number of siblings of a given Node in n-ary Tree
302
Chapter 49. Number of siblings of a given Node in n-ary Tree
Output:
Source
https://www.geeksforgeeks.org/number-siblings-given-node-n-ary-tree/
303
Chapter 50
Input : 7
/ \
6 5
/ \ / \
4 3 2 1
Output :
7
5 6
1 2 3 4
Input : 7
/ \
16 1
/ \
4 13
Output :
7
1 16
4 13
Here we can use two Priority queue for print in sorted order. We create an empty queue
q and two priority queues, current_level and next_level. We use NULL as a separator
between two levels. Whenever we encounter NULL in normal level order traversal, we swap
current_level and next_level.
304
Chapter 50. Print Binary Tree levels in sorted order
305
Chapter 50. Print Binary Tree levels in sorted order
306
Chapter 50. Print Binary Tree levels in sorted order
Output:
Source
https://www.geeksforgeeks.org/print-binary-tree-levels-sorted-order/
307
Chapter 51
Print Binary Tree levels in sorted order | Set 2 (Using set) - GeeksforGeeks
Given a tree, print the level order traversal in sorted order.
Examples :
Input : 7
/ \
6 5
/ \ / \
4 3 2 1
Output :
7
5 6
1 2 3 4
Input : 7
/ \
16 1
/ \
4 13
Output :
7
1 16
4 13
308
Chapter 51. Print Binary Tree levels in sorted order | Set 2 (Using set)
In this post, a set (which is implemented using balanced binary search tree) based solution
is discussed.
Approach :
1. Start level order traversal of tree.
2. Store all the nodes in a set(or any other similar data structures).
3. Print elements of set.
C++
309
Chapter 51. Print Binary Tree levels in sorted order | Set 2 (Using set)
else {
s.insert(tmp->data);
if (tmp->left != nullptr)
q.push(tmp->left);
if (tmp->right != nullptr)
q.push(tmp->right);
}
}
}
// Driver code
int main()
{
Node* root = new Node(7);
root->left = new Node(6);
root->right = new Node(5);
root->left->left = new Node(4);
root->left->right = new Node(3);
root->right->left = new Node(2);
root->right->right = new Node(1);
sorted_level_order(root);
return 0;
}
Output:
7 5 6 1 2 3 4
Source
https://www.geeksforgeeks.org/print-binary-tree-levels-sorted-order-2/
310
Chapter 52
1
/ \
2 3
/ \ / \
4 5 6 7
Top view of the above binary tree is
4 2 1 3 7
1
/ \
2 3
\
4
\
5
\
6
Top view of the above binary tree is
2 1 3 6
311
Chapter 52. Print Nodes in Top View of Binary Tree
The idea is to do something similar to vertical Order Traversal. Like vertical Order Traversal,
we need to nodes of same horizontal distance together. We do a level order traversal so that
the topmost node at a horizontal node is visited before any other node of same horizontal
distance below it. Hashing is used to check if a node at given horizontal distance is seen or
not.
C++
312
Chapter 52. Print Nodes in Top View of Binary Tree
if (n->right != NULL)
q.push(make_pair(n->right, val + 1));
}
}
// function to create a new node
struct Node* newNode(int key)
{
struct Node* node = new Node;
node->data = key;
node->left = node->right = NULL;
return node;
}
// main function
int main()
{
/* Create following Binary Tree
1
/ \
2 3
\
4
\
5
\
6*/
Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->right = newNode(4);
root->left->right->right = newNode(5);
root->left->right->right->right = newNode(6);
topView(root);
return 0;
}
/* This code is contributed by Niteesh Kumar */
Java
313
Chapter 52. Print Nodes in Top View of Binary Tree
class TreeNode {
// Members
int key;
TreeNode left, right;
// Constructor
public TreeNode(int key)
{
this.key = key;
left = right = null;
}
}
// A class to represent a queue item. The queue is used to do Level
// order traversal. Every Queue item contains node and horizontal
// distance of node from root
class QItem {
TreeNode node;
int hd;
public QItem(TreeNode n, int h)
{
node = n;
hd = h;
}
}
// Class for a Binary Tree
class Tree {
TreeNode root;
// Constructors
public Tree() { root = null; }
public Tree(TreeNode n) { root = n; }
// This method prints nodes in top view of binary tree
public void printTopView()
{
// base case
if (root == null) {
return;
}
// Creates an empty hashset
HashSet<Integer> set = new HashSet<>();
// Create a queue and add root to it
Queue<QItem> Q = new LinkedList<QItem>();
Q.add(new QItem(root, 0)); // Horizontal distance of root is 0
314
Chapter 52. Print Nodes in Top View of Binary Tree
// Standard BFS or level order traversal loop
while (!Q.isEmpty()) {
// Remove the front item and get its details
QItem qi = Q.remove();
int hd = qi.hd;
TreeNode n = qi.node;
// If this is the first node at its horizontal distance,
// then this node is in top view
if (!set.contains(hd)) {
set.add(hd);
System.out.print(n.key + " ");
}
// Enqueue left and right children of current node
if (n.left != null)
Q.add(new QItem(n.left, hd - 1));
if (n.right != null)
Q.add(new QItem(n.right, hd + 1));
}
}
}
// Driver class to test above methods
public class Main {
public static void main(String[] args)
{
/* Create following Binary Tree
1
/ \
2 3
\
4
\
5
\
6*/
TreeNode root = new TreeNode(1);
root.left = new TreeNode(2);
root.right = new TreeNode(3);
root.left.right = new TreeNode(4);
root.left.right.right = new TreeNode(5);
root.left.right.right.right = new TreeNode(6);
Tree t = new Tree(root);
System.out.println("Following are nodes in top view of Binary Tree");
t.printTopView();
}
315
Chapter 52. Print Nodes in Top View of Binary Tree
Output:
Time Complexity of the above implementation is O(n) where n is number of nodes in given
binary tree. The assumption here is that add() and contains() methods of HashSet work in
O(1) time.
This article is contributed by Rohan. Please write comments if you find anything incorrect,
or you want to share more information about the topic discussed above.
Improved By : Aarsee
Source
https://www.geeksforgeeks.org/print-nodes-top-view-binary-tree/
316
Chapter 53
317
Chapter 53. Priority Queue in Python
item = self.queue[max]
del self.queue[max]
return item
except IndexError:
print()
exit()
if __name__ == '__main__':
myQueue = PriorityQueue()
myQueue.insert(12)
myQueue.insert(1)
myQueue.insert(14)
myQueue.insert(7)
print(myQueue)
while not myQueue.isEmpty():
print(myQueue.delete())
Output:
12 1 14 7
14
12
7
1
()
Source
https://www.geeksforgeeks.org/priority-queue-in-python/
318
Chapter 54
• push(): This function is used to insert a new data into the queue.
• pop(): This function removes the element with the highest priority form the queue.
• peek() / top(): This function is used to get the highest priority element in the queue
without removing it from the queue.
Priority Queues can be implemented using common data structures like arrays, linked-lists,
heaps and binary trees.
Prerequisites :
Linked Lists, Priority Queues
The list is so created so that the highest priority element is always at the head of the list.
The list is arranged in descending order of elements based on their priority. This allow us to
remove the highest priority element in O(1) time. To insert an element we must traverse the
list and find the proper position to insert the node so that the overall order of the priority
queue is maintained. This makes the push() operation takes O(N) time. The pop() and
peek() operations are performed in constant time.
Algorithm :
PUSH(HEAD, DATA, PRIORITY)
Step 1: Create new node with DATA and PRIORITY
Step 2: Check if HEAD has lower priority. If true follow Steps 3-4 and end. Else goto Step
5.
Step 3: NEW -> NEXT = HEAD
Step 4: HEAD = NEW
Step 5: Set TEMP to head of the list
319
Chapter 54. Priority Queue using Linked List
Step 6: While TEMP -> NEXT != NULL and TEMP -> NEXT -> PRIORITY > PRI-
ORITY
Step 7: TEMP = TEMP -> NEXT
[END OF LOOP]
Step 8: NEW -> NEXT = TEMP -> NEXT
Step 9: TEMP -> NEXT = NEW
Step 10: End
POP(HEAD)
Step 2: Set the head of the list to the next node in the list. HEAD = HEAD -> NEXT.
Step 3: Free the node at the head of the list
Step 4: End
PEEK(HEAD):
Step 1: Return HEAD -> DATA
Step 2: End
Below is the implementation of the algorithm :
C
320
Chapter 54. Priority Queue using Linked List
{
return (*head)->data;
}
// Removes the element with the
// highest priority form the list
void pop(Node** head)
{
Node* temp = *head;
(*head) = (*head)->next;
free(temp);
}
// Function to push according to priority
void push(Node** head, int d, int p)
{
Node* start = (*head);
// Create new Node
Node* temp = newNode(d, p);
// Special Case: The head of list has lesser
// priority than new node. So insert new
// node before head node and change head node.
if ((*head)->priority > p) {
// Insert New Node before head
temp->next = *head;
(*head) = temp;
}
else {
// Traverse the list and find a
// position to insert new node
while (start->next != NULL &&
start->next->priority < p) {
start = start->next;
}
// Either at the ends of the list
// or at required position
temp->next = start->next;
start->next = temp;
}
}
// Function to check is list is empty
int isEmpty(Node** head)
321
Chapter 54. Priority Queue using Linked List
{
return (*head) == NULL;
}
// Driver code
int main()
{
// Create a Priority Queue
// 7->4->5->6
Node* pq = newNode(4, 1);
push(&pq, 5, 2);
push(&pq, 6, 3);
push(&pq, 7, 0);
while (!isEmpty(&pq)) {
printf("%d ", peek(&pq));
pop(&pq);
}
return 0;
}
Output:
7 4 5 6
Source
https://www.geeksforgeeks.org/priority-queue-using-linked-list/
322
Chapter 55
• push(): This function is used to insert a new data into the queue.
• pop(): This function removes the element with the lowest priority value form the
queue.
• peek() / top(): This function is used to get the lowest priority element in the queue
without removing it from the queue.
Approach :
1. Create a doubly linked list having fields info(hold the information of the Node), prior-
ity(hold the priority of the Node), prev(point to previous Node), next(point to next Node).
2. Insert the element and priority in the Node.
3. Arrange the Nodes in the increasing order of the priority.
Below is the implementation of above steps :
C++
323
Chapter 55. Priority Queue using doubly linked list
int priority;
struct Node *prev, *next;
};
// Function to insert a new Node
void push(Node** fr, Node** rr, int n, int p)
{
Node* news = (Node*)malloc(sizeof(Node));
news->info = n;
news->priority = p;
// If linked list is empty
if (*fr == NULL) {
*fr = news;
*rr = news;
news->next = NULL;
}
else {
// If p is less than or equal front
// node's priority, then insert at
// the front.
if (p <= (*fr)->priority) {
news->next = *fr;
(*fr)->prev = news->next;
*fr = news;
}
// If p is more rear node's priority,
// then insert after the rear.
else if (p > (*rr)->priority) {
news->next = NULL;
(*rr)->next = news;
news->prev = (*rr)->next;
*rr = news;
}
// Handle other cases
else {
// Find position where we need to
// insert.
Node* start = (*fr)->next;
while (start->priority > p)
start = start->next;
(start->prev)->next = news;
news->next = start->prev;
news->prev = (start->prev)->next;
start->prev = news->next;
324
Chapter 55. Priority Queue using doubly linked list
}
}
}
// Return the value at rear
int peek(Node *fr)
{
return fr->info;
}
bool isEmpty(Node *fr)
{
return (fr == NULL);
}
// Removes the element with the
// least priority value form the list
int pop(Node** fr, Node** rr)
{
Node* temp = *fr;
int res = temp->info;
(*fr) = (*fr)->next;
free(temp);
if (*fr == NULL)
*rr = NULL;
return res;
}
// Diver code
int main()
{
Node *front = NULL, *rear = NULL;
push(&front, &rear, 2, 3);
push(&front, &rear, 3, 4);
push(&front, &rear, 4, 5);
push(&front, &rear, 5, 6);
push(&front, &rear, 6, 7);
push(&front, &rear, 1, 2);
cout << pop(&front, &rear) << endl;
cout << peek(front);
return 0;
}
Output:
325
Chapter 55. Priority Queue using doubly linked list
1
2
Related Article :
Priority Queue using Singly Linked List
Time Complexities and Comparison with Binary Heap:
Source
https://www.geeksforgeeks.org/priority-queue-using-doubly-linked-list/
326
Chapter 56
struct item {
int item;
int priority;
}
insert() operation can be implemented by adding an item at end of array in O(1) time.
getHighestPriority() operation can be implemented by linearly searching the highest priority
item in array. This operation takes O(n) time.
deleteHighestPriority() operation can be implemented by first linearly searching an item,
then removing the item by moving all subsequent items one position back.
We can also use Linked List, time complexity of all operations with linked list remains same
as array. The advantage with linked list is deleteHighestPriority() can be more efficient as
we don’t have to move items.
327
Chapter 56. Priority Queue | Set 1 (Introduction)
Using Heaps:
Heap is generally preferred for priority queue implementation because heaps provide better
performance compared arrays or linked list. In a Binary Heap, getHighestPriority() can be
implemented in O(1) time, insert() can be implemented in O(Logn) time and deleteHighest-
Priority() can also be implemented in O(Logn) time.
With Fibonacci heap, insert() and getHighestPriority() can be implemented in O(1) amor-
tized time and deleteHighestPriority() can be implemented in O(Logn) amortized time.
Applications of Priority Queue:
1) CPU Scheduling
2) Graph algorithms like Dijkstra’s shortest path algorithm, Prim’s Minimum Spanning
Tree, etc
3) All queue applications where priority is involved.
A priority queue is implemented using Heap. Please refer below articles for our own imple-
mentation and library implementations.
Useful Links :
References:
http://en.wikipedia.org/wiki/Priority_queue
Source
https://www.geeksforgeeks.org/priority-queue-set-1-introduction/
328
Chapter 57
329
Chapter 57. Program for Page Replacement Algorithms | Set 2 (FIFO)
C++
330
Chapter 57. Program for Page Replacement Algorithms | Set 2 (FIFO)
// To store the pages in FIFO manner
queue<int> indexes;
// Start from initial page
int page_faults = 0;
for (int i=0; i<n; i++)
{
// Check if the set can hold more pages
if (s.size() < capacity)
{
// Insert it into set if not present
// already which represents page fault
if (s.find(pages[i])==s.end())
{
s.insert(pages[i]);
// increment page fault
page_faults++;
// Push the current page into the queue
indexes.push(pages[i]);
}
}
// If the set is full then need to perform FIFO
// i.e. remove the first page of the queue from
// set and queue both and insert the current page
else
{
// Check if current page is not already
// present in the set
if (s.find(pages[i]) == s.end())
{
//Pop the first page from the queue
int val = indexes.front();
indexes.pop();
// Remove the indexes page
s.erase(val);
// insert the current page
s.insert(pages[i]);
// push the current page into
// the queue
indexes.push(pages[i]);
331
Chapter 57. Program for Page Replacement Algorithms | Set 2 (FIFO)
// Increment page faults
page_faults++;
}
}
}
return page_faults;
}
// Driver code
int main()
{
int pages[] = {7, 0, 1, 2, 0, 3, 0, 4,
2, 3, 0, 3, 2};
int n = sizeof(pages)/sizeof(pages[0]);
int capacity = 4;
cout << pageFaults(pages, n, capacity);
return 0;
}
Java
332
Chapter 57. Program for Page Replacement Algorithms | Set 2 (FIFO)
333
Chapter 57. Program for Page Replacement Algorithms | Set 2 (FIFO)
}
// Driver method
public static void main(String args[])
{
int pages[] = {7, 0, 1, 2, 0, 3, 0, 4,
2, 3, 0, 3, 2};
int capacity = 4;
System.out.println(pageFaults(pages, pages.length, capacity));
}
}
// This code is contributed by Gaurav Miglani
Output:
Note – We can also find the number of page hits. Just have to maintain a separate count.
If the current page is already in the memory then that must be count as Page-hit.
Belady’s anomaly –
Belady’s anomaly proves that it is possible to have more page faults when increasing the
number of page frames while using the First in First Out (FIFO) page replacement algorithm.
For example, if we consider reference string 3, 2, 1, 0, 3, 2, 4, 3, 2, 1, 0, 4 and 3 slots, we
get 9 total page faults, but if we increase slots to 4, we get 10 page faults.
Improved By : Villan
Source
https://www.geeksforgeeks.org/program-page-replacement-algorithms-set-2-fifo/
334
Chapter 58
• The Queue is used to insert elements at the end of the queue and removes from the
beginning of the queue. It follows FIFO concept.
• The Java Queue supports all methods of Collection interface including insertion, dele-
tion etc.
• LinkedList, ArrayBlockingQueue and PriorityQueue are the most frequently used im-
plementations.
• If any null operation is performed on BlockingQueues, NullPointerException is thrown.
• BlockingQueues have thread-safe implementations.
• The Queues which are available in java.util package are Unbounded Queues
• The Queues which are available in java.util.concurrent package are the Bounded
Queues.
• All Queues except the Deques supports insertion and removal at the tail and head of
the queue respectively. The Deques support element insertion and removal at both
ends.
Methods in Queue:
1. add()- This method is used to add elements at the tail of queue. More specifically, at
the last of linkedlist if it is used, or according to the priority in case of priority queue
implementation.
335
Chapter 58. Queue Interface In Java
2. peek()- This method is used to view the head of queue without removing it. It returns
Null if the queue is empty.
3. element()- This method is similar to peek(). It throws NoSuchElementException
when the queue is empty.
4. remove()- This method removes and returns the head of the queue. It throws No-
SuchElementException when the queue is impty.
5. poll()- This method removes and returns the head of the queue. It returns null if the
queue is empty.
Since it is a subtype of Collections class, it inherits all the methods of it namely size(),
isEmpty(), contains() etc.
Below is a simple Java program to demonstrate these methods:
336
Chapter 58. Queue Interface In Java
// Rest all methods of collection interface,
// Like size and contains can be used with this
// implementation.
int size = q.size();
System.out.println("Size of queue-" + size);
}
}
Output:
Elements of queue-[0, 1, 2, 3, 4]
removed element-0
[1, 2, 3, 4]
head of queue-1
Size of queue-4
Source
https://www.geeksforgeeks.org/queue-interface-java/
337
Chapter 59
Input : a a b c
Output : a -1 b b
Input : a a c
Output : a -1 c
We have already discussed a Doubly linked list based approach in the previous post.
Approach-
1. Create a count array of size 26(assuming only lower case characters are present) and
initialize it with zero.
2. Create a queue of char datatype.
3. Store each character in queue and increase its frequency in the hash array.
4. For every character of stream, we check front of the queue.
5. If the frequency of character at the front of queue is one, then that will be the first
non repeating character.
6. Else if frequency is more than 1, then we pop that element.
7. If queue became empty that means there are no non repeating character so we will
print -1.
338
Chapter 59. Queue based approach for first non-repeating character in a stream
C++
339
Chapter 59. Queue based approach for first non-repeating character in a stream
Java
340
Chapter 59. Queue based approach for first non-repeating character in a stream
}
System.out.println();
}
// Driver function
public static void main(String[] args)
{
String str = "aabc";
firstNonRepeating(str);
}
}
//This code is Contributed by Sumit Ghosh
Output:
a -1 b b
Source
https://www.geeksforgeeks.org/queue-based-approach-for-first-non-repeating-character-in-a-stream/
341
Chapter 60
A queue can be implemented using two stacks. Let queue to be implemented be q and stacks
used to implement q be stack1 and stack2. q can be implemented in two ways:
Method 1 (By making enQueue operation costly) This method makes sure that oldest
entered element is always at the top of stack 1, so that deQueue operation just pops from
stack1. To put the element at top of stack1, stack2 is used.
342
Chapter 60. Queue using Stacks
enQueue(q, x)
1) While stack1 is not empty, push everything from stack1 to stack2.
2) Push x to stack1 (assuming size of stacks is unlimited).
3) Push everything back to stack1.
Here time complexity will be O(n)
deQueue(q)
1) If stack1 is empty then error
2) Pop an item from stack1 and return it
Here time complexity will be O(1)
C++
343
Chapter 60. Queue using Stacks
Method 2 (By making deQueue operation costly)In this method, in en-queue oper-
ation, the new element is entered at the top of stack1. In de-queue operation, if stack2 is
empty then all the elements are moved to stack2 and finally top of stack2 is returned.
enQueue(q, x)
1) Push x to stack1 (assuming size of stacks is unlimited).
Here time complexity will be O(1)
deQueue(q)
1) If both stacks are empty then error.
2) If stack2 is empty
While stack1 is not empty, push everything from stack1 to stack2.
3) Pop the element from stack2 and return it.
Here time complexity will be O(n)
344
Chapter 60. Queue using Stacks
#include <bits/stdc++.h>
using namespace std;
struct Queue {
stack<int> s1, s2;
// Enqueue an item to the queue
void enQueue(int x)
{
// Push item into the first stack
s1.push(x);
}
// Dequeue an item from the queue
int deQueue()
{
// if both stacks are empty
if (s1.empty() && s2.empty()) {
cout << "Q is empty";
exit(0);
}
// if s2 is empty, move
// elements from s1
if (s2.empty()) {
while (!s1.empty()) {
s2.push(s1.top());
s1.pop();
}
}
// return the top item from s2
int x = s2.top();
s2.pop();
return x;
}
};
// Driver code
int main()
{
Queue q;
q.enQueue(1);
q.enQueue(2);
q.enQueue(3);
cout << q.deQueue() << '\n';
cout << q.deQueue() << '\n';
345
Chapter 60. Queue using Stacks
346
Chapter 60. Queue using Stacks
stack2 is empty */
if (q->stack2 == NULL) {
while (q->stack1 != NULL) {
x = pop(&q->stack1);
push(&q->stack2, x);
}
}
x = pop(&q->stack2);
return x;
}
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data)
{
/* allocate node */
struct sNode* new_node = (struct sNode*)malloc(sizeof(struct sNode));
if (new_node == NULL) {
printf("Stack overflow \n");
getchar();
exit(0);
}
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*top_ref);
/* move the head to point to the new node */
(*top_ref) = new_node;
}
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref)
{
int res;
struct sNode* top;
/*If stack is empty then error */
if (*top_ref == NULL) {
printf("Stack underflow \n");
getchar();
exit(0);
}
else {
top = *top_ref;
res = top->data;
347
Chapter 60. Queue using Stacks
*top_ref = top->next;
free(top);
return res;
}
}
/* Driver function to test anove functions */
int main()
{
/* Create a queue with items 1 2 3*/
struct queue* q = (struct queue*)malloc(sizeof(struct queue));
q->stack1 = NULL;
q->stack2 = NULL;
enQueue(q, 1);
enQueue(q, 2);
enQueue(q, 3);
/* Dequeue items */
printf("%d ", deQueue(q));
printf("%d ", deQueue(q));
printf("%d ", deQueue(q));
return 0;
}
Java
348
Chapter 60. Queue using Stacks
{
/*If stack is empty then error */
if (top_ref.isEmpty()) {
System.out.println("Stack Underflow");
System.exit(0);
}
// pop the data from the stack
return top_ref.pop();
}
// Function to enqueue an item to the queue
static void enQueue(Queue q, int x)
{
push(q.stack1, x);
}
/* Function to deQueue an item from queue */
static int deQueue(Queue q)
{
int x;
/* If both stacks are empty then error */
if (q.stack1.isEmpty() && q.stack2.isEmpty()) {
System.out.println("Q is empty");
System.exit(0);
}
/* Move elements from stack1 to stack 2 only if
stack2 is empty */
if (q.stack2.isEmpty()) {
while (!q.stack1.isEmpty()) {
x = pop(q.stack1);
push(q.stack2, x);
}
}
x = pop(q.stack2);
return x;
}
/* Driver function to test above functions */
public static void main(String args[])
{
/* Create a queue with items 1 2 3*/
Queue q = new Queue();
q.stack1 = new Stack<>();
q.stack2 = new Stack<>();
enQueue(q, 1);
349
Chapter 60. Queue using Stacks
enQueue(q, 2);
enQueue(q, 3);
/* Dequeue items */
System.out.print(deQueue(q) + " ");
System.out.print(deQueue(q) + " ");
System.out.println(deQueue(q) + " ");
}
}
// This code is contributed by Sumit Ghosh
Output:
1 2 3
Queue can also be implemented using one user stack and one Function Call
Stack. Below is modified Method 2 where recursion (or Function Call Stack) is used to
implement queue using only one user defined stack.
enQueue(x)
1) Push x to stack1.
deQueue:
1) If stack1 is empty then error.
2) If stack1 has only one element then return it.
3) Recursively pop everything from the stack1, store the popped item
in a variable res, push the res back to stack1 and return res
The step 3 makes sure that the last popped item is always returned and since the recursion
stops when there is only one item in stack1 (step 2), we get the last element of stack1 in
deQueue() and all other items are pushed back in step
3. Implementation of method 2 using Function Call Stack:
C++
350
Chapter 60. Queue using Stacks
s.push(x);
}
// Dequeue an item from the queue
int deQueue()
{
if (s.empty()) {
cout << "Q is empty";
exit(0);
}
// pop an item from the stack
int x = s.top();
s.pop();
// if stack becomes empty, return
// the popped item
if (s.empty())
return x;
// recursive call
int item = deQueue();
// push popped item back to the stack
s.push(x);
// return the result of deQueue() call
return item;
}
};
// Driver code
int main()
{
Queue q;
q.enQueue(1);
q.enQueue(2);
q.enQueue(3);
cout << q.deQueue() << '\n';
cout << q.deQueue() << '\n';
cout << q.deQueue() << '\n';
return 0;
}
351
Chapter 60. Queue using Stacks
352
Chapter 60. Queue using Stacks
/* push everything back to stack1 */
push(&q->stack1, x);
return res;
}
}
/* Function to push an item to stack*/
void push(struct sNode** top_ref, int new_data)
{
/* allocate node */
struct sNode* new_node = (struct sNode*)malloc(sizeof(struct sNode));
if (new_node == NULL) {
printf("Stack overflow \n");
getchar();
exit(0);
}
/* put in the data */
new_node->data = new_data;
/* link the old list off the new node */
new_node->next = (*top_ref);
/* move the head to point to the new node */
(*top_ref) = new_node;
}
/* Function to pop an item from stack*/
int pop(struct sNode** top_ref)
{
int res;
struct sNode* top;
/*If stack is empty then error */
if (*top_ref == NULL) {
printf("Stack underflow \n");
getchar();
exit(0);
}
else {
top = *top_ref;
res = top->data;
*top_ref = top->next;
free(top);
return res;
}
353
Chapter 60. Queue using Stacks
}
/* Driver function to test above functions */
int main()
{
/* Create a queue with items 1 2 3*/
struct queue* q = (struct queue*)malloc(sizeof(struct queue));
q->stack1 = NULL;
enQueue(q, 1);
enQueue(q, 2);
enQueue(q, 3);
/* Dequeue items */
printf("%d ", deQueue(q));
printf("%d ", deQueue(q));
printf("%d ", deQueue(q));
return 0;
}
Java
354
Chapter 60. Queue using Stacks
355
Chapter 60. Queue using Stacks
/* Dequeue items */
System.out.print(deQueue(q) + " ");
System.out.print(deQueue(q) + " ");
System.out.print(deQueue(q) + " ");
}
}
// This code is contributed by Sumit Ghosh
Output:
1 2 3
Please write comments if you find any of the above codes/algorithms incorrect, or find better
ways to solve the same problem.
Improved By : iamsdhar, ParulShandilya
Source
https://www.geeksforgeeks.org/queue-using-stacks/
356
Chapter 61
357
Chapter 61. Queue | Set 1 (Introduction and Array Implementation)
Applications of Queue:
Queue is used when things don’t have to be processed immediatly, but have to be processed
in First InFirst Out order like Breadth First Search. This property of Queue makes it also
useful in following kind of scenarios.
1) When a resource is shared among multiple consumers. Examples include CPU scheduling,
Disk Scheduling.
2) When data is transferred asynchronously (data not necessarily received at same rate as
sent) between two processes. Examples include IO Buffers, pipes, file IO, etc.
See this for more detailed applications of Queue and Stack.
Array implementation Of Queue
For implementing queue, we need to keep track of two indices, front and rear. We enqueue
an item at the rear and dequeue an item from front. If we simply increment front and rear
indices, then there may be problems, front may reach end of the array. The solution to this
problem is to increase front and rear in circular manner (See thisfor details)
C
358
Chapter 61. Queue | Set 1 (Introduction and Array Implementation)
// function to create a queue of given capacity.
// It initializes size of queue as 0
struct Queue* createQueue(unsigned capacity)
{
struct Queue* queue = (struct Queue*) malloc(sizeof(struct Queue));
queue->capacity = capacity;
queue->front = queue->size = 0;
queue->rear = capacity - 1; // This is important, see the enqueue
queue->array = (int*) malloc(queue->capacity * sizeof(int));
return queue;
}
// Queue is full when size becomes equal to the capacity
int isFull(struct Queue* queue)
{ return (queue->size == queue->capacity); }
// Queue is empty when size is 0
int isEmpty(struct Queue* queue)
{ return (queue->size == 0); }
// Function to add an item to the queue.
// It changes rear and size
void enqueue(struct Queue* queue, int item)
{
if (isFull(queue))
return;
queue->rear = (queue->rear + 1)%queue->capacity;
queue->array[queue->rear] = item;
queue->size = queue->size + 1;
printf("%d enqueued to queue\n", item);
}
// Function to remove an item from queue.
// It changes front and size
int dequeue(struct Queue* queue)
{
if (isEmpty(queue))
return INT_MIN;
int item = queue->array[queue->front];
queue->front = (queue->front + 1)%queue->capacity;
queue->size = queue->size - 1;
return item;
}
// Function to get front of queue
int front(struct Queue* queue)
{
359
Chapter 61. Queue | Set 1 (Introduction and Array Implementation)
if (isEmpty(queue))
return INT_MIN;
return queue->array[queue->front];
}
// Function to get rear of queue
int rear(struct Queue* queue)
{
if (isEmpty(queue))
return INT_MIN;
return queue->array[queue->rear];
}
// Driver program to test above functions./
int main()
{
struct Queue* queue = createQueue(1000);
enqueue(queue, 10);
enqueue(queue, 20);
enqueue(queue, 30);
enqueue(queue, 40);
printf("%d dequeued from queue\n\n", dequeue(queue));
printf("Front item is %d\n", front(queue));
printf("Rear item is %d\n", rear(queue));
return 0;
}
Java
360
Chapter 61. Queue | Set 1 (Introduction and Array Implementation)
}
// Queue is full when size becomes equal to
// the capacity
boolean isFull(Queue queue)
{ return (queue.size == queue.capacity);
}
// Queue is empty when size is 0
boolean isEmpty(Queue queue)
{ return (queue.size == 0); }
// Method to add an item to the queue.
// It changes rear and size
void enqueue( int item)
{
if (isFull(this))
return;
this.rear = (this.rear + 1)%this.capacity;
this.array[this.rear] = item;
this.size = this.size + 1;
System.out.println(item+ " enqueued to queue");
}
// Method to remove an item from queue.
// It changes front and size
int dequeue()
{
if (isEmpty(this))
return Integer.MIN_VALUE;
int item = this.array[this.front];
this.front = (this.front + 1)%this.capacity;
this.size = this.size - 1;
return item;
}
// Method to get front of queue
int front()
{
if (isEmpty(this))
return Integer.MIN_VALUE;
return this.array[this.front];
}
// Method to get rear of queue
int rear()
361
Chapter 61. Queue | Set 1 (Introduction and Array Implementation)
{
if (isEmpty(this))
return Integer.MIN_VALUE;
return this.array[this.rear];
}
}
// Driver class
public class Test
{
public static void main(String[] args)
{
Queue queue = new Queue(1000);
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
queue.enqueue(40);
System.out.println(queue.dequeue() +
" dequeued from queue\n");
System.out.println("Front item is " +
queue.front());
System.out.println("Rear item is " +
queue.rear());
}
}
// This code is contributed by Gaurav Miglani
Python3
362
Chapter 61. Queue | Set 1 (Introduction and Array Implementation)
363
Chapter 61. Queue | Set 1 (Introduction and Array Implementation)
queue = Queue(30)
queue.EnQueue(10)
queue.EnQueue(20)
queue.EnQueue(30)
queue.EnQueue(40)
queue.DeQueue()
queue.que_front()
queue.que_rear()
C#
364
Chapter 61. Queue | Set 1 (Introduction and Array Implementation)
365
Chapter 61. Queue | Set 1 (Introduction and Array Implementation)
Q.enqueue(20);
Q.enqueue(30);
Q.enqueue(40);
Q.printQueue();
Q.dequeue();
}
}
}
Output:
10 enqueued to queue
20 enqueued to queue
30 enqueued to queue
40 enqueued to queue
10 dequeued from queue
Front item is 20
Rear item is 40
Time Complexity: Time complexity of all operations like enqueue(), dequeue(), isFull(),
isEmpty(), front() and rear() is O(1). There is no loop in any of the operations.
Linked list implementation is easier, it is discussed here: Queue | Set 2 (Linked List Imple-
mentation)
Improved By : SoumikMondal
Source
https://www.geeksforgeeks.org/queue-set-1introduction-and-array-implementation/
366
Chapter 62
367
Chapter 62. Queue | Set 2 (Linked List Implementation)
};
// A utility function to create a new linked list node.
struct QNode* newNode(int k)
{
struct QNode *temp = (struct QNode*)malloc(sizeof(struct QNode));
temp->key = k;
temp->next = NULL;
return temp;
}
// A utility function to create an empty queue
struct Queue *createQueue()
{
struct Queue *q = (struct Queue*)malloc(sizeof(struct Queue));
q->front = q->rear = NULL;
return q;
}
// The function to add a key k to q
void enQueue(struct Queue *q, int k)
{
// Create a new LL node
struct QNode *temp = newNode(k);
// If queue is empty, then new node is front and rear both
if (q->rear == NULL)
{
q->front = q->rear = temp;
return;
}
// Add the new node at the end of queue and change rear
q->rear->next = temp;
q->rear = temp;
}
// Function to remove a key from given queue q
struct QNode *deQueue(struct Queue *q)
{
// If queue is empty, return NULL.
if (q->front == NULL)
return NULL;
// Store previous front and move front one node ahead
struct QNode *temp = q->front;
q->front = q->front->next;
368
Chapter 62. Queue | Set 2 (Linked List Implementation)
Java
369
Chapter 62. Queue | Set 2 (Linked List Implementation)
370
Chapter 62. Queue | Set 2 (Linked List Implementation)
q.enqueue(20);
q.dequeue();
q.dequeue();
q.enqueue(30);
q.enqueue(40);
q.enqueue(50);
System.out.println("Dequeued item is "+ q.dequeue().key);
}
}
// This code is contributed by Gaurav Miglani
Python3
371
Chapter 62. Queue | Set 2 (Linked List Implementation)
def DeQueue(self):
if self.isEmpty():
return
temp = self.front
self.front = temp.next
if(self.front == None):
self.rear = None
return str(temp.data)
# Driver Code
if __name__== '__main__':
q = Queue()
q.EnQueue(10)
q.EnQueue(20)
q.DeQueue()
q.DeQueue()
q.EnQueue(30)
q.EnQueue(40)
q.EnQueue(50)
print("Dequeued item is " + q.DeQueue())
Output:
Dequeued item is 30
Time Complexity: Time complexity of both operations enqueue() and dequeue() is O(1)
as we only change few pointers in both operations. There is no loop in any of the operations.
Source
https://www.geeksforgeeks.org/queue-set-2-linked-list-implementation/
372
Chapter 63
Input : 50
/ \
30 70
/ \ / \
20 40 60 80
k = 70
Output :
Inorder before reversal :
20 30 40 50 60 70 80
Inorder after reversal :
20 30 40 70 60 50 80
Input : 8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
k = 13
Output :
Inorder before reversal :
373
Chapter 63. Reverse a path in BST using queue
1 3 4 6 7 8 10 13 14
Inorder after reversal :
1 3 4 6 7 13 14 10 8
Approach :
Take a queue and push all the element till that given key at the end replace node key with
queue front element till root, then print inorder of the tree.
Below is the implementation of above approach :
374
Chapter 63. Reverse a path in BST using queue
return;
// If the node key equal
// to key then
if ((*node)->key == key)
{
// push current node key
q1.push((*node)->key);
// replace first node
// with last element
(*node)->key = q1.front();
// remove first element
q1.pop();
// return
return;
}
// if key smaller than node key then
else if (key < (*node)->key)
{
// push node key into queue
q1.push((*node)->key);
// recusive call itself
reversePath(&(*node)->left, key, q1);
// replace queue front to node key
(*node)->key = q1.front();
// performe pop in queue
q1.pop();
}
// if key greater than node key then
else if (key > (*node)->key)
{
// push node key into queue
q1.push((*node)->key);
// recusive call itself
reversePath(&(*node)->right, key, q1);
// replace queue front to node key
(*node)->key = q1.front();
375
Chapter 63. Reverse a path in BST using queue
376
Chapter 63. Reverse a path in BST using queue
insert(root, 80);
cout << "Before Reverse :" << endl;
// print inoder traversal of the BST
inorder(root);
cout << "\n";
// reverse path till k
reversePath(&root, k, q1);
cout << "After Reverse :" << endl;
// print inorder of reverse path tree
inorder(root);
return 0;
}
Output:
Before Reverse :
20 30 40 50 60 70 80
After Reverse :
20 30 40 80 60 70 50
Source
https://www.geeksforgeeks.org/reverse-path-bst-using-queue/
377
Chapter 64
Reversing a Queue
Examples:
Input : Q = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100]
Output :Q = [100, 90, 80, 70, 60, 50, 40, 30, 20, 10]
Input :[1, 2, 3, 4, 5]
Output :[5, 4, 3, 2, 1]
C++
378
Chapter 64. Reversing a Queue
}
// Function to reverse the queue
void reverseQueue(queue<int>& Queue)
{
stack<int> Stack;
while (!Queue.empty()) {
Stack.push(Queue.front());
Queue.pop();
}
while (!Stack.empty()) {
Queue.push(Stack.top());
Stack.pop();
}
}
// Driver code
int main()
{
queue<int> Queue;
Queue.push(10);
Queue.push(20);
Queue.push(30);
Queue.push(40);
Queue.push(50);
Queue.push(60);
Queue.push(70);
Queue.push(80);
Queue.push(90);
Queue.push(100);
reverseQueue(Queue);
Print(Queue);
}
Java
379
Chapter 64. Reversing a Queue
Output
380
Chapter 64. Reversing a Queue
Source
https://www.geeksforgeeks.org/reversing-a-queue/
381
Chapter 65
Input : Q = [8, 7, 2, 5, 1]
Output : Q = [1, 5, 2, 7, 8]
Recursive Algorithm :
1) Pop element from the queue if the queue has elements otherwise return empty queue.
2) Call reverseQueue function for the remaining queue.
3) Push the popped element in the resultant reversed queue.
382
Chapter 65. Reversing a queue using recursion
Pseudo Code :
queue reverseFunction(queue)
{
if (queue is empty)
return queue;
else {
data = queue.front()
queue.pop()
queue = reverseFunction(queue);
q.push(data);
return queue;
}
}
C++
383
Chapter 65. Reversing a queue using recursion
}
// Recursive function to reverse the queue
void reverseQueue(queue<long long int>& q)
{
// Base case
if (q.empty())
return;
// Dequeue current item (from front)
long long int data = q.front();
q.pop();
// Reverse remaining queue
reverseQueue(q);
// Enqueue current item (to rear)
q.push(data);
}
// Driver code
int main()
{
queue<long long int> Queue;
Queue.push(56);
Queue.push(27);
Queue.push(30);
Queue.push(45);
Queue.push(85);
Queue.push(92);
Queue.push(58);
Queue.push(80);
Queue.push(90);
Queue.push(100);
reverseQueue(Queue);
printQueue(Queue);
}
Java
384
Chapter 65. Reversing a queue using recursion
385
Chapter 65. Reversing a queue using recursion
}
}
Python3
# Queue Class
class Queue:
def __init__(self):
self.items = []
def isEmpty(self):
return self.items == []
def add(self, item):
self.items.append(item)
def pop(self):
return self.items.pop(0)
def front(self):
return self.items[0]
def printQueue(self):
for i in self.items:
print(i, end =" ")
print("")
# Recursive Function to reverse the queue
def reverseQueue(q):
# Base case
if (q.isEmpty()):
return
# Dequeue current item (from front)
data = q.front();
q.pop();
# Reverse remaining queue
reverseQueue(q)
# Enqueue current item (to rear)
q.add(data)
# Driver Code
386
Chapter 65. Reversing a queue using recursion
q = Queue()
q.add(56)
q.add(27)
q.add(30)
q.add(45)
q.add(85)
q.add(92)
q.add(58)
q.add(80)
q.add(90)
q.add(100)
reverseQueue(q)
q.printQueue()
C#
387
Chapter 65. Reversing a queue using recursion
// Enqueue current
// item (to rear)
q.Enqueue(data);
}
// Driver code
static void Main()
{
Queue<long> queue = new Queue<long>();
queue.Enqueue(56);
queue.Enqueue(27);
queue.Enqueue(30);
queue.Enqueue(45);
queue.Enqueue(85);
queue.Enqueue(92);
queue.Enqueue(58);
queue.Enqueue(80);
queue.Enqueue(90);
queue.Enqueue(100);
reverseQueue(ref queue);
printQueue(queue);
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Output:
100 90 80 58 92 85 45 30 27 56
Source
https://www.geeksforgeeks.org/reversing-queue-using-recursion/
388
Chapter 66
Examples:
389
Chapter 66. Reversing the first K elements of a Queue
390
Chapter 66. Reversing the first K elements of a Queue
// Driver code
int main()
{
queue<int> Queue;
Queue.push(10);
Queue.push(20);
Queue.push(30);
Queue.push(40);
Queue.push(50);
Queue.push(60);
Queue.push(70);
Queue.push(80);
Queue.push(90);
Queue.push(100);
int k = 5;
reverseQueueFirstKElements(k, Queue);
Print(Queue);
}
Java
391
Chapter 66. Reversing the first K elements of a Queue
// Enqueue the contents of stack at the back
// of the queue
while (!stack.empty()) {
queue.add(stack.peek());
stack.pop();
}
// Remove the remaining elements and enqueue
// them at the end of the Queue
for (int i = 0; i < queue.size() - k; i++) {
queue.add(queue.peek());
queue.remove();
}
}
// Utility Function to print the Queue
static void Print() {
while (!queue.isEmpty()) {
System.out.print(queue.peek() + " ");
queue.remove();
}
}
// Driver code
public static void main(String args[]) {
queue = new LinkedList<Integer>();
queue.add(10);
queue.add(20);
queue.add(30);
queue.add(40);
queue.add(50);
queue.add(60);
queue.add(70);
queue.add(80);
queue.add(90);
queue.add(100);
int k = 5;
reverseQueueFirstKElements(k);
Print();
}
}
// This code is contributed by Sumit Ghosh
Output:
392
Chapter 66. Reversing the first K elements of a Queue
50 40 30 20 10 60 70 80 90 100
Source
https://www.geeksforgeeks.org/reversing-first-k-elements-queue/
393
Chapter 67
• Thread A generates random integers and pushes them into a shared queue.
• Threads B and C compete with each other to grab an integer from the queue.
• The threads B and C compute the sum of integers that they have grabbed from the
queue.
• Compare the sums as computed by B and C. The greatest is the winner.
Prerequisite :- Multithreading
Approach :- Create a global queue which is shared among all three threads. First create
all three threads and call the respective functions associated with them.
Note :- There is mutex lock in every function to avoid any race condition.
394
Chapter 67. Sharing a queue among three threads
395
Chapter 67. Sharing a queue among three threads
pthread_cond_broadcast(&dataNotProduced);
}
// If queue is full, release the lock and return
else if (producerCount == MAX) {
pthread_mutex_unlock(&mutex);
return NULL;
}
// If some other thread is exectuing, wait
else {
cout << ">> Producer is in wait.." << endl;
pthread_cond_wait(&dataNotConsumed, &mutex);
}
// Get the mutex unlocked
pthread_mutex_unlock(&mutex);
}
}
// Function definition for consumer thread B
void* add_B(void*)
{
while (1) {
// Getting the lock on queue using mutex
pthread_mutex_lock(&mutex);
// Pop only when queue has at least 1 element
if (Q.size() > 0) {
// Get the data from the front of queue
int data = Q.front();
cout << "B thread consumed: " << data << endl;
// Add the data to the integer variable
// associated with thread B
sum_B += data;
// Pop the consumed data from queue
Q.pop();
consumerCount1++;
pthread_cond_signal(&dataNotConsumed);
}
396
Chapter 67. Sharing a queue among three threads
// Check if consmed numbers from both threads
// has reached to MAX value
else if (consumerCount2 + consumerCount1 == MAX) {
pthread_mutex_unlock(&mutex);
return NULL;
}
// If some other thread is exectuing, wait
else {
cout << "B is in wait.." << endl;
pthread_cond_wait(&dataNotProduced, &mutex);
}
// Get the mutex unlocked
pthread_mutex_unlock(&mutex);
}
}
// Function definition for consumer thread C
void* add_C(void*)
{
while (1) {
// Getting the lock on queue using mutex
pthread_mutex_lock(&mutex);
// Pop only when queue has at least 1 element
if (Q.size() > 0) {
// Get the data from the front of queue
int data = Q.front();
cout << "C thread consumed: " << data << endl;
// Add the data to the integer variable
// associated with thread B
sum_C += data;
// Pop the consumed data from queue
Q.pop();
consumerCount2++;
pthread_cond_signal(&dataNotConsumed);
}
// Check if consmed numbers from both threads
// has reached to MAX value
397
Chapter 67. Sharing a queue among three threads
398
Chapter 67. Sharing a queue among three threads
else
cout << "Both has same score" << endl;
return 0;
}
Output:
B is in wait..
Produced: 10
Produced: 1
Produced: 6
Produced: 6
Produced: 4
C thread consumed: 10
C thread consumed: 1
C thread consumed: 6
C thread consumed: 6
Produced: 1
Produced: 9
Produced: 9
Produced: 6
C thread consumed: 4
C thread consumed: 1
C thread consumed: 9
C thread consumed: 9
C thread consumed: 6
>> C is in wait..
Produced: 5
C thread consumed: 5
Winner is Thread C
Source
https://www.geeksforgeeks.org/sharing-queue-among-three-threads/
399
Chapter 68
#include<stdio.h>
void printKMax(int arr[], int n, int k)
{
400
Chapter 68. Sliding Window Maximum (Maximum of all subarrays of size k)
int j, max;
for (int i = 0; i <= n-k; i++)
{
max = arr[i];
for (j = 1; j < k; j++)
{
if (arr[i+j] > max)
max = arr[i+j];
}
printf("%d ", max);
}
}
int main()
{
int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int n = sizeof(arr)/sizeof(arr[0]);
int k = 3;
printKMax(arr, n, k);
return 0;
}
Java
//Java Program to find the maximum for each and every contiguous subarray of size k.
public class GFG
{
// Method to find the maximum for each and every contiguous subarray of size k.
static void printKMax(int arr[], int n, int k)
{
int j, max;
for (int i = 0; i <= n - k; i++) {
max = arr[i];
for (j = 1; j < k; j++)
{
if (arr[i + j] > max)
max = arr[i + j];
}
System.out.print(max + " ");
}
}
401
Chapter 68. Sliding Window Maximum (Maximum of all subarrays of size k)
// Driver method
public static void main(String args[])
{
int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int k = 3;
printKMax(arr, arr.length, k);
}
}
//This code is contributed by Sumit Ghosh
Python3
C#
402
Chapter 68. Sliding Window Maximum (Maximum of all subarrays of size k)
class GFG
{
// Method to find the maximum for
// each and every contiguous subarray
// of size k.
static void printKMax(int []arr, int n, int k)
{
int j, max;
for (int i = 0; i <= n - k; i++) {
max = arr[i];
for (j = 1; j < k; j++)
{
if (arr[i + j] > max)
max = arr[i + j];
}
Console.Write(max + " ");
}
}
// Driver method
public static void Main()
{
int []arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
int k = 3;
printKMax(arr, arr.Length, k);
}
}
// This Code is Contributed by Sam007
PHP
<?php
// PHP program to find the maximum
// for each and every contiguous
// subarray of size k
function printKMax($arr, $n, $k)
{
$j; $max;
for ($i = 0; $i <= $n - $k; $i++)
{
$max = $arr[$i];
403
Chapter 68. Sliding Window Maximum (Maximum of all subarrays of size k)
Output :
3 4 5 6 7 8 9 10
Time Complexity : The outer loop runs n-k+1 times and the inner loop runs k times for
every iteration of outer loop. So time complexity is O((n-k+1)*k) which can also be written
as O(nk).
Method 2 (Use Self-Balancing BST)
1) Pick first k elements and create a Self-Balancing Binary Search Tree (BST) of size k.
2) Run a loop for i = 0 to n – k
…..a) Get the maximum element from the BST, and print it.
…..b) Search for arr[i] in the BST and delete it from the BST.
…..c) Insert arr[i+k] into the BST.
Time Complexity: Time Complexity of step 1 is O(kLogk). Time Complexity of steps 2(a),
2(b) and 2(c) is O(Logk). Since steps 2(a), 2(b) and 2(c) are in a loop that runs n-k+1
times, time complexity of the complete algorithm is O(kLogk + (n-k+1)*Logk) which can
also be written as O(nLogk).
Method 3 (A O(n) method: use Dequeue)
We create a Dequeue, Qi of capacity k, that stores only useful elements of current window
of k elements. An element is useful if it is in current window and is greater than all other
elements on left side of it in current window. We process all array elements one by one
and maintain Qi to contain useful elements of current window and these useful elements are
maintained in sorted order. The element at front of the Qi is the largest and element at
rear of Qi is the smallest of current window. Thanks to Aashishfor suggesting this method.
Following is the implementation of this method.
404
Chapter 68. Sliding Window Maximum (Maximum of all subarrays of size k)
C++
#include <iostream>
#include <deque>
using namespace std;
// A Dequeue (Double ended queue) based method for printing maixmum element of
// all subarrays of size k
void printKMax(int arr[], int n, int k)
{
// Create a Double Ended Queue, Qi that will store indexes of array elements
// The queue will store indexes of useful elements in every window and it will
// maintain decreasing order of values from front to rear in Qi, i.e.,
// arr[Qi.front[]] to arr[Qi.rear()] are sorted in decreasing order
std::deque<int> Qi(k);
/* Process first k (or first window) elements of array */
int i;
for (i = 0; i < k; ++i)
{
// For very element, the previous smaller elements are useless so
// remove them from Qi
while ( (!Qi.empty()) && arr[i] >= arr[Qi.back()])
Qi.pop_back(); // Remove from rear
// Add new element at rear of queue
Qi.push_back(i);
}
// Process rest of the elements, i.e., from arr[k] to arr[n-1]
for ( ; i < n; ++i)
{
// The element at the front of the queue is the largest element of
// previous window, so print it
cout << arr[Qi.front()] << " ";
// Remove the elements which are out of this window
while ( (!Qi.empty()) && Qi.front() <= i - k)
Qi.pop_front(); // Remove from front of queue
// Remove all elements smaller than the currently
// being added element (remove useless elements)
while ( (!Qi.empty()) && arr[i] >= arr[Qi.back()])
Qi.pop_back();
// Add current element at the rear of Qi
Qi.push_back(i);
405
Chapter 68. Sliding Window Maximum (Maximum of all subarrays of size k)
}
// Print the maximum element of last window
cout << arr[Qi.front()];
}
// Driver program to test above functions
int main()
{
int arr[] = {12, 1, 78, 90, 57, 89, 56};
int n = sizeof(arr)/sizeof(arr[0]);
int k = 3;
printKMax(arr, n, k);
return 0;
}
Java
//Java Program to find the maximum for each and every contiguous subarray of size k.
import java.util.Deque;
import java.util.LinkedList;
public class SlidingWindow
{
// A Dequeue (Double ended queue) based method for printing maixmum element of
// all subarrays of size k
static void printMax(int arr[],int n, int k)
{
// Create a Double Ended Queue, Qi that will store indexes of array elements
// The queue will store indexes of useful elements in every window and it will
// maintain decreasing order of values from front to rear in Qi, i.e.,
// arr[Qi.front[]] to arr[Qi.rear()] are sorted in decreasing order
Deque<Integer> Qi = new LinkedList<Integer>();
/* Process first k (or first window) elements of array */
int i;
for(i = 0; i < k; ++i)
{
// For very element, the previous smaller elements are useless so
// remove them from Qi
while(!Qi.isEmpty() && arr[i] >= arr[Qi.peekLast()])
Qi.removeLast(); // Remove from rear
// Add new element at rear of queue
Qi.addLast(i);
}
406
Chapter 68. Sliding Window Maximum (Maximum of all subarrays of size k)
// Process rest of the elements, i.e., from arr[k] to arr[n-1]
for( ;i < n; ++i)
{
// The element at the front of the queue is the largest element of
// previous window, so print it
System.out.print(arr[Qi.peek()] + " ");
// Remove the elements which are out of this window
while((!Qi.isEmpty()) && Qi.peek() <= i-k)
Qi.removeFirst();
// Remove all elements smaller than the currently
// being added element (remove useless elements)
while((!Qi.isEmpty()) && arr[i] >= arr[Qi.peekLast()])
Qi.removeLast();
// Add current element at the rear of Qi
Qi.addLast(i);
}
// Print the maximum element of last window
System.out.print(arr[Qi.peek()]);
}
// Driver program to test above functions
public static void main(String[] args)
{
int arr[]={12, 1, 78, 90, 57, 89, 56};
int k=3;
printMax(arr, arr.length,k);
}
}
//This code is contributed by Sumit Ghosh
Python3
407
Chapter 68. Sliding Window Maximum (Maximum of all subarrays of size k)
408
Chapter 68. Sliding Window Maximum (Maximum of all subarrays of size k)
Output:
78 90 90 90 89
Time Complexity: O(n). It seems more than O(n) at first look. If we take a closer look, we
can observe that every element of array is added and removed at most once. So there are
total 2n operations.
Auxiliary Space: O(k)
Below is an extension of this problem.
Sum of minimum and maximum elements of all subarrays of size k.
Improved By : vt_m
Source
https://www.geeksforgeeks.org/sliding-window-maximum-maximum-of-all-subarrays-of-size-k/
409
Chapter 69
Input : N = 5
Output : X = 90
Exaplanation: 90 is the smallest number made up
of 9's and 0's which is divisible by 5.
Input : N = 7
Output : X = 9009
Exaplanation: 9009 is smallest number made up
of 9's and 0's which is divisible by 7.
The idea to solve this problem is to generate and store all of the numbers which can be
formed using digits 0 & 9. Then find the smallest number among these generated number
which is divisible by N.
We will use the method of generating binary numbers to generate all numbers which can be
formed by using digits 0 & 9.
Below is the implementation of above idea:
410
Chapter 69. Smallest multiple of a given number made of digits 0 and 9 only
C++
411
Chapter 69. Smallest multiple of a given number made of digits 0 and 9 only
{
// traverse the vector to find the smallest
// multiple of n
for (int i = 0; i < vec.size(); i++)
// stoi() is used for string to int conversion
if (stoi(vec[i])%n == 0)
return vec[i];
}
// Driver Code
int main()
{
generateNumbersUtil();
int n = 7;
cout << findSmallestMultiple(n);
return 0;
}
C#
412
Chapter 69. Smallest multiple of a given number made of digits 0 and 9 only
413
Chapter 69. Smallest multiple of a given number made of digits 0 and 9 only
// Driver Code
static void Main()
{
generateNumbersUtil();
int n = 7;
Console.Write(findSmallestMultiple(n));
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Output:
9009
Source
https://www.geeksforgeeks.org/smallest-multiple-of-a-given-number-made-of-digits-0-and-9-only/
414
Chapter 70
1. enqueue() : Adds an item to rear of queue. In C++ STL queue, this function is called
push().
2. dequeue() : Removes an item from front of queue. In C++ STL queue, this function
is called pop().
3. isEmpty() : Checks if a queue is empty. In C++ STL queue, this function is called
empty().
Examples :
If we are allowed extra space, then we can simply move all items of queue to an array, then
sort the array and finally move array elements back to queue.
415
Chapter 70. Sorting a Queue without extra space
Input :
-------------
11 5 4 21 min index = 2
-------------
-------------
11 5 21 4 after inserting 4
-------------
-------------
11 5 21 4 min index = 1
-------------
-------------
11 21 4 5 after inserting 5
-------------
-------------
11 21 4 5 min index = 0
-------------
-------------
21 4 5 11 after inserting 11
-------------
-------------
21 4 5 11 min index = 0
-------------
-------------
4 5 11 21 after inserting 21
-------------
Output : 4 5 11 21
C++
416
Chapter 70. Sorting a Queue without extra space
417
Chapter 70. Sorting a Queue without extra space
}
q.push(min_val);
}
void sortQueue(queue<int> &q)
{
for (int i = 1; i <= q.size(); i++)
{
int min_index = minIndex(q, q.size() - i);
insertMinToRear(q, min_index);
}
}
// driver code
int main()
{
queue<int> q;
q.push(30);
q.push(11);
q.push(15);
q.push(4);
// Sort queue
sortQueue(q);
// Print sorted queue
while (q.empty() == false)
{
cout << q.front() << " ";
q.pop();
}
cout << endl;
return 0;
}
Java
418
Chapter 70. Sorting a Queue without extra space
int sortIndex)
{
int min_index = -1;
int min_value = Integer.MAX_VALUE;
int s = list.size();
for (int i = 0; i < s; i++)
{
int current = list.peek();
// This is dequeue() in Java STL
list.poll();
// we add the condition i <= sortIndex
// because we don't want to traverse
// on the sorted part of the queue,
// which is the right part.
if (current <= min_value && i <= sortIndex)
{
min_index = i;
min_value = current;
}
list.add(current);
}
return min_index;
}
// Moves given minimum element
// to rear of queue
public static void insertMinToRear(Queue<Integer> list,
int min_index)
{
int min_value = 0;
int s = list.size();
for (int i = 0; i < s; i++)
{
int current = list.peek();
list.poll();
if (i != min_index)
list.add(current);
else
min_value = current;
}
list.add(min_value);
}
public static void sortQueue(Queue<Integer> list)
{
for(int i = 1; i <= list.size(); i++)
419
Chapter 70. Sorting a Queue without extra space
{
int min_index = minIndex(list,list.size() - i);
insertMinToRear(list, min_index);
}
}
//Driver function
public static void main (String[] args)
{
Queue<Integer> list = new LinkedList<Integer>();
list.add(30);
list.add(11);
list.add(15);
list.add(4);
//Sort Queue
sortQueue(list);
//print sorted Queue
while(list.isEmpty()== false)
{
System.out.print(list.peek() + " ");
list.poll();
}
}
}
// This code is contributed by akash1295
C#
// C# program to implement
// sorting a queue data structure
using System;
using System.Collections.Generic;
class GFG
{
// Queue elements after sorted
// Index are already sorted.
// This function returns index
// of minimum element from front
// to sortedIndex
static int minIndex(ref Queue<int> q,
int sortedIndex)
{
int min_index = -1;
int min_val = int.MaxValue;
420
Chapter 70. Sorting a Queue without extra space
int n = q.Count;
for (int i = 0; i < n; i++)
{
int curr = q.Peek();
q.Dequeue(); // This is dequeue()
// in C++ STL
// we add the condition
// i <= sortedIndex because
// we don't want to traverse
// on the sorted part of the
// queue, which is the right part.
if (curr <= min_val &&
i <= sortedIndex)
{
min_index = i;
min_val = curr;
}
q.Enqueue(curr); // This is enqueue()
// in C++ STL
}
return min_index;
}
// Moves given minimum
// element to rear of queue
static void insertMinToRear(ref Queue<int> q,
int min_index)
{
int min_val = 0;
int n = q.Count;
for (int i = 0; i < n; i++)
{
int curr = q.Peek();
q.Dequeue();
if (i != min_index)
q.Enqueue(curr);
else
min_val = curr;
}
q.Enqueue(min_val);
}
static void sortQueue(ref Queue<int> q)
{
for (int i = 1; i <= q.Count; i++)
{
int min_index = minIndex(ref q,
421
Chapter 70. Sorting a Queue without extra space
q.Count - i);
insertMinToRear(ref q,
min_index);
}
}
// Driver Code
static void Main()
{
Queue<int> q = new Queue<int>();
q.Enqueue(30);
q.Enqueue(11);
q.Enqueue(15);
q.Enqueue(4);
// Sort queue
sortQueue(ref q);
// Print sorted queue
while (q.Count != 0)
{
Console.Write(q.Peek() + " ");
q.Dequeue();
}
Console.WriteLine();
}
}
// This code is contributed by
// Manish Shaw(manishshaw1)
Output:
4 11 15 30
Source
https://www.geeksforgeeks.org/sorting-queue-without-extra-space/
422
Chapter 71
There are a huge number of permutations possible using a stack for a single input queue.
Given two arrays, both of unique elements. One represents the input queue and the other
represents the output queue. Our task is to check if the given output is possible through
stack permutation.
Examples:
423
Chapter 71. Stack Permutations (Check if an array is stack permutation of other)
The idea to do this is we will try to convert the input queue to output queue using a stack,
if we are able to do so then the queue is permutable otherwise not.
Below is the step by step algorithm to do this:
1. Continuously pop elements from the input queue and check if it is equal to the top of
output queue or not, if it is not equal to the top of output queue then we will push
the element to stack.
2. Once we find an element in input queue such the top of input queue is equal to top
of output queue, we will pop a single element from both input and output queues,
and compare the top of stack and top of output queue now. If top of both stack and
output queue are equal then pop element from both stack and output queue. If not
equal, go to step 1.
3. Repeat above two steps until the input queue becomes empty. At the end if both of
the input queue and stack are empty then the input queue is permutable otherwise
not.
424
Chapter 71. Stack Permutations (Check if an array is stack permutation of other)
425
Chapter 71. Stack Permutations (Check if an array is stack permutation of other)
Output:
Yes
Source
https://www.geeksforgeeks.org/stack-permutations-check-if-an-array-is-stack-permutation-of-other/
426
Chapter 72
// Initialize queue
Syntax: queue.Queue(maxsize)
// Insert Element
Syntax: Queue.put(data)
Initializes a variable to a maximum size of maxsize. A maxsize of zero ‘0’ means a infinite
queue. This Queue follows FIFO rule. This module also has a LIFO Queue, which is
basically a Stack. Data is inserted into Queue using put() and the end. get() takes data
out from the front of the Queue. Note that Both put() and get() take 2 more parameters,
optional flags, block and timeout.
import queue
# From class queue, Queue is
# created as an object Now L
427
Chapter 72. Stack and Queue in Python using queue Module
# is Queue of a maximum
# capacity of 20
L = queue.Queue(maxsize=20)
# Data is inserted into Queue
# using put() Data is inserted
# at the end
L.put(5)
L.put(9)
L.put(1)
L.put(7)
# get() takes data out from
# the Queue from the head
# of the Queue
print(L.get())
print(L.get())
print(L.get())
print(L.get())
Output:
5
9
1
7
import queue
L = queue.Queue(maxsize=6)
# qsize() give the maxsize
# of the Queue
print(L.qsize())
L.put(5)
L.put(9)
L.put(1)
L.put(7)
# Return Boolean for Full
428
Chapter 72. Stack and Queue in Python using queue Module
# Queue
print("Full: ", L.full())
L.put(9)
L.put(10)
print("Full: ", L.full())
print(L.get())
print(L.get())
print(L.get())
# Return Boolean for Empty
# Queue
print("Empty: ", L.empty())
print(L.get())
print(L.get())
print(L.get())
print("Empty: ", L.empty())
print("Full: ", L.full())
# This would result into Infinite
# Loop as the Queue is empty.
# print(L.get())
Output:
0
Full: False
Full: True
5
9
1
Empty: False
7
9
10
Empty: True
Full: False
3. Stack
This module queue also provides LIFO Queue which technically works as a Stack.
import queue
429
Chapter 72. Stack and Queue in Python using queue Module
L = queue.LifoQueue(maxsize=6)
# qsize() give the maxsize of
# the Queue
print(L.qsize())
# Data Inserted as 5->9->1->7,
# same as Queue
L.put(5)
L.put(9)
L.put(1)
L.put(7)
L.put(9)
L.put(10)
print("Full: ", L.full())
print("Size: ", L.qsize())
# Data will be accessed in the
# reverse order Reverse of that
# of Queue
print(L.get())
print(L.get())
print(L.get())
print(L.get())
print(L.get())
print("Empty: ", L.empty())
Output:
0
Full: True
Size: 6
10
9
7
1
9
Empty: False
Reference:
https://docs.python.org/3/library/asyncio-queue.html
Source
https://www.geeksforgeeks.org/stack-queue-python-using-module-queue/
430
Chapter 73
Approach: Since in the above problem the modulus given is 1000, therefore the maximum
number of states will be 103 . All the states can be checked using simple BFS. Initialize
an ans[] array with -1 which marks that the state has not been visited. ans[i] stores the
number of steps taken to reach i from start. Initially push the start to the queue, then apply
BFS. Pop the top element and check if it is equal to the end if it is then print the ans[end].
If the element is not equal to the topmost element, then add the top element with every
element in the array and perform a mod operation with 1000. If the added element state
has not been visited previously, then push it into the queue. Initialize ans[pushed_element]
431
Chapter 73. Sudo Placement[1.3] | Final Destination
by ans[top_element] + 1. Once all the states are visited, and the state cannot be reached
by performing every possible multiplication, then print -1.
Below is the implementation of the above approach:
432
Chapter 73. Sudo Placement[1.3] | Final Destination
Output:
Source
https://www.geeksforgeeks.org/sudo-placement1-3-final-destination/
433
Chapter 74
434
Chapter 74. Sum of minimum and maximum elements of all subarrays of size k.
empty double ended queues of size k (‘S’ , ‘G’) that only store indexes of elements of current
window that are not useless. An element is useless if it can not be maximum or minimum
of next subarrays.
435
Chapter 74. Sum of minimum and maximum elements of all subarrays of size k.
// The queue will store indexes of useful elements
// in every window
// In deque 'G' we maintain decreasing order of
// values from front to rear
// In deque 'S' we maintain increasing order of
// values from front to rear
deque< int > S(k), G(k);
// Process first window of size K
int i = 0;
for (i = 0; i < k; i++)
{
// Remove all previous greater elements
// that are useless.
while ( (!S.empty()) && arr[S.back()] >= arr[i])
S.pop_back(); // Remove from rear
// Remove all previous smaller that are elements
// are useless.
while ( (!G.empty()) && arr[G.back()] <= arr[i])
G.pop_back(); // Remove from rear
// Add current element at rear of both deque
G.push_back(i);
S.push_back(i);
}
// Process rest of the Array elements
for ( ; i < n; i++ )
{
// Element at the front of the deque 'G' & 'S'
// is the largest and smallest
// element of previous window respectively
sum += arr[S.front()] + arr[G.front()];
// Remove all elements which are out of this
// window
while ( !S.empty() && S.front() <= i - k)
S.pop_front();
while ( !G.empty() && G.front() <= i - k)
G.pop_front();
// remove all previous greater element that are
// useless
while ( (!S.empty()) && arr[S.back()] >= arr[i])
S.pop_back(); // Remove from rear
436
Chapter 74. Sum of minimum and maximum elements of all subarrays of size k.
Output:
16
Source
https://www.geeksforgeeks.org/sum-minimum-maximum-elements-subarrays-size-k/
437
Chapter 75
Zig Zag Level order traversal of a tree using single queue - GeeksforGeeks
Write a function to print spiral order traversal of a tree. For below tree, function should
print 1, 2, 3, 4, 5, 6, 7.
We have discussed naive approach and two stack based approach in Level Order with recur-
sion and multiple stacks
The idea behind this approach is first we have to take a queue, a direction flag and a
separation flag which is NULL
1. Insert the root element into the queue and again insert NULL into the queue.
2. For every element in the queue insert its child nodes.
3. If a NULL is encountered then check the direction to traverse the particular level is left
to right or right to left. If it’s an even level then traverse from left to right otherwise
traverse the tree in right to level order i.e., from the front to the previous front i.e.,
from the current NULL to to the last NULL that has been visited. This continues
till the last level then there the loop breaks and we print what is left (that has not
printed) by checking the direction to print.
438
Chapter 75. Zig Zag Level order traversal of a tree using single queue
C++
439
Chapter 75. Zig Zag Level order traversal of a tree using single queue
else {
if (count % 2 == 0) {
for (int i = prevFront + 1; i < front; i++)
printf("%d ", queue[i]->data);
}
else {
for (int i = front - 1; i > prevFront; i--)
printf("%d ", queue[i]->data);
}
prevFront = front;
count++;
front++;
// Insert a new level separator
queue[++top] = NULL;
continue;
}
}
if (curr->left != NULL)
queue[++top] = curr->left;
if (curr->right != NULL)
queue[++top] = curr->right;
front++;
}
if (count % 2 == 0) {
for (int i = prevFront + 1; i < top; i++)
printf("%d ", queue[i]->data);
}
else {
for (int i = top - 1; i > prevFront; i--)
printf("%d ", queue[i]->data);
}
}
// Driver code
int main()
{
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(7);
root->left->right = newNode(6);
root->right->left = newNode(5);
root->right->right = newNode(4);
440
Chapter 75. Zig Zag Level order traversal of a tree using single queue
levelOrder(root, 7);
return 0;
}
Output:
1 2 3 4 5 6 7
Source
https://www.geeksforgeeks.org/zig-zag-level-order-traversal-of-a-tree-using-single-queue/
441
Chapter 76
This problem can be solved using two stacks. Assume the two stacks are current: cur-
rentlevel and nextlevel. We would also need a variable to keep track of the current level
order(whether it is left to right or right to left). We pop from the currentlevel stack and print
the nodes value. Whenever the current level order is from left to right, push the nodes left
child, then its right child to the stack nextlevel. Since a stack is a LIFO(Last-In-First_out)
structure, next time when nodes are popped off nextlevel, it will be in the reverse order. On
the other hand, when the current level order is from right to left, we would push the nodes
right child first, then its left child. Finally, do-not forget to swap those two stacks at the
end of each level(i.e., when current level is empty)
Below is the implementation of the above approach:
C++
442
Chapter 76. ZigZag Tree Traversal
#include <stack>
using namespace std;
// Binary Tree node
struct Node {
int data;
struct Node *left, *right;
};
// function to print the zigzag traversal
void zizagtraversal(struct Node* root)
{
// if null then return
if (!root)
return;
// declare two stacks
stack<struct Node*> currentlevel;
stack<struct Node*> nextlevel;
// push the root
currentlevel.push(root);
// check if stack is empty
bool lefttoright = true;
while (!currentlevel.empty()) {
// pop out of stack
struct Node* temp = currentlevel.top();
currentlevel.pop();
// if not null
if (temp) {
// print the data in it
cout << temp->data << " ";
// store data according to current
// order.
if (lefttoright) {
if (temp->left)
nextlevel.push(temp->left);
if (temp->right)
nextlevel.push(temp->right);
}
else {
if (temp->right)
nextlevel.push(temp->right);
443
Chapter 76. ZigZag Tree Traversal
if (temp->left)
nextlevel.push(temp->left);
}
}
if (currentlevel.empty()) {
lefttoright = !lefttoright;
swap(currentlevel, nextlevel);
}
}
}
// A utility function to create a new node
struct Node* newNode(int data)
{
struct Node* node = new struct Node;
node->data = data;
node->left = node->right = NULL;
return (node);
}
// driver program to test the above function
int main()
{
// create tree
struct Node* root = newNode(1);
root->left = newNode(2);
root->right = newNode(3);
root->left->left = newNode(7);
root->left->right = newNode(6);
root->right->left = newNode(5);
root->right->right = newNode(4);
cout << "ZigZag Order traversal of binary tree is \n";
zizagtraversal(root);
return 0;
}
Java
444
Chapter 76. ZigZag Tree Traversal
int data;
Node leftChild;
Node rightChild;
Node(int data)
{
this.data = data;
}
}
class BinaryTree {
Node rootNode;
// function to print the
// zigzag traversal
void printZigZagTraversal() {
// if null then return
if (rootNode == null) {
return;
}
// declare two stacks
Stack<Node> currentLevel = new Stack<>();
Stack<Node> nextLevel = new Stack<>();
// push the root
currentLevel.push(rootNode);
boolean leftToRight = true;
// check if stack is empty
while (!currentLevel.isEmpty()) {
// pop out of stack
Node node = currentLevel.pop();
// print the data in it
System.out.print(node.data + " ");
// store data according to current
// order.
if (leftToRight) {
if (node.leftChild != null) {
nextLevel.push(node.leftChild);
}
if (node.rightChild != null) {
nextLevel.push(node.rightChild);
}
445
Chapter 76. ZigZag Tree Traversal
}
else {
if (node.rightChild != null) {
nextLevel.push(node.rightChild);
}
if (node.leftChild != null) {
nextLevel.push(node.leftChild);
}
}
if (currentLevel.isEmpty()) {
leftToRight = !leftToRight;
Stack<Node> temp = currentLevel;
currentLevel = nextLevel;
nextLevel = temp;
}
}
}
}
public class zigZagTreeTraversal {
// driver program to test the above function
public static void main(String[] args)
{
BinaryTree tree = new BinaryTree();
tree.rootNode = new Node(1);
tree.rootNode.leftChild = new Node(2);
tree.rootNode.rightChild = new Node(3);
tree.rootNode.leftChild.leftChild = new Node(7);
tree.rootNode.leftChild.rightChild = new Node(6);
tree.rootNode.rightChild.leftChild = new Node(5);
tree.rootNode.rightChild.rightChild = new Node(4);
System.out.println("ZigZag Order traversal of binary tree is");
tree.printZigZagTraversal();
}
}
// This Code is contributed by Harikrishnan Rajan.
Python3
446
Chapter 76. ZigZag Tree Traversal
class Node:
# Constructor to create a new node
def __init__(self, data):
self.data = data
self.left = self.right = None
# function to print zigzag traversal of
# binary tree
def zizagtraversal(root):
# Base Case
if root is None:
return
# Create two stacks to store current
# and next level
currentLevel = []
nextLevel = []
# if ltr is true push nodes from
# left to right otherwise from
# right to left
ltr = True
# append root to currentlevel stack
currentLevel.append(root)
# Check if stack is empty
while len(currentLevel) > 0:
# pop from stack
temp = currentLevel.pop(-1)
# print the data
print(temp.data, " ", end="")
if ltr:
# if ltr is true push left
# before right
if temp.left:
nextLevel.append(temp.left)
if temp.right:
nextLevel.append(temp.right)
else:
# else push right before left
if temp.right:
nextLevel.append(temp.right)
if temp.left:
nextLevel.append(temp.left)
447
Chapter 76. ZigZag Tree Traversal
if len(currentLevel) == 0:
# reverse ltr to push node in
# opposite order
ltr = not ltr
# swapping of stacks
currentLevel, nextLevel = nextLevel, currentLevel
# Driver program to check above function
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(7)
root.left.right = Node(6)
root.right.left = Node(5)
root.right.right = Node(4)
print("Zigzag Order traversal of binary tree is")
zizagtraversal(root)
# This code is contributed by Shweta Singh
Output:
Source
https://www.geeksforgeeks.org/zigzag-tree-traversal/
448