Queue
Queue
Your task is to complete the function rev(), that reverses the N elements of the
queue.
Given an array A[] of size N and a positive integer K, find the first negative
integer for each and every window(contiguous subarray) of size K.
for(int i=0;i<k;i++){
int y=q.front();
q.pop();
st.push(y);
}
while(!q.empty()){
int y=q.front();
q.pop();
UwU.push(y);
}
while(!st.empty()){
int y=st.top();
st.pop();
q.push(y);
}
while(!UwU.empty()){
int y=UwU.front();
UwU.pop();
q.push(y);
}
return q;
}
class Solution {
public:
string FirstNonRepeating(string A){
string ans;
queue<char> buffer;
int arr[26]={0};
ans.push_back(A[0]);
buffer.push(A[0]);
arr[A[0]-'a']++;
for(int i=1 ; i<A.length();i++){
arr[A[i]-'a']++;
if(buffer.empty()){
if(arr[A[i]-'a']==1){
buffer.push(A[i]);
ans.push_back(A[i]);
}
else {
ans.push_back('#');
}
}
else if(A[i]!=buffer.front()){
ans.push_back(buffer.front());
buffer.push(A[i]);
}
else if(A[i]==buffer.front()){
while(!buffer.empty() && arr[buffer.front()-'a']>=2){
buffer.pop();
}
if(buffer.empty()){
ans.push_back('#');
}
else{
ans.push_back(buffer.front());
}
}
}
return ans;
}
};
Suppose there is a circle. There are N petrol pumps on that circle. You will be
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.
Find a starting point where the truck can start to get through the complete
circle without exhausting its petrol in between.
class Solution{
public:
int tour(petrolPump p[],int n)
{
int ans=0;
int pet=0;
int i;
for(i=0;i<n;i++){
pet += p[i].petrol;
if(p[i].distance>pet){
pet=0;
ans=i+1;
}
else{
pet = pet-p[i].distance;
}
}
if(ans==n){
return -1;
}
if(ans==n-1){
i=0;
}
else{
i=ans+1;
}
pet=p[ans].petrol-p[ans].distance;
while(i%n!=ans){
pet += p[i%n].petrol;
if(p[i%n].distance>pet){
return -1;
}
pet = pet-p[i%n].distance;
i++;
}
return ans;
}
};
class kQueues
{
int *arr;
int *front;
int *rear;
int *next;
int n, k;
int free;
public:
kQueues(int k, int n);
bool isFull() { return (free == -1); }
void enqueue(int item, int qn);
int dequeue(int qn);
bool isEmpty(int qn) { return (front[qn] == -1); }
};
kQueues::kQueues(int k1, int n1)
{
k = k1, n = n1;
arr = new int[n];
front = new int[k];
rear = new int[k];
next = new int[n];
for (int i = 0; i < k; i++)
front[i] = -1;
free = 0;
for (int i=0; i<n-1; i++)
next[i] = i+1;
next[n-1] = -1;
}
void kQueues::enqueue(int item, int qn)
{
if (isFull())
{
cout << "\nQueue Overflow\n";
return;
}
int i = free;
free = next[i];
if (isEmpty(qn))
front[qn] = i;
else
next[rear[qn]] = i;
next[i] = -1;
rear[qn] = i;
arr[i] = item;
}
int kQueues::dequeue(int qn)
{
if (isEmpty(qn))
{
cout << "\nQueue Underflow\n";
return INT_MAX;
}
int i = front[qn];
front[qn] = next[i];
next[i] = free;
free = i;
return arr[i];
}