Problem: Given two strings, write a java program to check whether both are permutations for each other.

package in.questionsforinterview.problems;

import java.util.Arrays;

public class PermutationCheck {

	/*
	 * Method #1: check two strings for identical character counts
	 */
	public boolean perm(String s1, String s2) {
		if (s1 == null || s2 == null || s1.length() != s2.length()) {
			return false;
		}
		int[] counts = new int[256];
		
		// count number of times each char repeated
		for (char c : s1.toCharArray()) {
			counts[c]++;
		}
		
		// decrement each char count until second array completed
		for (char c : s2.toCharArray()) {
			if (--counts[c] < 0) {
				return false;
			}
		}
		return true;
	}

	/*
	 * Method #2: sort two strings first, then check whether both are same
	 */
	public boolean perm1(String s1, String s2) {
		if (s1 == null || s2 == null || s1.length() != s2.length()) {
			return false;
		}
		
		// convert to arrays
		char[] arr1 = s1.toCharArray();
		char[] arr2 = s1.toCharArray();

		// sort both arrays
		Arrays.sort(arr1);
		Arrays.sort(arr2);

		if (Arrays.equals(arr1, arr2))
			return true;
		else
			return false;
	}

	public static void main(String[] args) {
		PermutationCheck cp = new PermutationCheck();
	
		// True case
		String s1 = "asasdasd";
		String s2 = "asassdda";
		
		System.out.println("Method #1 - " + cp.perm(s1, s2));

		System.out.println("Method #2 - " + cp.perm1(s1, s2));
		
		// False case
		s1 = "abcd";
		s2 = "abcf";
		
		System.out.println("Method #1 - " + cp.perm(s1, s2));

		System.out.println("Method #2 - " + cp.perm1(s1, s2));

	}

}

output

Method #1 - true
Method #2 - true
Method #1 - false
Method #2 - true