Skip to content

Commit

Permalink
Coursera - algorithms part 1 - integer array permutations
Browse files Browse the repository at this point in the history
  • Loading branch information
eschwabe committed Sep 25, 2015
1 parent 7a618b1 commit b75ac89
Showing 1 changed file with 48 additions and 0 deletions.
48 changes: 48 additions & 0 deletions coursera/algorithms-part1/elementary-sorts/Permutation.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
/**
* Coursera - Algorithms Part I
* Week 2 - Interview Questions - Elementary Sorts
*
* Question 2: Permutation
* Given two integer arrays of size N, design a subquadratic algorithm to
* determine whether one is a permutation of the other. That is, do they
* contain exactly the same entries but, possibly, in a different order.
*
* Solution:
*
* Sort each integer array and run a linear comparison. If any integer does
* not align with the other array, then they are not a permutation of each
* other.
*/

import java.util.Arrays;

class Permutation {

private static boolean isPermutation(int[] a, int[] b) {
int[] a1 = new int[a.length];
int[] b1 = new int[b.length];
System.arraycopy(a, 0, a1, 0, a.length);
System.arraycopy(b, 0, b1, 0, b.length);

Arrays.sort(a1);
Arrays.sort(b1);

for (int i = 0; i < a1.length; ++i) {
if (a1[i] != b1[i]) {
return false;
}
}

return true;
}

public static void main(String[] args) {
int[] a = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
int[] b = { 1, 3, 4, 6 };
int[] c = { 1, 3, 5, 7, 9, 2, 4, 6, 8 };
System.out.println(isPermutation(a, b));
System.out.println(isPermutation(a, c));
System.out.println(isPermutation(a, a));
System.out.println(isPermutation(b, c));
}
}

0 comments on commit b75ac89

Please sign in to comment.