About nptel c program

We say that a string ‘s’ is an anagram of another string ‘t’ if the
letters in ‘s’ can be rearranged to form ‘t’.

For example, “butterfly” is an anagram of “flutterby”, since a
rearrangement of the first word results in the second.

We say that a position ‘i’ in ‘s’ and ‘t’ match, if ‘s’ is an anagram of
‘t’, and s[i]==t[i].

In this question, you will be given two words, ‘s’ and ‘t’. You have
to output the number of matching positions if s is an anagram of t,
and -1 if s is not an anagram of t.

Input

The input consists of two lines. The first line contains the first
string, with length <= 100 characters. The second line contains the
second string, with length <= 100 characters.

Output

If the first string is an anagram of the second string, then output
the number of matching positions. Otherwise, print -1.

Sample Input 1

butterfly
flutterby

Sample Output 1

2

Sample Input 2

home
come

Sample Output 2

-1

Since length is small<=100, you could just do as it is asked in the question. First check both words if they are anagrams, and then check for each position and report ans.

1 Like

have you got answer for first question

#include <stdio.h>

int check_anagram(char [],char []);

int main()
{
char a[100],b[100];
int flag;

//printf(“Enter first string : “);
scanf(”%c”,a);

//printf(“Enter second string : “);
scanf(”%c”,b);

flag=check_anagram(a,b);

if(flag == 1)
printf(“1”);
else
printf("-1");

return 0;
}

int check_anagram(char a[],char b[])
{
int first[26] = {0}, second[26] = {0}, c = 0;

while (a[c] != ‘\0’)
{
first[a[c]-‘a’]++;
c++;
}

c = 0;

while (b[c] != ‘\0’)
{
second[b[c]-‘a’]++;
c++;
}

for (c = 0; c < 26; c++)
{
if (first[c] != second[c])
return 0;
}

return 1;
}

well it simple first for cheking if its anagam just look if they have same and equal letters and for checking position just iterate over the string

O(n) per test case

if you have question 1 answer then please post here

  1. first of all you have to check anagram .

  2. all charcters of 1st string must be present in 2nd string.

  3. if it is true then you will check position.

  4. and if it is false then you will print -1.

//