NZEC error on Hackerearth in java - java

I am getting NZEC exception in java for below code on hackerearth. Can anyone please help?
Added the try catch block as well
import java.util.HashMap;
import java.util.Scanner;
class TestClass {
public static void main(String args[]) throws Exception {
try {
Scanner sc = new Scanner(System.in);
String S = new String();
HashMap<Long, String> hm = new HashMap<>();
S = sc.nextLine();
int len = sc.nextInt();
long[] q = new long[len];
for (int i = 0; i < len; i++) {
q[i] = sc.nextLong();
}
Long key = (long) 1;
for (int i = 0; i < S.length(); i++) {
for (int j = i + 1; j <= S.length(); j++) {
hm.put(key++, S.substring(i, j));
}
}
for (int i = 0; i < len; i++) {
if (q[i] <= hm.size())
System.out.println(hm.get(q[i]));
else {
System.out.println(-1);
}
}
} catch (Exception e) {
}
}
}

It mostly occurs when negative array index is accesed or the program which we have written takes up more space than the allocated memory for our program to run.

Related

Hackerrank (Java) MAXIMUM LENGTH SUBSTRING - timeout error

Link to this problem:
https://www.hackerrank.com/contests/takneek/challenges/maximum-length-substring/problem
The code passes the initial test case but then times out when I go to submit on hacker rank for much larger strings. I have a feeling it's the algorithm I'm using for the unique substrings, how do I cut down this time into something efficient?
My code:
import java.io.*;
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);
LinkedList<Integer> kList = new LinkedList<Integer>();
LinkedList<String> setout = new LinkedList<String>();
LinkedList<String> setLex = new LinkedList<String>();
//Get the original text
String text = in.nextLine();
//Get n from the file
int n = in.nextInt();
//Get the next needed items for comparison and order
for (int i = 0; i < n; i++) {
kList.add(in.nextInt());
}
setout = getAllUniqueSubset(text);
setLex = sortLexographically(setout);
int findMax = findMaximumSub(setLex, kList, 0);
// System.out.println(setLex);
System.out.println(findMax);
}
//Get the unique subset to begin with and return it
public static LinkedList<String> getAllUniqueSubset(String text) {
LinkedList<String> set = new LinkedList<String>();
for (int i = 0; i < text.length(); i++) {
for (int j = 0; j < text.length() - i; j++) {
String elem =text.substring(j, j + (i+1));
if (!set.contains(elem)) {
set.add(elem);
}
}
}
return set;
}
public static LinkedList<String> sortLexographically(LinkedList<String> setout){
for(int i = 0; i < setout.size()-1; ++i) {
for (int j = i + 1; j < setout.size(); ++j) {
if (setout.get(i).compareTo(setout.get(j)) > 0) {
String testLex = setout.get(i);
setout.set(i, setout.get(j));
setout.set(j, testLex);
}
}
}
return setout;
}
public static int findMaximumSub(LinkedList<String> setLex, LinkedList<Integer> kList, int maxCheck){
for (int i = 0; i < kList.size()-1; i++) {
if (maxCheck < setLex.get(kList.get(i)).length()) {
maxCheck = setLex.get(kList.get(i)).length();
}
}
return maxCheck;
}
}

TimeLimitExceeded upon submission

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
class Main {
public static void main(String[] args) throws NumberFormatException, IOException {
BufferedReader input = new BufferedReader(new InputStreamReader(System.in));
int t = Integer.parseInt(input.readLine());
for (int i = 0; i < t; i++) {
String[] arrayData = input.readLine().split(" ");
int[] cardsi = new int[arrayData.length];
int e = 0;
for(int a = 0; a < arrayData.length; a++){
cardsi[e] = Integer.parseInt(arrayData[a]);
e++;
}
int X = cardsi[0];
int N = cardsi[1];
long count = 0;
for (int j = 2; j < cardsi.length; j++) {
for (int l = 3; l <= (cardsi.length - 1); l++) {
if ((cardsi[j] + cardsi[l]) == X &&(j != l)) {
count++;
}
}
}
System.out.println((i + 1) + ". " + count);
}
}
}
Time limit exceeded error is appearing upon submitting this LCPC12F problem on spoj.. what might be a solution? Is scanner a major trouble for such error to appear?
Have you ever run those codes on IDE?
When I give the number to t element then arrayData (in this case, we should enter int type not String, because of the java.lang.NumberFormatException), it shows Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 and int N = cardsi[1]; is the main problem on your code I think. This is because String[] arrayData = input.readLine().split(" "); size is 1 so you do not have cardsi[1] element on your int array

