Hi Coders,
I recently solved the problem called "Permutations" on CSES Problem set. It is the 5th problem in the list.
I started by writing the solution in Java, because I'm more proficient in Java. Here is the solution that I have written. For some reasons, my Java solution failed some test with TLE(Time Limit Exceeded) for the following inputs : 11542, 1000000, 906819, 898673, 719525, etc.
import java.util.Scanner;
public class Permutations {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
if (n == 1) {
System.out.println("1");
} else if (n < 4) {
System.out.println("NO SOLUTION");
} else if (n == 4) {
System.out.println("2 4 1 3");
} else {
for (int i = 1; i <= n; i += 2) {
System.out.print(i + " ");
}
for (int i = 2; i <= n; i += 2) {
System.out.print(i);
if (i + 2 <= n) {
System.out.print(" ");
} else {
System.out.println();
}
}
}
}
}
Now, because I'm learning C++ to become really good at Competitive programming, I wrtethe following code in C++ to address the same problem. Here is my C++ code:
#include <iostream>
using namespace std;
int main() {
int n;
cin >> n;
if (n == 1) {
cout << 1 << endl;
} else if (n < 4) {
cout << "NO SOLUTION" << endl;
} else if (n == 4) {
cout << "2 4 1 3" << "\n";
} else {
for (int i = 1; i <= n; i += 2) {
cout << i << " ";
}
for (int i = 2; i <= n; i += 2) {
cout << i;
if (i + 2 <= n) {
cout << " ";
} else {
cout << endl;
}
}
}
}
At my surprise, all the tests passed with C++ code. Now I would like to understand the main reason behind why almost the same code passed all the tests in C++ and not in Java. I thought may I should have use the type long in Java, but I did not need that in C++.
Is there something that I need to understand? Please your advice is welcome to make me understand what happened.
Try FastReader (FastScanner + FastWriter) on java!