mag_08
mag_08

Reputation: 1

IF statement giving wrong answer whereas ELSE IF is working fine

I am solving Count Occurences of Anagrams question on GeekForGeeks.

int search(string ana, string s) {

    unordered_map<char, int> m;
    for(auto it : ana) m[it]++;

    int k=ana.length();
    int count=m.size();
    
    int i=0, j=0;
    int ans=0;
    
    while(j<s.length()){
    
        if(m.find(s[j])!=m.end()){
            m[s[j]]--;
            if(m[s[j]]==0) count--;
        }
         
        if(j-i+1<k) j++;
        
       if(j-i+1==k){  //**else if works**
           
            if(count==0) ans++;
           
            if(m.find(s[i])!=m.end()){
                m[s[i]]++;
                if(m[s[i]]==1) count++;
            }

            i++;
            j++;
        }
    }
    return ans;
}

This code works when using else if(j-i+1==k), but when using simply if(j-i+1==k) it gives the wrong answer.

for test case:

s = forxxorfxdofr
ana = for
Output: 3

But when using only if it gives

Output :0 

Upvotes: 0

Views: 188

Answers (1)

Vlad from Moscow
Vlad from Moscow

Reputation: 310930

The difference is that after this if statement

    if(j-i+1<k) j++;

the variable j is incremented and the next if statement

   if(j-i+1==k){  /

in any case gets the control and can evaluate to true.

If to use if else statement

    if(j-i+1<k) j++;
    
    else if(j-i+1==k){  /

then if the first if statement was evaluated the else if statement will be skipped.

So logically the behavior is different for these two code snippets.

Here is a simplified demonstrative program.

#include <iostream>

int main() 
{
    int x = 0;
    
    if ( x == 0 ) ++x;
    if ( x == 1 ) ++x;
    
    std::cout << "x = " << x << '\n';
    
    x = 0;
    
    if ( x == 0 ) ++x;
    else if ( x == 1 ) ++x;
    
    std::cout << "x = " << x << '\n';
    
    
    return 0;
}

The program output is

x = 2
x = 1

Investigate it.

Upvotes: 2

Related Questions