Vectors vs Arrays. TIME LIMIT EXCEED

in this problem:
https://practice.geeksforgeeks.org/problems/merge-two-sorted-arrays/0

solution is accepted using arrays.
https://ide.geeksforgeeks.org/KPtW2E47MA

but with vector it is giving TIME LIMIT EXCEED
https://ide.geeksforgeeks.org/qPceaYA12v

i have tried declearing vectors both inside and outside T loop ;

This occurs due to the slow performance of push_back() in case of vectors.
Because in each operation, you are pushing an element in the containers which also results in the increase in size of container by 1.

This extra effort by the compiler gave you TLE. :slightly_smiling_face:

Try replacing:

        vector <int> A;
        vector <int> B;
        for (int i = 0;i < n;i++)///taking input in array A
        {   
            cin >> temp;
            A.push_back(temp);
        }


        for (int i = 0;i < m;i++)//taking input in array B
        {   
            cin >> temp;
            B.push_back(temp);
        }

with:

        vector <int> A(n);
        vector <int> B(m);
        for (int i = 0;i < n;i++)///taking input in array A
        {   
            cin >> A[i];
        }

        for (int i = 0;i < m;i++)//taking input in array B
        {   
            cin >> B[i];
        }
3 Likes

i did replaced it. it still gives TLE

can u give better vector version of it?
i tried declearing vectors size prior and took inputs like arrays.
but still TLE.

Lots of people in the comments section saying that vector gives TLE - I’m guessing the time limits are extremely tight. Try using fast input/output.

4 Likes

thanks for advice . appreciate ur time.
i ll look fast input/output.

2 Likes

You are using ‘endl’ for new line.
Always use “\n”, it is much faster.

Also fast input/output is always recommended.

3 Likes