Circular Array Rotation Time Limit Exceeded(TLE) - java

I am really confused why my java code is not working it is giving TLE on Code Monks on Hacker Earth.
Here is the link to the question - Link to Question
the first question MONK AND ROTATION
import java.util.Scanner;
class TestClass {
static int[] ar=new int[100001];
public static void main(String args[] ){
Scanner in=new Scanner(System.in);
byte t=in.nextByte();
while(--t>0){
int n=in.nextInt();
int k=in.nextInt()%n;
for(int i=0;i<n-k;i++)
ar[i]=in.nextInt();
for(int i=0;i<k;i++)
System.out.print(in.nextInt()+" ");
for(int i=0;i<n-k;i++)
System.out.print(ar[i]+" ");
System.out.println();
}
}
}
I don't know why is it giving TLE I think there is some infinite loop going.
the question at the site is-
Monk and Rotation
Monk loves to perform different operations on arrays, and so being the principal of HackerEarth School, he assigned a task to his new student Mishki. Mishki will be provided with an integer array A of size N and an integer K , where she needs to rotate the array in the right direction by K steps and then print the resultant array. As she is new to the school, please help her to complete the task.
Input:
The first line will consists of one integer T denoting the number of test cases.
For each test case:
The first line consists of two integers N and K, N being the number of elements in the array and K denotes the number of steps of rotation.
The next line consists of N space separated integers , denoting the elements of the array A.
Output:
Print the required array.
Constraints:
1<=T<=20
1<=N<=10^5
0<=K<=10^6
0<=A[i]<=10^6
Sample Input
1
5 2
1 2 3 4 5
Sample Output
4 5 1 2 3
Explanation
Here T is 1, which means one test case.
denoting the number of elements in the array and , denoting the number of steps of rotations.
The initial array is:
In first rotation, 5 will come in the first position and all other elements will move to one position ahead from their current position. Now, the resultant array will be
In second rotation, 4 will come in the first position and all other elements will move to one position ahead from their current position. Now, the resultant array will be
Time Limit: 1.0 sec(s) for each input file
Memory Limit: 256 MB
Source Limit: 1024 KB

Think from a different perspective. Instead of splitting the string and converting it into an array and applying the iterative logic, we can apply a different logic.
The trick is you just need to find the position of the input string where we have to split only once.
By that I mean,
input=>
6 2       //4 is the length of numbers and 2 is the index of rotation
1 2 3 4 5 6     //array (take input as a string using buffered reader)
Here, we just need to split the array string at the 2nd last space i.e. 4th space. So the output can be achieved by just splitting the string once-
5 6 1 2 3 4
first split- 5 6 + space + second split- 1 2 3 4
This logic worked for me and all the test cases passed.
Also don't forget to cover the corner case scenario when array input string is just one number.
Code Snippet-
int count=0;
for(int k=0; k<arr.length(); k++) {
if(arr.charAt(k)==' ')
count++;
if(count==size-rot) {
System.out.println(arr.substring(k+1,arr.length())
+ " " + arr.substring(0,k));
break;
}
}

Problem is here
for(int i=0;i<n-k;i++) //this loop you are using for storing input elements in array
ar[i]=in.nextInt();
for(int i=0;i<k;i++) // here you again taking the input you don't need this loop
System.out.print(in.nextInt()+" ");
for(int i=0;i<n-k;i++)
System.out.print(ar[i]+" ");
You also need to change the condition in while loop while(--t>0) to while(--t >= 0). It should be >= 0 other wise it will not work. Other solution is to use post decrement while(t-- > 0)
You are trying to print right rotation of the array. So you need to start printing the elements from index n - k. Then you need to calculate the end index it is (n - k) + n this is because array has n elements. Then you can access array elements like this arr[i % n].
Here is the complete working solution
class TestClass {
static int[] ar = new int[100001];
public static void main(String args[]) {
Scanner in = new Scanner(System.in);
byte t = in.nextByte();
while (--t >= 0) {
int n = in.nextInt();
int k = in.nextInt() % n;
for (int i = 0; i < n; i++)
ar[i] = in.nextInt();
for (int i = n - k; i < n + (n - k); i++)
System.out.print(ar[i % n] + " ");
System.out.println();
}
}
}

