Amazon Interview Question
SDE-2sCountry: India
Interview Type: In-Person
trivial recursive implementation:
public class LangfordPairing {
private int[] internal;
private int len;
public LangfordPairing( int n ) {
len = n * 2;
internal = new int[len];
for( int i = 0; i < 2*n; i++ ) {
internal[i] = 0;
}
}
public boolean doPairingHelper( int n, int startPosition ) {
if( startPosition < 0 || startPosition + n + 2 > len ) {
return false;
}
if( n == 1 ) {
int pos = getFirstNonZeroPosition(0);
if( pos != -1 && pos+n+1 < len && internal[pos] == 0 && internal[pos+n+1] == 0 ) {
internal[pos] = n;
internal[pos+n+1] = n;
return true;
}
return false;
}else {
int pos = getFirstNonZeroPosition( startPosition );
if( pos != -1 && pos+n+1 < len && internal[pos] == 0 && internal[pos+n+1] == 0 ) {
internal[pos] = n;
internal[pos+n+1] = n;
if( doPairingHelper( n-1, 0 ) ) {
return true;
}else {
internal[pos] = 0;
internal[pos+n+1] = 0;
}
}
return doPairingHelper( n, startPosition+1 );
}
}
public boolean doPairing() {
return doPairingHelper( len/2, 0 );
}
private int getFirstNonZeroPosition( int start ) {
if( start >= 0 && start < len ) {
for( int i = start; i < len; i++ ) {
if( internal[i] == 0 ) {
return i;
}
}
}
return -1;
}
public int[] getResult() {
return internal;
}
public static void main( String[] args ) {
LangfordPairing lf = new LangfordPairing( 8 );
if( lf.doPairing() ) {
int[] result = lf.getResult();
for( int i : result ) {
System.out.print( i + ", " );
}
}else {
System.out.println( "Failed!" );
}
}
}
public class Langford {
private static boolean print(int a[], int k, int n) {
if (k == n + 1) {
return true;
}
for (int i = 0; i < a.length; ++i) {
if (a[i] == 0 && i + k + 1 < a.length && a[i + k + 1] == 0) {
a[i] = a[i + k + 1] = k;
if (print(a, k + 1, n)) {
return true;
}
a[i] = a[i + k + 1] = 0;
}
}
return false;
}
public static void print(int n) {
int a[] = new int[n << 1];
boolean ret = print(a, 1, n);
if (ret) {
for (int i = 0; i < a.length; ++i) {
System.out.print(a[i] + " ");
}
System.out.println();
} else {
System.out.println("Sorry");
}
}
public static void main(String args[]) {
print(Integer.parseInt(args[0]));
}
}
another solution. prints all possible combinations for a given N (else prints nothing)
EDIT: the array should be of size 2*N - check can be added
- VJ April 17, 2013