Non-empty subsets from HackerEarth exercises - java

Actually, I am doing an exercise from HackerEarth.
The exercise is pretty simple: I have to use a min-max algorithm but I have some struggles when I use the readLine method from the variable BufferReader.
I cannot figure out why but my min variable for an iteration keep the Integer.MAX_VALUE.
Code
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
class TestClass {
public static void main(String args[] ) throws Exception {
//BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
int N = Integer.parseInt(br.readLine());
while (T-- >= 0) {
String[] line = br.readLine().trim().split("\\s");
int min = Integer.MAX_VALUE;
for (int i = 0; i < line.length - 1; i++) {
min = Math.min(min, Integer.parseInt(line[i]));
}
System.out.println(min);
}
}
}
Output
1
2147483647
2

I've made many corrections to your code.
You are not reading every N of every test case, you only read it once. You have to put it inside the while loop.
Method trim is unnecessary because inputs from the problems are always in the right manner.
Use > not >= when comparing using array lengths or the number of test cases, because it will iterate once more even if the index is already beyond the array's capacity or 0.
public static void main(String args[] ) throws Exception {
//BufferedReader
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int T = Integer.parseInt(br.readLine());
while (T-- > 0) {
br.readLine(); // to read N
String[] line = br.readLine().split(" ");
int min = Integer.MAX_VALUE;
for (int i = 0; i < line.length; i++) {
min = Math.min(min, Integer.parseInt(line[i]));
}
System.out.println(min);
}
}

Related

Exception in thread "main" java.lang.NumberFormatException: For input string: "" for user input

Even though I have parsed it to an integer value I'm still getting an error. I need to get the integer value from a String input where I remove the comma and space, and store it in an array, then I convert that array to an integer array
import java.util.ArrayList;
import java.util.Scanner;
public class SeriesSolution {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int count = sc.nextInt();
ArrayList<Integer> modes = new ArrayList<>();
for (int x = 0; x < count; x++) {
String lines = sc.nextLine();
String[] strs = lines.split(", ");
int[] array = new int[strs.length];
for (int i = 0; i < strs.length; i++) {
if (Integer.parseInt(strs[i]) > 0 && Integer.parseInt(strs[i]) < 100) {
array[i] = Integer.parseInt(strs[i]);
}
}
modes.add(mode(array));
}
for (int y:modes){
System.out.println(y);
}
}
private static int mode(int a[]) {
int maxValue=0, maxCount=0;
for (int anA : a) {
int count = 0;
for (int anA1 : a) {
if (anA1 == anA) ++count;
}
if (count > maxCount) {
maxCount = count;
maxValue = anA;
}
}
return maxValue;
}
}
The issue is mainly because Scanner accepts Enter keystroke as input. And because of which
String lines = sc.nextLine();
this peice of code stores an empty string into lines variable. This empty string throws NumberFormatException when passed to parseInt()
I would recommend you to use BufferedReader with InputStreamReader
BufferedReader br = new BuffereedReader(new InputStreamReader(System.in));
This is good for larger inputs and is error free. Though empty checks are must as prevention is better.
If you want to use Scanner, I would recommend you to update the code and use the below snippet of code.
String lines = "";
while (lines.equals("")) {
lines = sc.nextLine();
}
Do a check before the parseInt
if (strs[i] != null && !"".equals(strs[i]) && Integer.parseInt(strs[i]) ...
Or surround it with a try catch to catch the NumberformatException that will happen if a string is inserted instead of a number

Understanding Time Complexity

Can some one help me to understand the time complexity for the below code. The program is for shifting all the zeros to the right of an array.
class TestClass {
public static void main(String args[] ) throws Exception {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String []s = br.readLine().split(" ");
int a[] = new int[s.length];
for(int i=0;i<s.length;i++)
a[i]=Integer.parseInt(s[i]);
int j= a.length-1;
int i=0;
while(j>=0 && i<a.length-1 && j-i>0){
if(a[i]==0){
while(a[j]==0)
j--;
int temp=a[i];
a[i]=a[j];
a[j]=temp;
}
i++;
}
for(int k:a)
System.out.print(k+" ");
}
}
Calculating time complexity will be difficult if we try to include the a[i]=Integer.parseInt(s[i]);since in Integer class , parseInt()method runs inside a while loop, and depending on the length of the passing String, it will gives different time complexity, but if we assume that it will take O(F(q)), the time complexity of your code will be O(s.length^2)+O((s.length)*O(F(q))

NumberFormatException when reading from System.in

I am getting these exception while running the code
Exception in thread "main" java.lang.NumberFormatException: null
at java.lang.Integer.parseInt(Integer.java:542)
at java.lang.Integer.parseInt(Integer.java:615)
at Ideone.main(Main.java:22)
I am new at java and unable to resolve this error. Please help !
Here is my code ->
import java.util.*;
import java.lang.*;
import java.io.*;
class etest {
public static void main (String[] args) throws java.lang.Exception{
int n,k;
Scanner in = new Scanner(System.in);
n = in.nextInt();
k = in.nextInt();
BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
//StringTokenizer token = new StringTokenizer(input.readLine());
int total=0;
int values[] = new int[n];
for(int i =0; i<n; i++) {
values[i] = Integer.parseInt(input.readLine());
if ((values[i]%k)==0) {
total++ ;
}
input.close();
}
System.out.println(total);
}
}
I am using the following input sample to run the program.
Thank you so much for any help!
7 3
1
51
966369
7
9
999996
11
your program has too many errors :
You can change your code as below
public static void main(String[] args) throws java.lang.Exception {
int n, k;
Scanner in = new Scanner(System.in);
n = in.nextInt();
k = in.nextInt();
int total = 0;
int values[] = new int[n];
for (int i = 0; i < n; i++) {
values[i] = in.nextInt();
if ((values[i] % k) == 0) {
total++;
}
}
System.out.println(total);
}
1) you should not close BufferedReader it will automatically close input stream also.
2) you don't need Scanner and BufferedReader at the same time. your solution can use any one of them.
3) better to use try-catch while using Integer.parseInt(String str);
if you want to go with BufferedReader then you need to change your code as
public static void main(String[] args) throws java.lang.Exception {
int n, k;
BufferedReader input = new BufferedReader( new InputStreamReader(System.in));
String str[]= input.readLine().split(" ");
n = Integer.parseInt(str[0]);
k = Integer.parseInt(str[1]);
int total = 0;
int values[] = new int[n];
for (int i = 0; i < n; i++) {
values[i]=Integer.parseInt(input.readLine());
if ((values[i] % k) == 0) {
total++;
}
}
System.out.println(total);
}

