I have been solving competitive coding questions for a brief period of time now, and I have observed something. Sometimes, in any solution involving array manipulations or addition or multiplication, some of the test cases gave me TLE (time limit exceeded).
I used integer variables. When I change such variables to the long type, the execution time for that test case reduces, and sometimes, makes my solution excepted 100% instead of partial acceptance.
My question is, how, and why, is this the case? And in which scenarios would this (long over int) not hold true? The only disadvantage I can think of for not using long over int in such scenarios would be higher memory consumption.
UPDATE - Code Example: Here is a sample code I wrote to rotate a given array of numbers to the right by K places and display the output.
public static void main(String [] args)
{
Scanner sc = new Scanner(System.in);
StringBuilder sb = new StringBuilder();
int numTestCases = sc.nextInt();
for(int i = 0; i< numTestCases;i++)
{
int arraySize = sc.nextInt();
int offset = sc.nextInt();
int [] array = new int[arraySize];
if(offset>=arraySize)
offset = offset%arraySize;
int count = 0;
while(count<arraySize)
{
array[offset] = sc.nextInt();
offset = (offset+1)%arraySize;
count++;
}
for(int j = 0; j< arraySize; j++) {
sb.append(array[j]);
sb.append(" ");
}
sb.append("\n");
}
System.out.println(sb.toString());
sc.close();
}
One of the test cases gave a TLE for this code. However, when changed the array type to long, that test case passed.
The test case contained an array of 89384 integers (all less than 100 - or atleast within int range) and had to be rotated right by 930886 places.