-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day_89.cpp
76 lines (61 loc) · 1.53 KB
/
Day_89.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
DAY 89: Reverse First K elements of Queue.
QUESTION : Given an integer K and a queue of integers, we need to reverse the order of the first K
elements of the queue, leaving the other elements in the same relative order.
Only following standard operations are allowed on queue.
enqueue(x) : Add an item x to rear of queue
dequeue() : Remove an item from front of queue
size() : Returns number of elements in queue.
front() : Finds front item.
Example 1:
Input:
5 3
1 2 3 4 5
Output:
3 2 1 4 5
Explanation:
After reversing the given
input from the 3rd position the resultant
output will be 3 2 1 4 5.
Example 2:
Input:
4 4
4 3 2 1
Output:
1 2 3 4
Explanation:
After reversing the given
input from the 4th position the resultant
output will be 1 2 3 4.
Expected TIme Complexity : O(n)
Expected Auxilliary Space : O(n)
Constraints:
1 <= N <= 1000
1 <= K <= N
*/
queue<int> modifyQueue(queue<int> q, int k)
{
stack <int> stk;
queue <int> temp_q;
for (int i=0; i<k; i++) {
int t = q.front();
q.pop();
stk.push(t);
}
while(!q.empty()) {
int ele = q.front();
q.pop();
temp_q.push(ele);
}
for (int i=0; i<k; i++) {
int temp = stk.top();
stk.pop();
q.push(temp);
}
while(!temp_q.empty()) {
int ele = temp_q.front();
temp_q.pop();
q.push(ele);
}
return q;
}