Related

Why does my CalcOddIntegers method always return zero?

This method is supposed to take user input for the length of the array, and then the integers that are part of the array, and return the amount of odd numbers in the array. However, it always returns zero for the count of odd integers and I am unsure as to why. The scanner is declared outside of this method.
System.out.print("Enter length of sequence\n");
int length = console.nextInt();
int[] array = new int[length];
System.out.print("Enter the sequence: \n");
int count = 0;
int i = 0;
for (i = 0; i < length; i++) {
array[i] = console.nextInt();
}
for (i = 0; i < length -1; i++); {
if (array[i] % 2 != 0) {
count++;
}
}
System.out.printf("The count of odd integers in the sequence is %d\n", count);
}
Example of console:
2. Calculate the factorial of a given number
3. Calculate the amount of odd integers in a given sequence
4. Display the leftmost digit of a given number
5. Calculate the greatest common divisor of two given integers
6. Quit
3
Enter length of sequence
4
Enter the sequence:
1
2
3
4
The count of odd integers in the sequence is 0
I have tried experimenting with the for statements with different variables to see if something was conflicting but nothing has worked.
Remove the semi-colon (;) in the line
for (i = 0; i < length -1; i++);
the semi-colon terminates the loop hence an assumption that your line does nothing.
After the second for there is a semicolon that shouldn't be there. The syntax is technically correct however, there is nothing to execute so the block that checks for odd numbers is going to be executed only once. I suggest using a debugger that will help you troubleshoot issues easier.

Java method to calculate the square root via minuend and subtrahend and print each step

I am tasked with creating a program in java which calculates the square root of a double and goes through each step of calculating it manually. The requirements are:
split the number into number pairs including the decimal point (1234.67 -> 12 34 67) to prepare for subtraction. If the number is uneven, a zero must populate (234.67 -> 02 34 67)
Print each pair (each pair is a minuend), one at a time, into the console and have the console show the subtraction. Subtrahend starts at 1 and so long as the result >= 0, the subtrahend increases by 2.
The count of subtrahends is the first number of the final square root output, the count of subtrahends from the second round is the second number of the square root output, etc.
From the first subtrahend round, take the remainder and join it to the second number pair, this is the new minuend for the second round of subtraction
Calculate the second subtrahend in round two by doubling the first number of the square root output and adding 1 in the first digit position
Repeat step 2, increasing by 2 each time
Step 5 and 6 repeat until two decimal places are reached
My question is with the number pairs in step 1 and getting the subsequent subtrahends after step 3 as a number to calculate. We are given the following visual:
My current thought is to put the double into a string and then tell java that each number pair is a number. I have a method created which creates a string from a double, but I am still missing how to incorporate the decimal place numbers. From my C class, I remember multiplying decimals by 100 to "store" the decimal numbers before converting them back later with another division by 100. I'm sure there is a java library that is able to do this but we are specifically not allowed to use them.
I think I should be able to continue on with the rest of the problem once I get past this point of splitting the number into number pairs inclusive of the decimals.
This is also my first stack post so if you have any tips on how to better write questions for future posts that would be helpful as well.
This is my current array method to store a given double into an array:
public static void printArray(int [] a) //printer helper method
{
for(int i = 0; i < a.length; i++)
{
System.out.print(a[i]);
}
}
public static void stringDigits (double n) //begin string method
{
int a [] = new int [15];
int i = 0;
int stringLength = 0;
while(n > 1)
{
a[i] = (int) (n % 10);
n = n / 10;
i++;
}
for(int j = 0; a[j] != 0; j++)
{
System.out.print(a[j]);
if(a[j] != 0)
{
stringLength++;
}
}
System.out.println("");
System.out.println(stringLength);
int[] numbersArray = new int[stringLength];
int g = 0;
for(int k = a.length-1; g < numbersArray.length; k--)
{
if(a[k] > 0)
{
numbersArray[g] = a[k];
g++;
}
}
System.out.println("");
printArray(numbersArray);
}
I've tried at first to store the value of the double into an int[] a array so that I can then select the numbers in pairs and then somehow combine them back into numbers. So if the array is {1,2,3,4,5,6} my next idea is to get java to convert a[0] + a[1] into the number 12 to prepare for the subtraction step.
This link looks close but does anyone know why the numbers are "10l" and "100l" etc? I've tested some of the answers and they dont produce the proper squareroot compared to the sqrt function from the math library.
Create a program that calculates the square root of a number without using Math.sqrt