Getting TLE in CodeChef and need for improvement of code

I am trying to solve a practice question of CodeChef . In this problem we are given N numbers Ai...An and we first have to sort(ascending order) the numbers and then add the alternate numbers starting from the last and show the output for each test cases , the test cases has 2 parts :
1>Constraints :
1 ≤ Ai ≤ 109
1 ≤ N ≤ 1000
2>Constraints:
1 ≤ Ai ≤ 109
1 ≤ N ≤ 105
You can see the full problem here.
The first part of my problem was successfully submitted but second part showed NZEC because I was using long to add those numbers(which was beyond that range). So I decided to use Strings to add up my numbers here is the method :
public static String myStringWayToAdd(String first , String second){
String temp = "";
if(first.length() < second.length()){
temp = first;
first = second;
second = temp;
}
temp = "";
int carry = 0;
for(int i=1;i<=first.length();++i){
if(i <= second.length()){
carry += Integer.parseInt(first.charAt(first.length()-i)+"") + Integer.parseInt(second.charAt(second.length()-i)+"");
}
else{
carry += Integer.parseInt(first.charAt(first.length()-i)+"");
}
temp += carry%10;
carry = carry/10;
}
if(carry != 0)
temp += carry;
StringBuilder myResult = new StringBuilder(temp);
return(myResult.reverse().toString());
}
But now it shows TLE(Time Limit Expire) , So then I thought to use BigInteger(which I am not pretty much Aware of but I saw some tutorials) :
BigInteger big = new BigInteger("0");
big = big.add(BigInteger.valueOf(mySort.get(j))); //for addition and mySort is my ArrayList
But this gave me NZEC I don't know whywell now I want to use double variable but there is a problem with that too, because with double large numbers will be in form of exponential value like :
1.243536E15 which will not be accepted by the machine, so is there any good way to solve this problem and not getting any Time Limit Expiry?.
Any help will really be appreciated. Thank you in Advance.
Edit 1 :
I changed baxck the variable to long and run and this time strangely I got TLE here is my code :
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
import java.math.BigInteger;
import java.lang.Number;
class CFEA{
public static void main(String[] s){
Scanner scan = new Scanner(System.in);
int testCases = scan.nextInt();
for(int i = 0 ; i<testCases;++i){
long sum = 0;
//BigInteger big = new BigInteger("0");
ArrayList<Integer> mySort = new ArrayList<Integer>();
int n = scan.nextInt();
for(int j = 1 ; j <= n ; ++j){
mySort.add(scan.nextInt());
}
Collections.sort(mySort);
for(int j = mySort.size()-1 ; j >= 0 ; j=j-2){
sum += mySort.get(j);
}
System.out.println(sum);
}
}
}
And here is Link to my submission.Is there Anything I can optimize in my code?
The sum of all number is at most 10^9 * 10^5 = 10^14. It is small enough to fit into long. There is no need to use BigInteger.
java.util.Scanner has performance issues. You can implement a custom scanner(using BufferedReader) to speed up your code.
Here is my implementation of a scanner:
import java.io.*;
import java.util.StringTokenizer;
public class FastScanner {
private BufferedReader reader;
private StringTokenizer tokenizer;
public FastScanner(InputStream inputStream) {
reader = new BufferedReader(new InputStreamReader(inputStream));
}
public String next() throws IOException {
while (tokenizer == null || !tokenizer.hasMoreTokens()) {
String line = reader.readLine();
if (line == null)
throw new IOException();
tokenizer = new StringTokenizer(line);
}
return tokenizer.nextToken();
}
public int nextInt() throws IOException {
return Integer.parseInt(next());
}
public void close() {
try {
reader.close();
} catch (IOException e) {
//ignore
}
}
}
I did some changes in my Program and it was All Accepted a much relief after submitting for about 20 times , here is my new code :
import java.util.Scanner;
import java.util.ArrayList;
import java.util.Collections;
class CFEA{
public static void main(String[] s){
Scanner scan = new Scanner(System.in);
byte testCases = Byte.parseByte(scan.nextLine()); //used byte for test cases instead of int
for(int i = 0 ; i<testCases;++i){
long sum = 0;
//BigInteger big = new BigInteger("0");
ArrayList<Integer> mySort = new ArrayList<Integer>();
int n = Integer.parseInt(scan.nextLine());
String input = scan.nextLine();
String[] my = input.split(" ");
for(String myString : my){
mySort.add(Integer.parseInt(myString));
}
Collections.sort(mySort);
for(int j = mySort.size()-1 ; j >= 0 ; j=j-2){
sum += mySort.get(j);
}
System.out.println(sum);
}
}
}
I think the main villain was that I was scanning for Integers N number of times as in this :
for(int j = 1 ; j <= n ; ++j){
mySort.add(scan.nextInt());
}
When N was something Like 100000 then this really slows it down.So i used 1 String for complete line and then Split it into Integers using split method as in :
String input = scan.nextLine(); //only 1 Scanner
String[] my = input.split(" ");
for(String myString : my){
mySort.add(Integer.parseInt(myString));
}
Although My code got submitted I still think there is Further scope for optimization , so please do answer if you have something better

