top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration Why to Join

Facebook Login
Site Registration

How to find if a string is a permutation of another string using C?

0 votes
How to find if a string is a permutation of another string using C?
posted Apr 24, 2017 by anonymous

Share this question
Facebook Share Button Twitter Share Button Google+ Share Button LinkedIn Share Button Multiple Social Share Button
define permutation
I think its simple "bac" is a permutation of "abc" i.e. same set of characters just different order....

2 Answers

0 votes
void permutation(char str[],char str2[])
    int size;
    int i=0,j=0;
    int review = 0;
    if(strlen(str) != strlen(str2))
        printf("string 2 is not permutation of string 1");
        return 0;

    size = strlen(str);

    while(i != size)
        while(j != size)
            if(str[i] != str2[j])
                str[i] = '*';
                str2[j] ='+';

    if(size == review)
        printf("str 2 is permutation of str 1");
        printf("str 2 is not permutation of str 1");
answer Apr 24, 2017 by Leon Martinović
0 votes

1) Create count arrays of size 256 for both strings. Initialize all values in count arrays as 0.
2) Iterate through every character of both strings and increment the count of character in the corresponding count arrays.
3) Compare count arrays. If both count arrays are same, then return true.

# define NO_OF_CHARS 256

bool permutation(char *str1, char *str2)
    // Create 2 count arrays and initialize all values as 0
    int count1[NO_OF_CHARS] = {0};
    int count2[NO_OF_CHARS] = {0};
    int i;

    // For each character in input strings, increment count in
    // the corresponding count array
    for (i = 0; str1[i] && str2[i];  i++)

    // If both strings are of different length. Removing this
    // condition will make the program fail for strings like
    // "aaca" and "aca"
    if (str1[i] || str2[i])
      return false;

    // Compare count arrays
    for (i = 0; i < NO_OF_CHARS; i++)
        if (count1[i] != count2[i])
            return false;

    return true; // Str1 is permutation of str2

Credit: geeksforgeeks

answer Apr 25, 2017 by Salil Agrawal
Similar Questions
+4 votes

Given a dictionary of strings and another string find out if the string is an exact match to some words in the dictionary or varies at most in only one place of some word of the dictionary?

0 votes

Find the first non repeating character in a string.

For example
Input string: "abcdeabc"
Output: "e"

–1 vote

Write a C program to check if the given string is repeated substring or not.
1: abcabcabc - yes (as abc is repeated.)
2: abcdabababababab - no

Contact Us
+91 9880187415
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Karnataka INDIA.