public class Permutations {
	private String original;
	private String [] perms;

	private void permute() {
		permuteHelper("", original, 0);
	}

	private int permuteHelper(String prefix, String remaining, int permsSoFar) {
		if (remaining.length() == 0) {
			//System.out.println(prefix);
			perms[permsSoFar] = prefix;
			return permsSoFar + 1;
		}

		for (int i = 0; i < remaining.length(); i++) {
			char chosen = remaining.charAt(i);
			String newPrefix = prefix + chosen;
			String newRemaining = remaining.substring(0, i) 
				+ remaining.substring(i + 1);

			permsSoFar = permuteHelper(newPrefix, newRemaining, permsSoFar);
		}
		return permsSoFar;
	}

	//removes duplicates from the list of permutations
	//uses an O(n^2) method comparing all pairs
	private void removeDuplicates() {
		int n = perms.length;

		// First pass: count how many unique elements
		int uniqueCount = 0;

		for (int i = 0; i < n; i++) {
			boolean isDuplicate = false;

			for (int j = 0; j < i; j++) {
				if (perms[i].equals(perms[j])) {
					isDuplicate = true;
					break;
				}
			}

			if (!isDuplicate) {
				uniqueCount++;
			}
		}

		// Create result array
		String[] tempPerms = new String[uniqueCount];

		// Second pass: copy unique elements
		int index = 0;

		for (int i = 0; i < n; i++) {
			boolean isDuplicate = false;

			for (int j = 0; j < i; j++) {
				if (perms[i].equals(perms[j])) {
					isDuplicate = true;
					break;
				}
			}

			if (!isDuplicate) {
				tempPerms[index] = perms[i];
				index++;
			}
		}

		perms = tempPerms;
	}

	private int factorial(int num) {
		int ret = 1;
		for(int x = num; x >= 1; x--) {
			ret *= x;
		}
		return ret;
	}

	//returns an of all permutations of the string
	//stored in this object
	public String[] getPermutations() {
		return perms;
	}

	//constructs a Permutations object storing theString
	public Permutations(String theString) {
		original = theString;
		perms = new String[factorial(theString.length())];
		permute();
		removeDuplicates();
	}

	public static void main(String[] args) {
		Permutations temp = new Permutations("ABCC");
		String[] theList = temp.getPermutations();
		for(String s : theList) {
			System.out.println(s);
		}
	}
}
