Header Ad

HackerEarth Bugs problem solution

In this HackerEarth Bugs problem solution, You are a developer at XYZ company. You like to call the bugs in your code as enemies. You maintain an array A of the list of enemies in decreasing order of their difficulty i.e., the most difficult bug will be the first element of the array. Initially, there are no bugs in the code. You are given N tasks. Each task contains one of the following two types of operations:
  1. P: Add a bug with difficulty P into the array A.
  2. Sort the array in decreasing order and print the difficulty of (n / 3)th bug in the sorted array, where n is the size of the array A. If the number of bugs is less than 3, print Not enough enemies.


HackerEarth Bugs problem solution


HackerEarth Bugs problem solution.

import java.util.*;
import java.io.*;

public class Problem {

static ArrayList<Integer> a = new ArrayList();
public static void main(String[] args) throws IOException
{
Scanner sc=new Scanner(System.in);
int N = sc.nextInt();
int count=0;
while( N-->0 )
{

int type=sc.nextInt();
if( type==1 )
{
int P=sc.nextInt();
add_to_list(P);
count++;
}
else
{
if( count>=3 )
System.out.println(a.get(count/3-1));
else
System.out.println("Not enough enemies");
}
}
}





private static void add_to_list(int n)
{
int size = a.size();
int l=0,r=size-1,flag=0,mid,index,obs;
while(true)
{
if( l>r )
{
index = l;
break;
}

mid = (l+r)/2;
obs = a.get(mid);
if( obs==n )
{
index = mid;
break;
}
else if( obs>n )
{
l = mid+1;
flag=0;
}
else
{
r = mid-1;
flag=1;
}

}
if( index>=size )
a.add(n);
else if( index<0 )
a.add(0,n);
else
a.add(index,n);

}


}


Post a Comment

0 Comments