Data structure Assignment
Name-Pragya Bharadwaj
Admission-
SEC-3
DATE-03/04/2020
Problem 1 : Given a char array representing tasks CPU need to do. It contains capital letters A to Z where
different letters represent different tasks. Tasks could be done without original order. Each task could be
done in one interval. For each interval, CPU could finish one task or just be idle.
However, there is a non-negative cooling interval n that means between two same tasks, there must be
at least n intervals that CPU are doing different tasks or just be idle.
You need to return the least number of intervals the CPU will take to finish all the given tasks.
Example:
Input: tasks = ["A","A","A","B","B","B"], n = 2
Output: 8
Explanation: A -> B -> idle -> A -> B -> idle -> A -> B.
Constraints:
The number of tasks is in the range [1, 10000]. The
integer n is in the range [0, 100].
Source code:
class Solution { public:
int leastInterval(vector<char>& tasks, int n) {
int counter[26] = {0};
for(char &c:tasks)
{ counter[c - 'A']++;
}
int max_val = 0; for(int
&v: counter){ max_val =
max(v, max_val);
int max_cnt = 0; for(int
&v: counter){ if(v ==
max_val) max_cnt++;
return max((int)[Link](), (max_val - 1) * (n + 1) + max_cnt);
};
OUTPUT-
Problem 2: Implement stack using Queues
Source code-
/* Program to implement a stack using two
queue */
#include <bits/stdc++.h>
using namespace std;
class Stack {
queue<int> q1, q2;
int curr_size;
public: Stack()
{ curr_size =
0;
}
void push(int x)
{ curr_size
++;
[Link](x);
while (![Link]()) {
[Link]([Link]()); [Link]();
}
queue<int> q = q1;
q1 = q2; q2 = q;
}
void pop()
{
if ([Link]())
return; [Link]();
curr_size--;
}
int top() {
if ([Link]())
return -1; return
[Link]();
}
int size() {
return curr_size;
}
};
int main() {
Stack s;
[Link](1);
[Link](2);
[Link](3);
cout << "current size: " << [Link]()
<< endl; cout
<< [Link]() << endl;
[Link](); cout <<
[Link]() << endl;
[Link](); cout <<
[Link]() << endl;
cout << "current size: " << [Link]()
<< endl;
return 0;
}
OUTPUT-