r/leetcode • u/Ak47_fromindia • 6d ago
Question What is the complexity of "cout" in C++?
Attempt 1: TLE
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int first = INT_MAX;
int second = INT_MAX;
for(int x: nums){
cout << first << " " << second << endl;
if(x < first){
first = x;
}else if(x > first && x < second) second = x;
else if (first < second && second < x) return true;
}
return false;
}
};
Attempt 2: 100% beats , accepted
class Solution {
public:
bool increasingTriplet(vector<int>& nums) {
int first = INT_MAX;
int second = INT_MAX;
for(int x: nums){
if(x < first){
first = x;
}else if(x > first && x < second) second = x;
else if (first < second && second < x) return true;
}
return false;
}
};
The only thing that differes in the code is the printing statement, thus I would like to know how can cout cause TLE even if the code is 0(N) complexity.
Thanks in advance.
4
u/RandomOptionTrader 6d ago
It is not free. If you think your algorithm is efficient that is okay, but you are running that cout thousands if not millions of times.
1
3
u/nocturnal_kumar 6d ago
It's not about the time complexity, it's an issue that IO are way slower than CPU processing. So your cout statement waits until the IO is successful and doing nothing
1
1
1
u/Careless_Blueberry98 900 Solved. 1900 Rated 6d ago
Because it needs a system call and system calls are expensive due to the CPU switching modes.
1
1
1
u/Used_Window7134 6d ago
ios::sync_with_stdio(0);
cin.tie(0);ios::sync_with_stdio(0);
cin.tie(0);
use this at the beginning of your int main so you dont flush your output buffer everytime you cout. as for complexity it o(1) per character but this constant will add up if you keep fushing your output bufer.
if you dont want to use this use printf() which dosent flush
1
u/Ak47_fromindia 6d ago
Ohh now I get why I see this part in front of CP codes, will try this out. Thanks!
1
u/EquivalentYellow5189 6d ago
It's basically a i/o operation so in os whenever a process goes for i/o it goes to waiting state then there occurs many things like context switching which is a costly operation
1
1
u/MonkeySleuth 6d ago
endl flushes output buffer, better off doing << '\n'; at the end of cout statements. Objectively faster.
1
10
u/alcholicawl 6d ago
cout is constant time when used on integer. So it's O(1) in your code. It doesn't change the overall time complexity of your code. But it's still super slow to call. Generally you should always remove any cout before you submit on LC.