Unable to pass all conditions on codechef problem TREE2 - java

please can someone check and tell why this code is unable to pass the 80% condition.
This problem is presented on the CodeChef with the problem code TREE2. It is problem in the beginner section.
There are 2 tasks. with the following code I am able to pass the task of 20%, but I am unable to pass the second task which consists of 80%.
Please look into it and suggest what went wrong.
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
int t,n,h;
Scanner s=new Scanner(System.in);
t=s.nextInt();
while(t-- > 0)
{ h=0;
n=s.nextInt();
int [] arr=new int [n];
for(int i=0;i<n;i++)
arr[i]=s.nextInt();
Arrays.sort(arr);
while(true)
{
if(arr[n-1]==0)
break;
h++;
if(arr[0]==arr[n-1])
break;
for(int i=n-2;i>=0;i--)
{
if(arr[i]!=arr[n-1])
{
for(int j=i;j<n;j++)
arr[j]=arr[i];
break;
}
}
}
System.out.println(h);
}
}
}

its cause of time complexity.
you are using 4 loops.
that results in n raise to 4 time complexity.
try to solve using only one loop or without loop.
for hint go through SET concept

Related

On the Codechef aug long challenge, AUG21C >CHFINVNT, this is the code I wrote, but the submit doesn't work. Its showing RE(NZEC) error

On the Codechef August long challenge, AUG21C > CHFINVNT, this is the code that I wrote, but the submit doesn't work. It's showing RE(NZEC) error.
The output still works.... but it won't submit. Please help.
/* package codechef; // don't place package name! */
import java.util.*;
import java.lang.*;
import java.io.*;
/* Name of the class has to be "Main" only if the class is public. */
class Codechef
{
public static void main (String[] args) throws java.lang.Exception
{
// your code goes here
Scanner scr = new Scanner(System.in);
try {
int T = scr.nextInt();
while(T-- > 0)
{
int N = scr.nextInt();
int p = scr.nextInt();
int K = scr.nextInt();
int[] A = new int[N];
for(int i=0; i<N; i++)
{
A[i%K]++;
}
int sum=0;
for(int i=0; i<p%K; i++)
{
sum+=A[i];
}
int add = (p - (p%K)) / K;
add++;
sum = sum + add;
System.out.println(sum);
}
}catch(Exception e){}
}
}
Obviously, you have a flaw in your code. NZEC means non-zero exit code. Your code probably triggered an uncaught exception. Although you have a broad catch statement, there are exceptions outside of your catch clause.
In the question statement, N can be as large as 10^9.
If that happens, int[] A = new int[N]; tries to allocate that memory. That is over the memory constraints. Probably that is causing the problem. Even if you could allocate that memory, you would hit the time limits: even counting to 10^9 shall fail on CodeChef.
Not directly related to the question, but I want to comment on your code from the perspective of software engineering and competitive coding best practices.
Having a broad catch block will hide any exceptions you may have. Even if you get an index-out-of-bounds exception, you shall not be able to see that in your trials. You may avoid catching broad exceptions.
Your code does not have a proper indentation. That makes reading & debugging cumbersome. Especially in competitive programming, speed is important. So, a proper indentation is critical in that regard. You may just use an IDE to format the code.
Your Java code does not follow the general conventions of Java. One of the rules is "local variables start with a lowercase". The local variables A and N violate that rule.
The code you submitted contains many empty lines. While submitting your code to StackOverflow, removing unnecessary lines shall ease the reading and increase the probability of getting a good answer.

Got stuck at Project Euler's question 3 i.e. finding the largest prime factor of a given number. Please see details

