write c program to check if one string is permutation of another string. This is a simple interview question for a programmer. For example if one string is “hello” and another is llheo ,then both the strings are permutation of each other. Let us discuss solution.

Sort method with O(n*log(n)) complexity

  1. if given strings are not equal , print no else
  2. sort both the strings.
  3. compare both strings with respect to their indexes.
  4. if both strings are equal print yes
  5. else print no.

c++ program check if one string is permutation of another string

#include<iostream>
#include<algorithm>
#include <string>
using namespace std;

bool is_perm(string s, string t)
{
	// if size of s and t mismatch
	if(s.length() != t.length())
		return false;

	// sort s and t
	sort(s.begin(), s.end());
	sort(t.begin(), t.end());

	// compare s and t now by indexes
	for(unsigned int i=0; i < s.size();i++)
	{
		if(s.at(i) != t.at(i))
			return false;
	}

	return true;
}
int main()
{
	string s = "hello";
	string t = "llheo";

	if(is_perm(s,t))
		cout << "strings are permutation of each other"<<endl;
	else
		cout << "strings are not a permutation of each other"<<endl;

	return 0;
}

There is a problem posted at www.hackerrank.com where you can test your solution.

Ref:

http://stackoverflow.com/questions/2131997/checking-if-two-strings-are-permutations-of-each-other




Related Contents to follow