Yandex Contest how to get rid of the error Memory Limit/Time Limit?

There is the following problem: yandex contest
There 2 solutions:
//Solution 1:
const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
 input: fs.createReadStream('input.txt'),
 terminal: false
});

let prev;

rl.once('line', () => {
 rl.on('line', line => {
 if (line != prev) fs.appendFileSync('output.txt', `${prev ? '\n' : "}${prev = line}`);
});
});

//Solution 2:
const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
 input: fs.createReadStream('input.txt'),
 terminal: false
});

let prev;

rl.once('line', () => {
 rl.on('line', line => {
 if (line != prev) process.stdout.write(`${prev ? '\n' : "}${prev = line}`);
});
});

Problem 1-go solutions - you have exceeded the time limit(1s), and second memory limit(20 MB). How to optimize this code?
March 19th 20 at 08:33
1 answer
March 19th 20 at 08:35
Solution
Pseudocode
opened the file
a = read a single number
until the file is over
 b = read one number
 if a < b
 brought a
 a = b
brought a
My code does the same thing, reads the file line by line and outputs either directly to the process.stdout or in output.txt. Think != it would be better as it is a string, for example '90' < '100' //false so you have to cast them to numbers(or rather one, the other, and so are coerced to number) +a < b don't think it's faster - Eliseo.Goyette67 commented on March 19th 20 at 08:38
@Eliseo.Goyette67, your first option uses blocking I / o. Try this
const sz = 100
buf = []
opened the file
a = read a single number
until the file is over
 b = read one number
 if a < b
buf.push(a)
 if (buf.lengh == sz)
 led buf
 buf = []
 a = b
buf.push(a)
led buf
- richmond.Murazik commented on March 19th 20 at 08:41
@richmond.Murazik, Thanks for the tip, helped optimize the first solution, instead of going to the output file each time, I only did it when str.length > 100, that actually sped up the decision in 2 times, here is the solution:
const fs = require('fs');
const readline = require('readline');

const rl = readline.createInterface({
 input: fs.createReadStream('input.txt'),
 terminal: false
});

let str = ", prev;

rl.once('line', () => {
 rl.on('line', line => {
 if (line != prev) str += `${prev = line}\n`;
 if (str.length > 100) {
 fs.appendFileSync('output.txt', str);
 str = ";
}
 }).on('close', () => fs.appendFileSync('output.txt', str));
});
- Eliseo.Goyette67 commented on March 19th 20 at 08:44
@Eliseo.Goyette67, the length of the buffer you can do more than 100. 150000 is about optimal. Total run time 100 I had 330мс, with a 150000 - 130мс - wava_Volkman97 commented on March 19th 20 at 08:47

Find more questions by tags Node.jsJavaScript