So I designed this code (given below) for the question & it seems to be giving all the answers there are but for some reason I'm not able to pass my test cases in the Hackerrank Question except for the sample one.
My Code :
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
BigInteger n = new BigInteger(in.next());
BigInteger max = BigInteger.valueOf(1);
for(BigInteger i=BigInteger.valueOf(2);i.multiply(i).compareTo(n)<=0;i=i.add(BigInteger.ONE))
{
if(i.isProbablePrime(1) && n.mod(i).compareTo(BigInteger.valueOf(0))==0 && i.compareTo(max)>=0)
{
max = i;
n = n.divide(i);
}
}
if(n.isProbablePrime(1))
max = n;
else if(n.divide(BigInteger.valueOf(2)).isProbablePrime(1))
max = n.divide(BigInteger.valueOf(2));
System.out.println(max);
}
}
}
I'm getting the same output for each input as this website here.
Can anyone please look have a look at my code & point out where am I going wrong. I'm not looking for new code or logic, I just want to know how & why my code or logic is wrong. Can anyone help?
Thanks in advance.
EDIT : NEW CODE Found The Solution Thanks to #Douglas for helping me with hints
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
public class Solution {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int t = in.nextInt();
for(int a0 = 0; a0 < t; a0++){
long n = in.nextLong();
long max = 1;
while(n%2==0)
n = n/2;
if(n==1)
max = 2;
for(long i=3;i*i<=n;i+=2)
{
while(n%i==0 && i>=max)
{
max = i;
n = n/i;
}
}
if(n>2)
max = n;
System.out.println(max);
}
}
}
The code above runs perfectly fine & passes all the testcases.
You have three problems with this code:
An actual bug. You don't handle when a prime divides the number multiple times. I'm fairly sure the four lines before the println output are a workaround you put in when you encountered a failure this causes, that fixed the specific failure you found but don't actually address the root cause. I just tested it, your code outputs 3 for the input 252. The correct output for 252 is 7.
Part of your code invokes a library method that may be significantly expensive. You should not be using isProbablePrime.
Your algorithm's logic scales poorly. Hackerrank's test cases probably include something where the correct output is something like 20 digits long. A major point of Project Euler is that it's not enough to write code that will find the correct answer. You need to write code that will find the correct answer efficiently. To fix this, you will need new logic for the fundamental design of the program.

Solving a Maze Problem without exceeding the Heap Memory

Link to the problem on HackerEarth. - The Maze
I have tried this problem and now facing an issue in passing all the test cases.
Here is my code:
import java.util.*;
class SumTarget {
static boolean[][] hole=new boolean[10001][10001];
static boolean[][] temp=new boolean[10001][10001];
public static void main(String args[] ) throws Exception {
int k,t,i,j,n,m,w,count,x1,y1,x2,y2;
Scanner sc=new Scanner(System.in);
t=sc.nextInt();
for(k=0;k<t;k++){
n=sc.nextInt();
m=sc.nextInt();
w=sc.nextInt();
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
hole[i][j]=false;
temp[i][j]=false;
}
}
for(i=0;i<w;i++)
{
x1=sc.nextInt();
y1=sc.nextInt();
x2=sc.nextInt();
y2=sc.nextInt();
for(j=x1;j<=x2;j++)
hole[y1][j]=true;
}
pathtoexit(n-1,m-1);
count=0;
for(i=0;i<n;i++)
{
for(j=0;j<m;j++)
{
if(!hole[i][j]&&!temp[i][j])
count++;
}
}
System.out.println(count);
}
}
static void pathtoexit(int r,int c)
{
if(temp[r][c]||hole[r][c])
return;
if(r-1>=0)
pathtoexit(r-1,c);
if(c-1>=0)
pathtoexit(r,c-1);
temp[r][c]=true;
return;
}
}
Now, this fails when the size of the grid NxM is very large, of the order of 10^5 or more. I get an error of "Java heap overflow".
Can anyone please help me sort this issue out and make the necessary changes in the code as required ?
It's difficult to propose changes to your code because your approach to the problem is not really practical. You are using a brute force approach to find every path but the problem's parameters allow for a 10^6 x 10^6 maze - finding a path from every cell is really not practical as it could require you to check 10^18 cells which would take more time than the current age of the universe!
The solution here is to start with the insight that the only way for a cell to be 'BAD' is if it is caught behind intersecting horizontal and vertical lines of holes (considering the edges to also represent holes). The secret is to look for those groups and calculate how many 'BAD' cells they generate.

If keep receiving runtimeException

