Test case failed

test case failed. no increasing the value ans.size

Hello @sauzepplin please share your code by saving it on ide.codingblocks.com .

#include

#include

using namespace std;

// solution

vector majorityElements(vector vec)

{

int element1 = vec[0];

int count1 = 1;

int element2 = 0;

int count2 = 0;

for (int i = 1; i < vec.size(); i++)

{

    if (element1 == vec[i])

    {

        count1++;

    }

    else if (element2 == vec[i])

    {

        count2++;

    }

    else if (count1 == 0)

    {

        element1 = vec[i];

        count1 = 1;

    }

    else if (count2 == 0)

    {

        element2 = vec[i];

        count2 = 1;

    }

    else

    {

        count1--;

        count2--;

    }

}

count1 = count2 = 0;

for (int i = 0; i < vec.size(); i++)

{

    if (vec[i] == element1)

    {

        count1;

    }

    else if (vec[i] == element2)

    {

        count2;

    }

}

vector<int> ans;

if (count1 > vec.size() / 3)

{

    ans.push_back(element1);

}

if (count2 > vec.size() / 3)

{

    ans.push_back(element2);

}

return ans;

}

int main()

{

int n;

cin >> n;

vector<int> vec;

int input;

for (int i = 0; i < n; i++)

{

    cin >> input;

    vec.push_back(input);

}

vector<int> ans;

ans = majorityElements(vec);

if (ans.size() == 0)

{

    cout << "No Majority Elements";

}

else

{

    for (int i = 0; i < ans.size(); i++)

    {

        cout << ans[i] << " ";

    }

}

cout << endl;

return 0;

}

@sauzepplin please share your code by saving it on ide.codingblocks.com .

I have saved it but not being able to share it please help me with this

@sauzepplin go the link above and then in the file section you will see option for save after that share the link.

check now:

the code is working fine now but I wanted to ask that we had to do the problem in 0(1) space but we are using extra space. Please explain.