TimeLimitExceeded upon submission - java

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

Related

Java For Loop Trouble, Index Errors

class Main{
public static void main (String str[]) throws IOException{
Scanner scan = new Scanner (System.in);
String message = scan.nextLine();
String[] sWords = {" qey ", " $ "," ^^ "};
int lenOfArray = sWords.length;
int c = 0;
int[] count = {0,0,0};
Getting the error, "java.lang.StringIndexOutOfBoundsException: String index out of range: -1" , in one of the for loops. I want the program to check for each substring in the sWord array and count how many times it occurs in the main message input.
for (int x = 0; x < sWords.length; x++){
for (int i = 0, j = i + sWords[x].length(); j < message.length(); i++){
if ((message.substring(i,j)).equals(sWords[x])){
count[c]++;
}
}
}
}
}
Following your approach, you need to set the value of jwithin the inner loop. Otherwise, it is only assigned on the first iteration. This changes the upper bound in the inner for loop as shown below. You also need to increment the counter index c after you search for an sWord.
import java.io.IOException;
import java.util.ArrayList;
import java.util.Scanner;
public class MyClass {
public static void main (String str[]) throws IOException {
Scanner scan = new Scanner(System.in);
String message = scan.nextLine();
String[] sWords = {" qey ", " $ ", " ^^ "};
int lenOfArray = sWords.length;
int c = 0;
int[] count = {0, 0, 0};
for (int x = 0; x < sWords.length; x++) {
for (int i = 0; i <= message.length()-sWords[x].length(); i++) {
int j = i + sWords[x].length();
if ((message.substring(i, j).equals(sWords[x]))) {
count[c]++;
}
}
++c;
}
}
}
You can find number of occurrences of each string in sWords in the code below:
public static void main(String[] args) {
try {
Scanner scan = new Scanner(System.in);
String message = scan.nextLine();
String[] sWords = {" qey ", " $ ", " ^^ "};
int lenOfArray = sWords.length;
int c = 0;
int[] count = {0, 0, 0};
for (int i = 0; i < lenOfArray; i++) {
while (c != -1) {
c = message.indexOf(sWords[i], c);
if (c != -1) {
count[i]++;
c += sWords[i].length();
}
}
c = 0;
}
int i = 0;
while (i < lenOfArray) {
System.out.println("count[" + i + "]=" + count[i]);
i++;
}
} catch (Exception e) {
e.getStackTrace();
}
}
It's better to use apache commons lang StringUtils
int count = StringUtils.countMatches("a.b.c.d", ".");

NZEC error on Hackerearth in 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.

Odd ArrayList Index out of range Exception [duplicate]

