Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 5

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)tasks.size(), (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
++;

q2.push(x);

while (!q1.empty()) {
q2.push(q1.front()); q1.pop();
}

queue<int> q = q1;
q1 = q2; q2 = q;
}

void pop()
{

if (q1.empty())
return; q1.pop();
curr_size--;
}

int top() {
if (q1.empty())
return -1; return
q1.front();
}

int size() {
return curr_size;
}
};

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

OUTPUT-

You might also like