Check if two strings are anagrams or not

Are the two strings or phrases anagrams or not algorithm

First thing first, What is anagram?

Anagrams are phrases/words of which one can be created from the other with rearrangement of characters.

Examples of anagram strings:

Debit card and bad credit
George Bush and He Bugs Gore

Now, given two strings, how would do find if the strings are anagrams or not.

The approach I used is a follows:

1. remove the space out of the strings
2. compare the length of strings, if they don’t match, they ain’t anagrams
3. sort the characters of each string
4. check character by character and see if they match till the end

This is approach I used with o(nlogn) because of the sorting part. All the others can be done in o(n)

A java solution for anagram algorithm

Sorting array by two fields in PHP

assume you have the following array:

$arr=array(
	array('field1'=>108, 'field2'=>'some'),
	array('field1'=>200, 'field2'=>'zen'),
	array('field1'=>105, 'field2'=>'bar'),
	array('field1'=>100, 'field2'=>'foo'),
	array('field1'=>200, 'field2'=>'yellow'),
	array('field1'=>200, 'field2'=>'any'),
);
How would you approach if you want to sort the array first by field1 and then by field2. That is sort the array by field1 but for field1 values that are same, sort by field two.. just like the SQL equivalent of ORDER By column1, colum2..

usort($arr, function($a, $b){
	if ($a['field1']>$b['field1']){
		return 1;
	}elseif($a['field1']<$b['field1']){
		return -1;
	}else{
		return strcasecmp($a['field2'], $b['field2']);
	}
});

Browser automatically sorting json object based on key problem..

Json data got sorted on browser by its key

This a problem where the browser decides to sort the json you provided its own way rather than the one you sorted.

And it happens especially if you have key value pair in json payload you are passing.

So the scenario would be, there JSON data you are sending from the backend is sorted and you displayed it on front end with some javascript, but the result you are showing is not sorted with the original sorting order you set.

Solution

I observed that some browsers, at least Chrome, is doing the sorting in the situation that is discussed above.

For the fix: make the key of the json values you are passing string format rather than number

like

in place of using:
{1:"one", 4:"four"}

use

{"1":"one", "4":"four"}