Sorting strings alphabetically in an array. Java

I have to sort strings in an array for a school project. Our teacher won't allow us to use array,sort().
i have to use 2 sort methods but they aren't working too well.
The first one returns double of each value. ie John, jack, adam, tom will return adam,adam,jack,jack,john,john,tom,tom.
public static void sort() {
inputFileNames();//inputs list of names from a file.
for (int i = 0; i < size - 1; i++) {
for (int j = i + 1; j < size; j++) {
if (stArr[i].compareTo(stArr[j])>0) {
temp = stArr[i];
stArr[i] = stArr[j];
stArr[j] = temp;
}
}
}
display("The names are: ");// method to display array
System.out.println("");
}
the second sort doesn' run:
public static void bubbleSort() {
inputFileNames();
for (int i = size - 1; i >= 0; i--) {
for (int j = 0; j <= i; j++) {
if (stArr[j].compareTo(stArr[j+1])>0) {
temp = stArr[j];
stArr[j] = stArr[j + 1];
stArr[j + 1] = temp;
}
}
}
display("The names are: ");
System.out.println("");
}
input and display:
static void display(String heading) {
System.out.println(heading + "\n");
for (int i = 0; i < size; i++) {
System.out.println(stArr[i]);
}
}
static void inputFileNames() {
try {
Scanner scFile = new Scanner(new File("Names.txt"));
while (scFile.hasNext()) {
stArr[size] = scFile.nextLine();
size++;
}
} catch (FileNotFoundException ex) {
System.out.println("File not found.");
}
}
/* 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
{ Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int i,j;
String[] stArr = new String[n];
for(i=0;i<n;i++)
{
stArr[i]=sc.next();
// System.out.println(stArr[i]);
}
//inputs list of names from a file.
for (i = 0; i < n ; i++) {
for (j = i+1 ; j < n; j++) {
if (stArr[i].compareTo(stArr[j])>0)
{
String temp = stArr[i];
stArr[i] = stArr[j];
stArr[j] = temp;
// System.out.println(stArr[i]);
// System.out.println(stArr[j]);
}
}
}
for(i=0;i<n;i++)
{
System.out.println(stArr[i]);
}
// your code goes here
}
}
This Is the answer for first code. I am not good in file handling so you have to use your input method. I know Scanner thats why i have used here.
In Your Second Example Your j loop is wrong it should be for ( j = 0; j <= i-1; j++). And Please Mark It as answer if your problem is solved

Java String Out of Bounds Exception

import java.util.*;
import java.lang.*;
public class pro19
{
public static void main(String[] args)
{
Scanner in = new Scanner(System.in);
String word;
System.out.print("Enter word: ");
word = in.nextLine();
StringBuffer s = new StringBuffer(word);
int l = word.length();
for(int i = 1; i<=l; i++)
{
for(int j = i+1; j<=l; j++)
{
if(s.charAt(i)==s.charAt(j))
{
s = s.deleteCharAt(j);
l--;
}
else
continue;
}
}
System.out.println("Word after deletion of duplicate letters: "+s);
}
}
I wrote this program to delete duplicate characters as school homework.
But whenever I run it I get the following output(exercise being the input):
Enter word: exercise
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 8
at java.lang.StringBuffer.charAt(Unknown Source)
at pro19.main(pro19.java:19)
Please help and tell me where I am going wrong.
You Write
for(int i = 1; i<=l; i++)
You can Write like This
for(int i = 0; i<=l-1; i++)
{
for(int j = i+1; j<=l-1; j++)
{
if(s.charAt(i)==s.charAt(j))
{
s = s.deleteCharAt(j);
l--;
}
else
continue;
}
Correct your loop conditions :
for(int i = 1; i < l; i++)
{
for(int j = i+1; j < l; j++)
{
What about word.replaceAll("(.)\\1+", "$1") ?

Changes to be made to make the given code more effecient

https://www.hackerrank.com/contests/csindia/challenges/pin-problem-1
The below solution for above problem is not getting submitted, "timeout terminated" message was popping out. For successful submission what changes should be made below code? Please help me out.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
class Solution
{
public static void main(String args[])
{
try{
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
int testcase = Integer.parseInt(br.readLine());
if (testcase > 0 && testcase <= 100000)
{
int outarr[] = new int[testcase];
for (int i = 0; i < testcase; i++)
{
String str = br.readLine();
StringTokenizer st = new StringTokenizer(str," ");
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
if (n > 0 && n <= 10000 && m > 0 && m <= 10)
{
int maincounter = 0;
str = br.readLine();
String s[];
s = str.split(" ");
if (s.length == m)
{
for (int k = 1; k <= n; k++)
{
int counter = 0;
for (int l = 0; l < s.length; l++)
{
if (k % (Integer.parseInt(s[l])) == 0)
counter++;
}
if (counter == s.length)
maincounter++;
}
outarr[i] = maincounter;
}
else
{
System.out.println("Enter the specified values of m not more than that");
testcase--;
}
}
else
{
System.out.println("Enter value of n in between 1 to 10^4 and value of m in between 0 to 10");
testcase--;
}
}
for (int i = 0; i < testcase-1; i++)
{
System.out.println(+outarr[i]);
}
System.out.print(+outarr[testcase-1]);
}
else
{
System.out.println("Enter the test value in between 1 to 10^5");
}
}
catch(Exception ae)
{
System.out.println("Exception caught");
}
}
}
You have a lot of unnecessary checks in your code that are slowing it down a little, but honestly not enough to make it not finish. Hackerrank tells you what the bounds will be for the input, so you don't need to verify it for these purposes.
I've gone through the code and added comments for you where this could be improved:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
class Solution
{
public static void main(String args[])
{
try{
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
int testcase = Integer.parseInt(br.readLine());
// This check is unnecessary, hackerrank told you testcase would be in these
// bounds.
if (testcase > 0 && testcase <= 100000)
{
int outarr[] = new int[testcase];
for (int i = 0; i < testcase; i++)
{
String str = br.readLine();
StringTokenizer st = new StringTokenizer(str," ");
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
// This check is unnecessary, hackerrank told you m and n would be in these
// bounds.
if (n > 0 && n <= 10000 && m > 0 && m <= 10)
{
int maincounter = 0;
str = br.readLine();
String s[];
s = str.split(" ");
// This check is unnecessary, hackerrank told you the next line
// would have m numbers
if (s.length == m)
{
for (int k = 1; k <= n; k++)
{
int counter = 0;
for (int l = 0; l < s.length; l++)
{
// Here, instead of checking every number to see
// if it is divisible, you can check and see if
// it isn't. If it isn't, then you shouldn't bother
// checking the rest of the possible numbers because
// you know that k isn't a possible pin number.
// Add a flag that indicates if the pin is still valid,
// if it isn't, move on to the next pin.
if (k % (Integer.parseInt(s[l])) == 0)
counter++;
}
if (counter == s.length)
maincounter++;
}
outarr[i] = maincounter;
}
else
{
System.out.println("Enter the specified values of m not more than that");
testcase--;
}
}
else
{
System.out.println("Enter value of n in between 1 to 10^4 and value of m in between 0 to 10");
testcase--;
}
}
// Why the -1? You can just do i < testcase and print it all here
// instead of on multiple lines.
for (int i = 0; i < testcase-1; i++)
{
System.out.println(+outarr[i]);
}
System.out.print(+outarr[testcase-1]);
}
else
{
System.out.println("Enter the test value in between 1 to 10^5");
}
}
catch(Exception ae)
{
System.out.println("Exception caught");
}
}
Code after changes:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
class Solution
{
public static void main(String args[])
{
try{
BufferedReader br =
new BufferedReader(new InputStreamReader(System.in));
int testcase = Integer.parseInt(br.readLine());
int outarr[] = new int[testcase];
for (int i = 0; i < testcase; i++)
{
String str = br.readLine();
StringTokenizer st = new StringTokenizer(str," ");
int n = Integer.parseInt(st.nextToken());
int m = Integer.parseInt(st.nextToken());
int maincounter = 0;
str = br.readLine();
String[] s = str.split(" ");
for (int k = 1; k <= n; k++)
{
boolean stillValid = true;
for (int l = 0; l < m && stillValid; l++)
{
if (k % (Integer.parseInt(s[l])) != 0)
{
stillValid = false;
}
}
if (stillValid)
{
maincounter++;
}
}
outarr[i] = maincounter;
}
for (int i = 0; i < testcase; i++)
{
System.out.println(outarr[i]);
}
}
catch(Exception ae)
{
System.out.println("Exception caught " + ae.getMessage());
}
}

Categories

Resources