Motivation: I was solving an array based i/o problem and encountered Time Limit Errors, it was later found that the code for java ran roughly 10x
slower than the python implementation.
Question: I would like to know which part of my code failed in the latter implementation (in Java) given that the algorithmic complexity for both the codes is the same. And what should I use in order to avoid it.
The problem is from https://www.hackerearth.com/practice/codemonk/ and a direct link doesn't exist.
Given problem abstract: If an indexed array arr
is given, print the contents of the array whose index is shifted by a constant.
Example:
let arr=1,2,3,4 then arr shift 3 towards right means 2,3,4,1
Input format:
- first line: number of test cases
- for each test case:
- first line contains n,k where n represents number of elements and k represents the shifting
- the second line contains the elements of the array
Here is my fast python code
from sys import stdin t= int(input()) for i in range(t): n,k=list(map(int,input().split())) a=list(map(int,stdin.readline().split())) for i in range(n): print(a[(i-k)%n],end=" ") print("\n")
Here are the results:
.
Now, I wrote another solution in Java
//imports for BufferedReader import java.io.BufferedReader; import java.io.InputStreamReader; //import for Scanner and other utility classes import java.util.*; class TestClass { public static void main(String args[] ) throws Exception { BufferedReader input = new BufferedReader(new InputStreamReader(System.in)); Scanner s = new Scanner(System.in); int t = Integer.parseInt(input.readLine()); while(t-->0){ String[] nk = input.readLine().split(" "); int n = Integer.parseInt(nk[0]); int k = Integer.parseInt(nk[1]); String [] arr = input.readLine().split(" "); for(int i = 0; i < n ; i++){ System.out.printf("%s ",arr[(i-k%arr.length+arr.length)%(arr.length)]); } System.out.printf("%n"); } } }
And here are the results:
.
Scanner
methods making the hot spots.\$\endgroup\$Scanner s
is used at all here?\$\endgroup\$i-k%arr.length+arr.length
is vulnerable to integer overflow. That may explain timeouts.\$\endgroup\$