Lapindromes, can anyone tell me why i am getting wrong answer

import java.util.Scanner;

class Codechef
{
public static void main(String[] args) {
Scanner s=new Scanner(System.in);
int t=s.nextInt();

       for(int i=0;i<t;i++) {
        String  x = s.next();
        lapindrome(x);
       }
}
public static void lapindrome(String x) {
        int l = x.length();
        String s1;
        String s2;
        int count = 0;
        
        
        if(l%2==0)
        {
             s1 = x.substring(0,(l/2));
            s2 = x.substring((l/2),l);
        }
        
        else
        {
            s1 = x.substring(0,(l/2));
            s2 = x.substring((l/2+1),l);
        }
        
        char a1[]=s1.toCharArray();
        char a2[]=s2.toCharArray();
        
        for(int i = 0;i<a1.length;i++)
        {
            int temp=0;
            int temp1=0;
            
            
            for(int j=0;j<a1.length;j++)
            {
                if(a1[i]==a1[j])
                temp++;
            }
            for(int k =0;k<a2.length;k++)
            {
                if(a1[i]==a2[k])
                temp1++;
            }
           if(temp==temp1)
            count=1;
            else
            count=0;
        }
       
        for(int i = 0;i<a2.length;i++)
        {
            
            int temp=0;
            int temp1=0;
            
            
            for(int j=0;j<a2.length;j++)
            {
                if(a2[i]==a2[j])
                temp++;
            }
            for(int k =0;k<a1.length;k++)
            {
                if(a2[i]==a1[k])
                temp1++;
            }
            
            if(temp==temp1)
            count=1;
            else
            count=0;
         }
        if(count == 1)
        {
           System.out.println("YES"); 
        }
        else
        {
            System.out.println("NO");
        }
    }

}

you are making it a little complex by checking the frequency of each character , I suggest you to sort both the halves of the string and compare them directly.

1 Like

My solution to this problem , Hope you find it useful.

1 Like

Simply use two hash maps one for each half of the string instead of making it too complex with nested loops. U can finish it in one loop if you use hash maps.

2 Likes

thankuu.

See if it helps.
`

int main()
{
#ifndef ONLINE_JUDGE
input_output
#else
fastio
#endif

int t;
cin>>t;
while(t--){
    string s; cin>>s;
    vector<int>m(26, 0);
    int i = 0, j = s.size()-1;
    while(i<j)
    {
        m[s[i++]-'a']++;
        m[s[j--]-'a']--;
    }
    bool exit = true;
    for(auto c: m){
        if(c != 0){
            exit = false;
            cout<<"NO"<<endl;
            break;
        }
    }
    if(exit)cout<<"YES"<<endl;
}
return 0;

}