The following code works fine with the eclipse but then in online editor I keep receiving runtimeException(NoSuchElementFoundException) please help me where am I going wrong?
{I have used sieve of eratosthenes alogirthm to find prime number in required range by the user}
public class test {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
if(sc.equals(""))
{
sc.close();
}
Integer t = sc.nextInt();
while(t>0)
{
int m = sc.nextInt();
int n = sc.nextInt();
int prime[]= new int[n+1];
for(int i=0;i<=n;i++)
{
prime[i]=1;
}
prime[0]=0;
prime[1]=0;
for(int i=2;i<Math.sqrt(n);i++)
{
if(prime[i]==1)
{
for(int j=2;i*j<n;j++)
{
prime[i*j]=0;
}
}
}
for(int i=m;i<n;i++)
{
if(prime[i]==1)
{
System.out.println(i+" ");
}
}
System.out.println();
t--;
}
}
}
I tried your code over the site you mentioned. I changed the class visibility to be default to avoid some compilation error. It produced internal error with no further details and it suggested to test the code on https://ideone.com/ site. I used the sample test case and it passed successfully on ideone site..I suggest that you use hacker rank, I think it is more handy. In hacker rank you can unlock test cases to trace errors, bugs in your code, also you can have discussion with colleagues there over the problem. On the other hand I couldn't get the exception you mentioned "NoSuchElementFoundException" if you have detailed stack trace kindly include it and I shall update my answer accordingly.

Improving the runtime of Insertion sort

Just to practice and improve my programming skills I decided to solve the questions on InterviewStreet. I decided to start off using simple InsertionSort (I expected it to be simple).
https://www.interviewstreet.com/challenges/dashboard/#problem/4e90477dbd22b
I am able to get correct answers. However the runtime is a problem. The max allowed runtime for the test cases is 5s. However I am going slightly overboard.
I used a few tricks (like removing something out of code. Storing the result of str.lenght() etc). However I am still slightly overboard.
The current runtimes for the ten test cases are:
1 Passed Success 0.160537
2 Passed Success 0.182606
3 Passed Success 0.172744
4 Passed Success 0.186676
5 Failed Time limit exceeded. 5.19279
6 Failed Time limit exceeded. 5.16129
7 Passed Success 2.91226
8 Failed Time limit exceeded. 5.14609
9 Failed Time limit exceeded. 5.14648
10 Failed Time limit exceeded. 5.16734
I am not aware what the test cases are.
Kindly help me improve the runtime.
Thank you.
import java.util.Scanner;
import java.io.*;
//import java.io.BufferedWriter;
//import java.io.FileInputStream;
//import java.io.FileOutputStream;
public class Solution {
public static int[] A=new int[100001];
public static int swap=0;
public static void InsertionSort(int n){
for (int i=1; i<=n; i++){
for (int var=i; var>0; var--){
if (A[var]<A[var-1]){
int temp=A[var-1];
A[var-1]=A[var];
A[var]=temp;
swap++;
}
else {
break;
}
}
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String str = br.readLine();
int number_of_cases =Integer.parseInt(str);
int counter;
int [] spacearray = new int[100000];
for (int j=0; j<number_of_cases; j++){
swap=0;
str = br.readLine();
int arraylength = Integer.parseInt(str);
str = br.readLine();
counter=0;
int strlen=str.length();
for (int i=0; i<strlen-1; i++){
if (str.charAt(i) == ' '){
spacearray[counter]=i;
counter++;
}
}
spacearray[counter]=strlen;
A[0]=Integer.parseInt(str.substring(0, spacearray[0]));
for (int i=1; i<=arraylength-1; i++){
A[i] = Integer.parseInt(str.substring(spacearray[i-1]+1,spacearray[i]));
}
InsertionSort(arraylength-1);
System.out.println(swap);
}
}
}
Use binary indexed trees to solve this problem
The bottleneck here is the insertion sort algorithm. It's time complexity is O(n^2) and with n up to 10^5, one can easily exceed 5 seconds on the interviewstreet judge machine. Also when a TLE signal is thrown, your program stops executing. So the slight overhead to 5 isn't really an indicator of the actual time it takes to run. It is introduced by the delay between detecting TLE and stopping the execution.
For the sake of history, this question appeared originally as a part of codesprint-1. Using insertion sort isn't the way to proceed here, otherwise the question would have been a complete give away.
Hint
Use the fact that all values will be within [1,10^6]. What you are really doing here is finding the number of inversions in the array A, i.e. find all pairs of i < j s.t. A[i] > A[j]. Think of a data structure that allows you to find the number of swaps needed for each insert operation in logarithmic time complexity (like Binary Indexed Trees). Of course, there are other approaches.

Categories