Why does my code fail the hidden input test cases?

This is the problem to be solved:
John is assigned a new task today. He is given an array A containing N integers. His task is to update all elements of array to some minimum value x , that is, A[i] = x; 1 <= i <= N; such that sum of this new array is strictly greater than the sum of the initial array.
Note that x should be as minimum as possible such that the sum of the new array is greater than the sum of the initial array.
Input Format:
First line of input consists of an integer N denoting the number of elements in the array A.
Second line consists of N space separated integers denoting the array elements.
Output Format:
The only line of output consists of the value of x.
Sample Input:
5
12345
Sample Output:
4
Explanation:
Initial sum of array= 1 + 2 + 3 + 4 + 5 = 15
When we update all elements to 4, sum of array = 4 + 4 + 4 + 4 + 4 = 20 which is greater than 15.
Note that if we had updated the array elements to 3, sum = 15 which is not greater than 15. So, 4 is the minimum value to which array elements need to be updated.
** ==> Here is my code. How can I improve it? or What is the problem in this code? **
import java.util.Scanner;
public class Test2 {
public static void main(String []args){
Scanner s=new Scanner(System.in);
int check=0, sum=0, biggest=0;
int size=s.nextInt();
if(size>=1 && size<=100000) {
int[] arr=new int[size];
for(int i=0; i<size; i++){
int temp=s.nextInt();
if(temp>=1 && temp<=1000) {
arr[i] = temp;
biggest=biggest > temp ? biggest:temp;
sum=sum+temp;
}
else break;
}
for(int i=1; i<biggest; i++){
check=(size*i)>sum ? i:0;
}
System.out.print(check);
}
else System.err.print("Invalid input size");
}
}
Issue:
for(int i=1; i<biggest; i++){
check=(size*i)>sum ? i:0;
}
There are 2 problems with this, hence it doesn't work. They are as follows-
(size*i)>sum ? i - The problem statement states that it needs minimum possible sum greater than sum of array of elements. Your code blindly assigns i to check without checking the minimality.
check=(size*i)>sum ? i:0 - So, even if you had come across some integer previously, you lost it because you assigned it to 0 if the condition is not satisfied.
I will share my idea of how would I go about this.
Approach 1
Sum all elements like you did.
Now, take average of elements - sum / size of the array. Let's say we store it in a variable average.
Print average + 1 as your answer, as that is the value that could give you minimum possible sum > sum of array itself.
Time Complexity: O(n), where n is size of the array.
Space Complexity: O(1)
Approach 2
Sum all elements like you did.
Calculate min and max for the array and store it in variables, say mini and maxi.
Now, do a binary search between mini and maxi and keep checking the minimum sum > sum criteria.
In this process, you will have variables like low, mid and high.
low = mini,high = maxi
while low <= high:
mid = low + (high - low) / 2
If mid * size <= sum,
low = mid + 1
else
high = mid - 1
Now, print low as your answer.
Let range = maxi - mini.
Time Complexity: O(n) + O(log(range)) = O(n) asymptotically, where n is size of the array.
Space Complexity: O(1)
Not sure if I completely followed what your attempt was, but there should be a pretty straightfoward solution. You know the size of the array and you can easily iterate through the array to get the value of the elements stored in it. All you need to do to find your min x is to take sumOfArray/size of array and then add one to the result to make your result higher.
In your example 15/5=3. 3+1 = 4 so that's your answer. If the numbers summed to 43, 43/5 = 8 r 3, so your answer is 9 (9*5=45). Etc.
When trying some other test cases, then the results are wrong. Try:
Input:
5
1 1 1 1 5
Expected Output: 2 Actual Output: 4
and
Input:
5
5 5 5 5 5
Expected Output: 6 Actual Output: 0