Which is the most efficient way of taking input in Java?

I am solving this question.
This is my code:
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] t = new int[n];
int count = 0;
for (int i = 0; i < n; i++) {
t[i] = sc.nextInt();
if (t[i] % k == 0) {
count++;
}
}
System.out.println(count);
}
}
But when I submit it, it get's timed out. Please help me optimize this to as much as is possible.
Example
Input:
7 3
1
51
966369
7
9
999996
11
Output:
4
They say :
You are expected to be able to process
at least 2.5MB of input data per
second at runtime.
Modified CODE
Thank you all...I modified my code and it worked...here it is....
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String[] input = br.readLine().split(" ");
int n = Integer.parseInt(input[0]);
int k = Integer.parseInt(input[1]);
int count = 0;
for (int i = 0; i < n; i++) {
if (Integer.parseInt(br.readLine()) % k == 0) {
count++;
}
}
System.out.println(count);
}
regards
shahensha
This could be slightly faster, based on limc's solution, BufferedReader should be faster still though.
import java.io.IOException;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws IOException {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int count = 0;
while (true) {
try {
if (sc.nextInt() % k == 0) {
count++;
}
} catch (NoSuchElementException e) {
break;
}
}
System.out.println(count);
}
}
How about this?
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int count = 0;
for (int i = 0; i < n; i++) {
if (sc.nextInt() % k == 0) {
count++;
}
}
System.out.println(count);
You may consider reading big chunks of input and then get the numbers from there.
Other change is, you may use Integer.parseInt() instead of Scanner.nextInt() although I don't know the details of each one, somethings tells me Scanner version performs a bit more computation to know if the input is correct. Another alternative is to convert the number yourself ( although Integer.parseInt should be fast enough )
Create a sample input, and measure your code, change a bit here and there and see what the difference is.
Measure, measure!
BufferedReader is supposed to be faster than Scanner. You will need to parse everything yourself though and depending on your implementation it could be worse.

Categories

Resources