0

You can only swapping at most one pair of elements in either of the arrays.

My code is working but I don't know how to make my code faster. I need it to be executed in 3s.

boolean checkSimilarArray(int[] a, int[] b) { int sml = 0; boolean result = false; for (int i = 0; i<a.length; i++){ if (a[i]!= b[i]){ sml++; } } Arrays.sort(a); Arrays.sort(b); if(Arrays.equals(a,b)){ if (sml <= 2){ result = true; }else{ result = false; } } return result; } 

Expected input and output images

expected input and output 1

expected input and output 2

expected input and output 3

expected input and output 4

2
  • 5
    What is the criteria of being similar? Can you provide the expected input and output? Commented Oct 2, 2021 at 17:13
  • I believe OP means two arrays similar if one can be obtained from the other by swapping at most one pair of elements in either of the arrays. Commented Oct 2, 2021 at 17:43

1 Answer 1

1

In your code, the expensive part is the sorting, so you should solve it without that.

An array that is equal except for one pair swapped will be identical in all but two positions (let's call them d1 and d2), and the positions will satisfy a[d1] == b[d2] && a[d2] == b[d1].

In code:

int d1 = -1; int d2 = -1; for (int i = 0; i < a.length; i++) { if (a[i] != b[i]) { if (d1 == -1) { d1 = i; } else if (d2 == -1) { d2 = i; } else { return false; // too many differences } } } return d1 == -1 || (d2 != -1 && a[d1] == b[d2] && a[d2] == b[d1]); 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.