This question already has answers here:
ArrayList initial capacity and IndexOutOfBoundsException [duplicate]
(3 answers)
Closed 7 years ago.
I'm attempting to create a program that will take a given word and find the list of words that could be made out of the letters inside the given word. Here's my code:
package wordfinder;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.TimeUnit;
public class WordFinder {
public static void main(String[] args) throws IOException {
List<String> wordList1 = Files.readAllLines(Paths.get("res", "WordList1.txt"));
List<String> wordList2 = Files.readAllLines(Paths.get("res", "WordList2.txt"));
Scanner scan = new Scanner(System.in);
System.out.println("Please enter the string you would like this program to find words in.");
String wordToFind = scan.nextLine();
ArrayList<String> words = new ArrayList<>();
ArrayList<Character> charArray = new ArrayList<>();
char[] charList = wordToFind.trim().toCharArray();
for (int i = 0; i < charList.length; i++) {
charArray.add(charList[i]);
}
for (int i = 0; i < wordList1.size(); i++) {
char[] charsInWordToCheckAgainst = wordList1.get(i).toCharArray();
ArrayList<Boolean> containsLetter = new ArrayList<>(charsInWordToCheckAgainst.length);
for (int j = 0; j < charsInWordToCheckAgainst.length; j++) {
if (charArray.contains(charsInWordToCheckAgainst[j])) {
containsLetter.set(j, true);
}
}
if (areAllTrue(containsLetter)) {
words.add(wordList1.get(i));
}
}
for (int i = 0; i < wordList2.size(); i++) {
for (int j = 0; j < wordList2.get(i).length(); j++) {
char[] charsInWordToCheckAgainst = wordList2.get(i).toCharArray();
ArrayList<Boolean> containsLetter = new ArrayList(charsInWordToCheckAgainst.length);
for (int k = 0; k < charsInWordToCheckAgainst.length; k++) {
if (charArray.contains(charsInWordToCheckAgainst[k])) {
containsLetter.set(k, true);
}
}
if (areAllTrue(containsLetter)) {
words.add(wordList2.get(i));
}
}
}
System.out.println("Words found: " + words.size());
for(int i = 0; i < words.size(); i++) {
System.out.println("Word " + i + ": " + words.get(i));
try {
TimeUnit.MILLISECONDS.sleep(1);
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
}
public static boolean areAllTrue(ArrayList<Boolean> bools) {
for (int i = 0; i < bools.size(); i++) {
if (!bools.get(i)) {
return false;
}
}
return true;
}
}
And here's the error I'm getting:
Please enter the string you would like this program to find words in.
abcdefghijklmnopqrstuvwxyz
Exception in thread "main" java.lang.IndexOutOfBoundsException: Index: 2, Size: 0
at java.util.ArrayList.rangeCheck(ArrayList.java:653)
at java.util.ArrayList.set(ArrayList.java:444)
at wordfinder.WordFinder.main(WordFinder.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
Process finished with exit code 1
For clarification, WordFinder.java:36 is containsLetter.set(j, true); in the wordList1 for loop. So I really just don't understand why the size of the array is 0. containLetter should not be 0.
UPDATE 1
Updated wordList1 for loop to this:
for (int i = 0; i < wordList2.size(); i++) {
for (int j = 0; j < wordList2.get(i).length(); j++) {
char[] charsInWordToCheckAgainst = wordList2.get(i).toCharArray()
ArrayList<Boolean> containsLetter = new ArrayList<>();
Collections.fill((List) containsLetter, charsInWordToCheckAgainst.length);
for (int k = 0; k < charsInWordToCheckAgainst.length; k++) {
if (charArray.contains(charsInWordToCheckAgainst[k])) {
containsLetter.set(k, true);
}
}
if (areAllTrue(containsLetter)) {
words.add(wordList2.get(i));
}
}
}
But that still gives me the same error.
According to javadoc for ArrayList constructor new ArrayList<>(charsInWordToCheckAgainst.length) accept single parameter - which is initial capacity of list. Capacity - not size.
The difference is as follow.
Size - is number of elements stored in the list.
Capacity - is initial array size created for this structure.
E.g. whenever you adding element to list it will check - do I have capacity for it and if not - re-allocate new array. Purpose of providing this parameter into constructor is to reduce amount of re-allocations. In order to pre-fill list - you need to put elements inside manually or use utility functions provided by 3-rd party libraries.

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

NoSuchElementException when submitting

I'm a Comp Sci student and my university has a club for the ACM Programming competition. I've just started there and I am solving one of the problems. The program works perfectly when I run it and doesn't generate any exceptions. However, when I submit it on the site that runs tests and stuff it gives me:
An exception has occured in your application:
Exception in thread "main" java.util.NoSuchElementException: No line found at java.util.Scanner.nextLine(Scanner.java:1585) at Main.main(Main.java:16)
Code:
import java.util.Scanner;
import java.util.ArrayList;
public class Main
{
public static void main(String[] args)
{
Scanner inMain = new Scanner(System.in);
ArrayList<String> a = new ArrayList<String>();
int q = inMain.nextInt();
for (int j = 0; j < q; j++)
{
Scanner read = new Scanner(System.in);
String temp = read.nextLine();
a.add(temp);
}
int r = inMain.nextInt();
for (int h = 0; h < r; h++)
{
int selection = inMain.nextInt();
if (selection < 0 || selection > q)
{
System.out.println("Rule " + selection + ": No such rule");
} else
{
System.out.println("Rule " + selection + ": "
+ a.get(selection - 1));
}
}
}
}
Check if next line exists before you access it
for (int j = 0; j < q; j++)
{
Scanner read = new Scanner(System.in);
if (read.hasNextLine()){
String temp = read.nextLine();
a.add(temp);
}
}

Categories

Resources