CP Beginners

No complex stream code. Just use the Fast Scanner.

If you are used to Java's Scanner, you don't need to learn complicated asynchronous event loop systems in JavaScript just to solve algorithmic problems. We can wrap JS reads into an easy, synchronous structure that acts exactly like what you already know.

Java Scanner Concept
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int k = sc.nextInt();
int[] arr = new int[n];
for (int i = 0; i < n; i++) {
    arr[i] = sc.nextInt();
}
JS Fast Scanner Equivalent
const n = nextInt();
const k = nextInt();
const arr = [];
for (let i = 0; i < n; i++) {
    arr.push(nextInt());
}

The Ultimate Fast Scanner Boilerplate

Copy-paste this template for any stream-based platform (Codeforces, HackerRank, AtCoder).

const fs = require("fs");

// 1. Grab all terminal input instantly
const input = fs.readFileSync(0, "utf-8").trim().split(/\s+/);
let ptr = 0; // The pointer pointing to the current token

// Equivalent to sc.next() in Java
function next() {
  return input[ptr++];
}

// Equivalent to sc.nextInt() in Java
function nextInt() {
  return Number(input[ptr++]);
}

// ==========================================
// SOLVE YOUR PROBLEM HERE
// ==========================================
function solve() {
  if (input.length === 0 || input[0] === "") return;

  const n = nextInt();
  const k = nextInt();
  
  const arr = [];
  for (let i = 0; i < n; i++) {
    arr.push(nextInt());
  }

  // Your algorithm code:
  console.log("N is:", n, "K is:", k);
  console.log("Parsed Array:", arr);
}

solve();

How does this work? (Simply Explained)

1

Grab Everything Instantly

fs.readFileSync(0) reads the entire input file/terminal feed at once, rather than reading line-by-line. This is incredibly fast.

2

Split into Simple Words

.split(/\s+/) cuts the entire input string wherever there are spaces, tabs, or newlines, producing a single, clean flat array of string elements.

3

The Sequence Pointer

We use the pointer index ptr. Every time we call nextInt(), we retrieve the value at the current index and increment the pointer by 1.

Common Problem-Solving Blueprints

Click below to see how easy it is to parse standard patterns using our Scanner.

Reading Multiple Test Cases (T)

const t = nextInt(); // 1. Read how many test cases exist

for (let tc = 0; tc < t; tc++) {
  const n = nextInt();
  const k = nextInt();
  
  const arr = [];
  for (let i = 0; i < n; i++) {
    arr.push(nextInt());
  }

  // Process testcase tc here...
}

Why is this method preferred?

When taking inputs, Node's typical asynchronous stream processing (`readline`) is slow and can trigger a Time Limit Exceeded (TLE) error on competitive programming platforms.

By loading everything instantly using direct synchronous read calls, we avoid all V8 execution micro-delays, giving you maximum performance matching Java's buffered input readers.

Execution Speed Score (Higher is Better)