4 ms·
That's still pretty naive. You can get away with one char and one int. - Read byte from input - Write byte to output - When byte is "\n": write the counter,
by DarkWiiPlayer 7y ago
That's still pretty naive. You can get away with one char and one int.
- Read byte from input
- Write byte to output
- When byte is "\n":
write the counter,
write a space,
increase the counter by one
Most likely, whatever logic you use to turn the counter into a string will already use more memory than your actual loop.
Technically it's still not O(1), as you will need one more bit for your counter variable every time you double the number of lines; realistically, you will most likely be using an integer anyway, so you can consider it "constant".