Data Structures & AlgorithmsVery hardGoogle · Flipkart interview
Edge case: JavaScript event-loop ordering of synchronous code, a promise callback and a timer.
Edge case: JavaScript event-loop ordering of synchronous code, a promise callback and a timer.
const out = [];
out.push("A");
setTimeout(() => { out.push("B"); console.log(out.join(" ")); }, 0);
Promise.resolve().then(() => out.push("C"));
out.push("D");What is printed?- A. A B C D
- B. A D B C
- C. A D C B
- D. A C D B
Correct answer: C. A D C B
Synchronous code runs first (A, D). Promise callbacks are microtasks, run as soon as the current script finishes (C). Timers are macrotasks, run on a later loop turn even with delay 0 (B), which then prints everything.
More Coding Interview Problems questions
- Problem: Split an array (duplicates allowed) into the most chunks such that sorting each chunk separately and concatenating gives the…
- Problem: Detect a 132 pattern (i < j < k with a[i] < a[k] < a[j]) in O(n) by scanning from the right with a stack. python def has132(a)…
- Problem: A single-threaded CPU log has entries 'id:start:t' and 'id:end:t' (an end at t covers time unit t). Functions can call each…
- Problem: Evaluate an expression with +, −, , / (integer division truncating toward zero) and no parentheses, using a stack. python def…
- Problem: Find every start index in s of a substring that is a concatenation of all the given words (each exactly once, any order; all…
- Problem: Find the shortest contiguous substring of S that contains T as a SUBSEQUENCE (leftmost on ties). Scan forward to complete T, then…