Adding Two Elements in an Array (Java)

I need to write a method that adds the two last elements of two arrays together and add the sum on another array. But if the two elements are more than 10, then I would need to carry that number to the next array.
This program should be similar to what an odometer does.
Here is my sample code.
int [] sum(int []number1, int []number2)
{
int [] total;
int carry = 0;
for ( int k = numbers1 - 1; k >= 0; k++)
{
sum = number1[k] + number2[k] + carry;
carry = sum/10;
total[k] = sum
}
return total;
}
An example output would be:
0 1 2 3 4
0 8 9 9 9
4 5 7 0 3
5 4 7 0 2
So the top array is just a visual aid that tells where the position for the number is.
The program is suppose to add the next two arrays together. i.e. 9 + 3 = 12
Since 12 is above 9, it carries over the 10 to the next set of arrays, that is why the third array only has a 2 in its place, and that is why the next array is 9 + 0 = 0; because the 10 was carried over.
I am not sure why my code won't work. I don't get the right numbers. Could anyone give any hints or solution to the problem?
-Thanks
I assume numbers1 is the number of elements in the array.
In this case it should be k-- instead of k++ because you are starting from the last element and moving backword.

1D Array, multiples of 5. Simple but new to coding

Write a program that assigns and stores the first 20 multiples of 5 in the array called Data, no other array can be used in the program. The program should output the elements of the array, according to the following:
write only the commands to assign and store the values in Data
output the array: 10 numbers/line with the sum of each line
output the array: in reversed order, 5 numbers/line with the sum for each line
the odd indexed position values (Data[1], Data[3], Data[5],...), 5 values/line and their sum
the even indexed position values (Data[3], Data[4], Data[6],...), 5 values/line and their sum
I have part 1. so far:
int data[]=new int[21]; int sum=0;
for(int i=1;i<21;i++){
data[i]=5*i;
sum+= data[i];
if(i%11==0)
System.out.println();
System.out.print(data[i] + " ");
}
System.out.println("sum " + sum);
int a[]=new int[21];
for(int i=1;i<21;i++){
a[i]=5*i;
//System.out.print(a[i] + " ");
}
System.out.println();
I need help with the rest.
As told in comments, we're not here to code for you, you will lose really important experience about learning how to program.
But I can give you some tips that may help in your assignment.
write only the commands to assign and store the values in Data
output the array: 10 numbers/line with the sum of each line
DONE, RIGHT? ;)
output the array: in reversed order, 5 numbers/line with the sum for each line
We wont speak now in built in functions of Arrays or Collections. Do it easy: to reverse array reverse the loop:
for(int i=20i>=0;i--){
Better use the array length:
for(int i=data.length-1;i>=0;i--){
To make increments (for example by 5) you can use d[i] += 5 equivalent to d[i] = d[i] + 5 in the same way a++ is a = a + 1.
you need 5 values per line right? To know when to finish a line, use modulus or remainder operator %.
if (i % 5 == 0)
That means, if modulus of i / 5 equals 0 (so 5 multiple), use it to print sum and new line (println)
the odd indexed position values (Data1, Data[3], Data[5],...), 5 values/line and their sum
Remembering for this part: i+=2 is same than i = i + 2 ;)
the even indexed position values (Data[3], Data[4], Data[6],...), 5 values/line and their sum
To sum, create a new variable to store values OUTSIDE the loop, and sum inside:
int total = 0;
for(int i=1;i<21;i++){
total += data[i]; // equals to total = total + data[i]
// more code
if (i % 5 == 0) {
// print total of the line and skip line
// reset total variable total = 0;
}
// more code
}

Categories