OA / Multiple choice OA MULTIPLE CHOICE · INSTANT FEEDBACK
Practise the multiple-choice part of the OA. 621 original OA-style multiple-choice questions on CS fundamentals (data structures and algorithms, OS, databases, networking, concurrency, OOP, the Linux command line, Git, computer architecture, web security, design patterns, web frontend, machine learning), code output (time complexity, Python, JavaScript, Java, C++, SQL, NumPy) and quant (probability, logic, statistics). Every “what does this print” answer (all but the big-O and undefined-behaviour questions) comes from running the code. Each question is graded the moment you submit, with an explanation, and comes back for review after 1, 3, 7 and 21 days. For scheduling, page replacement, TCP and congestion arithmetic, step through it in the OS and networking simulators .
Section All621 CS fundamentals337 Code output214 Quant & logic70 Topic All topics621 Operating systems20 Databases22 Networking21 Concurrency22 OOP16 Python26 JavaScript40 Java12 Probability24 Logic21 Data structures & algorithms86 Complexity66 Computer architecture20 C++30 Git15 Linux command line20 Design patterns15 Web security20 SQL20 Web frontend30 Statistics25 Machine learning30 NumPy code reading20 Review Every question621 Missed only0 Due today0 621 questions
Q1 Which of these do threads of the same process share?
Submit
Q2 What directly causes a page fault?
Submit
Q3 Which scheduling policy can starve long jobs?
Submit
Q4 Which is NOT a necessary condition for deadlock?
Submit
Q5 What is the typical symptom of thrashing?
Submit
Q6 A program calls fork() three times in a row without checking the return value. How many processes exist at the end, including the original?
Submit
Q7 Why is switching between threads of one process usually cheaper than switching processes?
Submit
Q8 Which kind of fragmentation does paging eliminate?
Submit
Q9 With 3 initially empty frames and the reference string 1 2 3 4 1 2 5 1 2 3 4 5, how many page faults does LRU incur?
Submit
Q10 Which page replacement policy can show Belady's anomaly (more frames, more faults)?
Submit
Q11 Which of these always needs a system call (a switch to kernel mode)?
Submit
Q12 What is a zombie process?
Submit
Q13 What does the TLB cache?
Submit
Q14 With 32-bit virtual addresses and 4 KB pages, how many bits is the page offset?
Submit
Q15 In round-robin scheduling, what does a very large time quantum degenerate into?
Submit
Q16 What does copy-on-write do for fork?
Submit
Q17 What is the main benefit of DMA?
Submit
Q18 In the many-to-one user-level thread model, what happens when one thread makes a blocking system call?
Submit
Q19 What usually crashes a very deep recursion?
Submit
Q20 What happens to a child process when its parent exits first?
Submit
Q21 What does the I in ACID stand for?
Submit
Q22 Which isolation level prevents dirty reads but still allows non-repeatable reads?
Submit
Q23 Under the SQL standard, which isolation level is guaranteed to prevent phantom reads?
Submit
Q24 What does second normal form (2NF) remove?
Submit
Q25 Employee(emp_id, dept_id, dept_name) has key emp_id, and dept_id determines dept_name. Which normal form does it violate?
Submit
Q26 Which statements about PRIMARY KEY and UNIQUE are true? (Select all that apply)
Submit
Q27 Why do databases usually prefer B+ trees over hash indexes for general-purpose indexing?
Submit
Q28 Which statement about a clustered index is true?
Submit
Q29 Table A has 5 rows. At least how many rows does SELECT * FROM A LEFT JOIN B ON ... return?
Submit
Q30 Column x holds 1, NULL, 2, NULL. What are COUNT(*) and COUNT(x)?
Submit
Q31 To keep only customers with more than 10 orders, where does the condition go?
Submit
Q32 In standard SQL, which clause can refer to an alias defined in the SELECT list?
Submit
Q33 What does SELECT * FROM t WHERE x = NULL return?
Submit
Q34 What does two-phase locking (2PL) guarantee?
Submit
Q35 What is the core rule of write-ahead logging (WAL)?
Submit
Q36 What does a FOREIGN KEY constraint enforce?
Submit
Q37 Which statement about adding an index is FALSE?
Submit
Q38 How do UNION and UNION ALL differ?
Submit
Q39 There is a composite B+ tree index on (a, b). Which predicates can use it efficiently? (Select all that apply)
Submit
Q40 By the CAP theorem, during a network partition a distributed system must choose between which two?
Submit
Q41 How does optimistic concurrency control usually detect a conflict?
Submit
Q42 What is the most reliable defence against SQL injection?
Submit
Q43 Which of these most commonly runs directly over UDP?
Submit
Q44 What is the order of segments in the TCP three-way handshake?
Submit
Q45 Which layer of the TCP/IP model does IP belong to?
Submit
Q46 A server is temporarily overloaded and wants the client to retry later. Which status code fits best?
Submit
Q47 What does ARP do?
Submit
Q48 How many usable host addresses does a /24 subnet have?
Submit
Q49 How many usable host addresses does a /26 subnet have?
Submit
Q50 Which side of a TCP connection enters TIME_WAIT after it closes?
Submit
Q51 Which port does HTTPS use by default?
Submit
Q52 At which layers do a switch and a router mainly work?
Submit
Q53 What does TCP flow control prevent?
Submit
Q54 During TCP slow start, how does the congestion window grow?
Submit
Q55 Which guarantees does TLS (HTTPS) provide? (Select all that apply)
Submit
Q56 Which HTTP methods are idempotent by the spec? (Select all that apply)
Submit
Q57 Which are private IPv4 addresses? (Select all that apply)
Submit
Q58 How long does it take to put 1 MB (10^6 bytes) onto a 100 Mbps link, ignoring propagation delay?
Submit
Q59 What is the main improvement of HTTP/2 over HTTP/1.1?
Submit
Q60 Which protocol does ping use?
Submit
Q61 What problem does NAT mainly solve?
Submit
Q62 How is a WebSocket connection established?
Submit
Q63 What is DHCP mainly for?
Submit
Q64 Two threads each run count++ 1000 times on a shared count starting at 0, with no synchronisation. What is the final value?
Submit
Q65 Thread A holds lock L1 and waits for L2; thread B holds L2 and waits for L1. What is the simplest reliable fix?
Submit
Q66 A counting semaphore initialised to 3 guards a section. At most how many threads can be inside at once?
Submit
Q67 Why should a condition-variable wait() sit inside a while loop that rechecks the condition?
Submit
Q68 What is a livelock?
Submit
Q69 In Java, count is declared volatile int and several threads run count++. What happens?
Submit
Q70 What does a read-write lock allow?
Submit
Q71 Which classic problem can a lock-free stack built on CAS run into?
Submit
Q72 When is a spinlock a better fit than a blocking mutex?
Submit
Q73 In default CPython (with the GIL), how do you usually use several cores for CPU-bound work?
Submit
Q74 What makes a lock reentrant?
Submit
Q75 A thread calls lock() twice in a row on the same non-reentrant mutex. What happens?
Submit
Q76 A bounded-buffer producer-consumer built on semaphores usually needs which semaphores?
Submit
Q77 In the dining philosophers problem, which change avoids deadlock?
Submit
Q78 A program is 90% perfectly parallelisable. By Amdahl's law, what is the best speed-up on 4 cores?
Submit
Q79 What does a single-threaded event loop (Node.js, asyncio) provide?
Submit
Q80 What is priority inversion?
Submit
Q81 In Java double-checked locking for a singleton, why must the instance field be volatile?
Submit
Q82 What does a barrier do?
Submit
Q83 What are the main benefits of a thread pool over a new thread per task? (Select all that apply)
Submit
Q84 What is the key difference between Thread.sleep() and Object.wait() in Java?
Submit
Q85 What exactly is a data race?
Submit
Q86 Which kind of polymorphism do overriding and overloading give?
Submit
Q87 Which statements about abstract classes and interfaces in Java are true? (Select all that apply)
Submit
Q88 What does the Liskov substitution principle require?
Submit
Q89 What does the O in SOLID (open/closed) mean?
Submit
Q90 What does the dependency inversion principle recommend?
Submit
Q91 Why 'favour composition over inheritance'?
Submit
Q92 In Java, a subclass declares a static method with the same signature as one in its parent. What happens?
Submit
Q93 What is the key step in implementing the Singleton pattern?
Submit
Q94 Which situation suits the Observer pattern?
Submit
Q95 Java forbids multiple inheritance of classes mainly to avoid what?
Submit
Q96 What is the Strategy pattern for?
Submit
Q97 In Java, why must you override hashCode when you override equals?
Submit
Q98 What characterises the Decorator pattern?
Submit
Q99 In Java, who can access a protected member?
Submit
Q100 What is the main purpose of encapsulation?
Submit
Q101 What problem does the Factory Method pattern solve?
Submit
Q102 What does this Python code print?def add(x, items=[]):
items.append(x)
return items
add(1)
add(2)
print(add(3))
Submit
Q103 What does this Python code print?fs = [lambda: i for i in range(3)]
print([f() for f in fs])
Submit
Q104 What does this Python code print?print(-7 // 2, -7 % 2)
Submit
Q105 What does this Python code print?a = [[0] * 2] * 2
a[0][0] = 1
print(a)A [[1, 0], [1, 0]] B [[1, 1], [1, 1]] C [[1, 0], [0, 0]] D [[1, 1], [0, 0]]
Submit
Q106 What does this Python code print?a = [1, 2]
b = a[:]
print(a == b, a is b)
Submit
Q107 What does this Python code print?s = "abcdef"
print(s[::-2])
Submit
Q108 What does this Python code print?d = {"a": 1, "b": 2}
d["a"] = 3
d["c"] = 4
print(list(d))
Submit
Q109 What does this Python code print?g = (x * x for x in range(4))
print(sum(g), sum(g))
Submit
Q110 What does this Python code print?t = ([1],)
try:
t[0] += [2]
except TypeError:
pass
print(t)
Submit
Q111 What does this Python code print?class A:
items = []
def add(self, x):
self.items.append(x)
a, b = A(), A()
a.add(1)
b.add(2)
print(a.items)
Submit
Q112 What does this Python code print?def make():
n = 0
def inc():
nonlocal n
n += 1
return n
return inc
f = make()
f()
f()
print(f())
Submit
Q113 What does this Python code print?words = ["bb", "a", "ccc", "dd"]
print(sorted(words, key=len))A ['a', 'bb', 'ccc', 'dd'] B ['a', 'dd', 'bb', 'ccc'] C ['a', 'bb', 'dd', 'ccc'] D ['ccc', 'bb', 'dd', 'a']
Submit
Q114 What does this Python code print?print(list(zip([1, 2, 3], "ab")))
Submit
Q115 What does this Python code print?print(True + True * 3)
Submit
Q116 What does this Python code print?print(1 < 3 > 2, 1 < 2 < 1)
Submit
Q117 What does this Python code print?def f():
try:
return "try"
finally:
print("finally", end=" ")
print(f())
Submit
Q118 What does this Python code print?a = {1, 2, 3}
b = {2, 3, 4}
print(sorted(a ^ b))
Submit
Q119 What does this Python code print?print("-".join("ab" * 2))
Submit
Q120 What does this Python code print?x = 10
def f():
print(x)
x = 5
try:
f()
except UnboundLocalError:
print("error")
Submit
Q121 What does this Python code print?print([x for x in range(10) if x % 3 == 0][-1])
Submit
Q122 What does this Python code print?d = {}
d.setdefault("k", []).append(1)
d.setdefault("k", []).append(2)
print(d)
Submit
Q123 What does this Python code print?import copy
a = [[1], [2]]
b = copy.copy(a)
b[0].append(9)
b.append([3])
print(len(a), a[0])
Submit
Q124 What does this Python code print?print(round(2.5), round(3.5))
Submit
Q125 What does this Python code print?print(0.1 + 0.2 == 0.3)
Submit
Q126 What does this Python code print?for i, c in enumerate("xyz", 1):
pass
print(i, c)
Submit
Q127 What does this Python code print?def f(a, *rest, b=0):
return a + sum(rest) + b
print(f(1, 2, 3, b=4))
Submit
Q128 What does this JavaScript print when run in Node.js?console.log(typeof null, typeof NaN);
Submit
Q129 What does this JavaScript print when run in Node.js?const out = [];
for (var i = 0; i < 3; i++) out.push(() => i);
console.log(out.map((f) => f()).join(" "));
Submit
Q130 What does this JavaScript print when run in Node.js?console.log(0 == "", 0 === "", null == undefined);
Submit
Q131 What does this JavaScript print when run in Node.js?console.log([10, 9, 1, 2].sort().join(","));A 1,10,2,9 B 1,2,9,10 C 10,9,2,1 D 9,10,1,2
Submit
Q132 What does this JavaScript print when run in Node.js?const log = [];
log.push("A");
setTimeout(() => {
log.push("B");
console.log(log.join(" "));
}, 0);
Promise.resolve().then(() => log.push("C"));
log.push("D");
Submit
Q133 What does this JavaScript print when run in Node.js?console.log(typeof f, typeof g);
function f() {}
var g = function () {};
Submit
Q134 What does this JavaScript print when run in Node.js?const obj = {
name: "box",
plain() {
return [1].map(function () {
return this?.name;
})[0];
},
arrow() {
return [1].map(() => this.name)[0];
},
};
console.log(obj.plain(), obj.arrow());
Submit
Q135 What does this JavaScript print when run in Node.js?function counter() {
let n = 0;
return () => ++n;
}
const a = counter();
const b = counter();
a();
a();
console.log(a(), b());
Submit
Q136 What does this JavaScript print when run in Node.js?console.log("5" + 3, "5" - 3, "5" * "2");
Submit
Q137 What does this JavaScript print when run in Node.js?const arr = [1, 2, 3];
arr[5] = 6;
console.log(arr.length, arr.filter(() => true).length);
Submit
Q138 What does this JavaScript print when run in Node.js?const o = { b: 1, 2: "x", a: 2, 1: "y" };
console.log(Object.keys(o).join(","));A b,2,a,1 B 1,2,b,a C a,b,1,2 D b,a,1,2
Submit
Q139 What does this JavaScript print when run in Node.js?const log = [];
async function f() {
log.push(1);
await null;
log.push(3);
}
f();
log.push(2);
setTimeout(() => console.log(log.join(" ")), 0);
Submit
Q140 What does this JavaScript print when run in Node.js?console.log(["1", "2", "3"].map(parseInt).join(","));
Submit
Q141 What does this JavaScript print when run in Node.js?const { a = 1, b = 2 } = { a: undefined, b: null };
console.log(a, b);
Submit
Q142 What does this JavaScript print when run in Node.js?console.log(NaN === NaN, Object.is(NaN, NaN), [NaN].includes(NaN), [NaN].indexOf(NaN));
Submit
Q143 What does this JavaScript print when run in Node.js?const out = [];
out.push(1);
setTimeout(() => out.push(2), 0);
Promise.resolve()
.then(() => out.push(3))
.then(() => out.push(4));
queueMicrotask(() => out.push(5));
out.push(6);
setTimeout(() => console.log(out.join(" ")), 10);
Submit
Q144 What does this JavaScript print when run in Node.js?const out = [];
async function a() {
out.push("a1");
await b();
out.push("a2");
}
async function b() {
out.push("b");
}
a();
Promise.resolve().then(() => out.push("p"));
out.push("s");
setTimeout(() => console.log(out.join(" ")), 0);
Submit
Q145 What does this JavaScript print when run in Node.js?const out = [];
new Promise((resolve) => {
out.push(1);
resolve();
out.push(2);
}).then(() => out.push(3));
out.push(4);
setTimeout(() => console.log(out.join(" ")), 0);
Submit
Q146 What does this JavaScript print when run in Node.js?const out = [];
setTimeout(() => {
out.push("t1");
Promise.resolve().then(() => out.push("m"));
}, 0);
setTimeout(() => out.push("t2"), 0);
setTimeout(() => console.log(out.join(" ")), 5);
Submit
Q147 What does this JavaScript print when run in Node.js?const out = [];
[1, 2, 3].forEach(async (n) => {
await null;
out.push(n);
});
out.push("done");
setTimeout(() => console.log(out.join(" ")), 0);
Submit
Q148 What does this JavaScript print when run in Node.js?Promise.resolve(1)
.then((x) => {
throw new Error("x" + x);
})
.then(() => console.log("skipped"))
.catch((e) => e.message)
.then((v) => console.log(v, "after"));
Submit
Q149 What does this JavaScript print when run in Node.js?var x = 1;
function f() {
console.log(x);
var x = 2;
}
f();
Submit
Q150 What does this JavaScript print when run in Node.js?let x = 1;
function f() {
try {
console.log(x);
} catch (e) {
console.log(e.name);
}
let x = 2;
}
f();
Submit
Q151 What does this JavaScript print when run in Node.js?const out = [typeof notDeclared];
try {
out.push(typeof later);
} catch (e) {
out.push(e.name);
}
let later = 1;
console.log(out.join(" "));
Submit
Q152 What does this JavaScript print when run in Node.js?const before = typeof foo;
var foo = 1;
function foo() {}
console.log(before, typeof foo);
Submit
Q153 What does this JavaScript print when run in Node.js?try {
new Dog();
} catch (e) {
console.log(e.name);
}
class Dog {}
Submit
Q154 What does this JavaScript print when run in Node.js?const fs = [];
for (let i = 0; i < 3; i++) fs.push(() => i);
let j = 0;
const gs = [];
for (; j < 3; j++) gs.push(() => j);
console.log(fs.map((f) => f()).join(""), gs.map((g) => g()).join(""));
Submit
Q155 What does this JavaScript print when run in Node.js?let msg = "hi";
const say = () => msg;
msg = "bye";
console.log(say());
Submit
Q156 What does this JavaScript print when run in Node.js?const out = [];
for (var i = 0; i < 3; i++) {
((j) => setTimeout(() => out.push(j), 0))(i);
}
setTimeout(() => console.log(out.join(","), i), 0);
Submit
Q157 What does this JavaScript print when run in Node.js?function once(fn) {
let done = false;
let result;
return (...args) => {
if (!done) {
done = true;
result = fn(...args);
}
return result;
};
}
const init = once((x) => x * 2);
console.log(init(5), init(10));
Submit
Q158 What does this JavaScript print when run in Node.js?const out = [];
class Counter {
constructor() {
this.n = 0;
}
inc() {
return ++this.n;
}
}
const c = new Counter();
const inc = c.inc;
try {
inc();
} catch (e) {
out.push(e.name);
}
out.push(c.inc());
console.log(out.join(" "));
Submit
Q159 What does this JavaScript print when run in Node.js?function who() {
return this.name;
}
const a = { name: "a", who };
const b = { name: "b" };
const bound = who.bind(b);
a.bound = bound;
console.log(a.who(), bound(), a.bound(), bound.call(a));
Submit
Q160 What does this JavaScript print when run in Node.js?function Person(name) {
this.name = name;
}
const p = new Person("Ann");
const q = Person.call({}, "Bo");
console.log(p.name, q);
Submit
Q161 What does this JavaScript print when run in Node.js?const out = [];
const timer = {
label: "T",
start() {
setTimeout(function () {
out.push(this === timer);
}, 0);
setTimeout(() => out.push(this.label), 0);
},
};
timer.start();
setTimeout(() => console.log(out.join(" ")), 5);
Submit
Q162 What does this JavaScript print when run in Node.js?const ctx = { id: 1 };
const fn = function () {
return this;
};
const arrow = () => this;
console.log(fn.call(ctx) === ctx, arrow.call(ctx) === ctx);
Submit
Q163 What does this JavaScript print when run in Node.js?console.log(JSON.stringify([] + []), [] + {}, [1, 2] + [3]);
Submit
Q164 What does this JavaScript print when run in Node.js?console.log([] == false, [0] == false, "0" == false, null == false);
Submit
Q165 What does this JavaScript print when run in Node.js?console.log(Number(""), Number(" 12 "), Number("1e3"), parseInt("12px"), Number("12px"));
Submit
Q166 What does this JavaScript print when run in Node.js?console.log(Boolean("0"), Boolean(""), !!NaN, !![], !!{});
Submit
Q167 What does this JavaScript print when run in Node.js?console.log(true + 1, null + 1, undefined + 1, "3" * "4", [2] * [3]);
Submit
Q168 What does this Java program print?public class Main {
public static void main(String[] args) {
String a = "hi";
String b = new String("hi");
System.out.println((a == b) + " " + a.equals(b));
}
}
Submit
Q169 What does this Java program print?public class Main {
public static void main(String[] args) {
Integer x = 127, y = 127, p = 128, q = 128;
System.out.println((x == y) + " " + (p == q));
}
}
Submit
Q170 What does this Java program print?public class Main {
public static void main(String[] args) {
System.out.println(('a' + 1) + " " + (char) ('a' + 1));
}
}
Submit
Q171 What does this Java program print?public class Main {
static void f(Object o) { System.out.println("Object"); }
static void f(String s) { System.out.println("String"); }
public static void main(String[] args) {
f(null);
}
}
Submit
Q172 What does this Java program print?class A {
String name = "A";
String who() { return "A"; }
}
class B extends A {
String name = "B";
String who() { return "B"; }
}
public class Main {
public static void main(String[] args) {
A obj = new B();
System.out.println(obj.name + " " + obj.who());
}
}
Submit
Q173 What does this Java program print?public class Main {
static void change(int[] arr, int n) {
arr[0] = 9;
n = 9;
arr = new int[] {7};
}
public static void main(String[] args) {
int[] a = {1};
int n = 1;
change(a, n);
System.out.println(a[0] + " " + n);
}
}
Submit
Q174 What does this Java program print?public class Main {
public static void main(String[] args) {
int big = Integer.MAX_VALUE;
System.out.println(big + 1);
}
}
Submit
Q175 What does this Java program print?public class Main {
static int f() {
try {
return 1;
} finally {
return 2;
}
}
public static void main(String[] args) {
System.out.println(f());
}
}
Submit
Q176 What does this Java program print?public class Main {
public static void main(String[] args) {
String s = "abc";
s.toUpperCase();
System.out.println(s + " " + s.concat("d"));
}
}
Submit
Q177 What does this Java program print?class C {
static int count = 0;
C() { count++; }
}
public class Main {
public static void main(String[] args) {
new C();
new C();
C c = new C();
System.out.println(C.count);
}
}
Submit
Q178 What does this Java program print?import java.util.HashSet;
import java.util.Set;
class P {
int x;
P(int x) { this.x = x; }
}
public class Main {
public static void main(String[] args) {
Set<P> s = new HashSet<>();
s.add(new P(1));
s.add(new P(1));
System.out.println(s.size());
}
}
Submit
Q179 What does this Java program print?public class Main {
public static void main(String[] args) {
Object o = true ? 1 : 2.0;
System.out.println(o);
}
}
Submit
Q180 Two fair dice are rolled. What is the probability that the sum is 7?
Submit
Q181 Two fair dice are rolled. What is the probability of at least one six?
Submit
Q182 A fair coin is tossed 3 times. What is the probability of exactly 2 heads?
Submit
Q183 Two cards are drawn without replacement from a standard 52-card deck. What is the probability both are aces?
Submit
Q184 A fair coin is tossed until the first head. What is the expected number of tosses?
Submit
Q185 How many people are needed for the chance that two share a birthday to exceed 50% (365 equally likely days)?
Submit
Q186 A disease affects 1% of people. A test is positive for 99% of the sick and for 5% of the healthy. Given a positive test, what is the chance the person is sick?
Submit
Q187 Monty Hall: you pick a door, and the host, who knows, opens another empty door. If you switch, what is your chance of winning?
Submit
Q188 A fair die is rolled until a six appears. What is the expected number of rolls?
Submit
Q189 How many rolls of a fair die are expected before every face has appeared at least once?
Submit
Q190 A family has two children and at least one is a boy. What is the probability both are boys? (Independent, half boys and half girls)
Submit
Q191 A random permutation of 1..n is chosen. What is the expected number of fixed points?
Submit
Q192 A bag holds 3 red and 5 blue balls. Two are drawn without replacement. What is the probability both are red?
Submit
Q193 Two fair dice are rolled. What is the expected sum?
Submit
Q194 P(A) = 0.5, P(B) = 0.4 and P(A∩B) = 0.2. What is P(A∪B)?
Submit
Q195 A fair coin is tossed 10 times. What is the variance of the number of heads?
Submit
Q196 Two fair dice are rolled. What is the expected value of the larger number, roughly?
Submit
Q197 A stick is broken at two uniformly random points. What is the probability the three pieces form a triangle?
Submit
Q198 A fair game: you start with $1 and each round win or lose $1 with probability 1/2, stopping at $3 or $0. What is the chance you reach $3?
Submit
Q199 Two different numbers are chosen at random from 1 to 10. What is the probability their sum is even?
Submit
Q200 How many distinct arrangements are there of the letters of LEVEL?
Submit
Q201 A fair coin is tossed until two heads in a row appear. What is the expected number of tosses?
Submit
Q202 Independent events A and B have P(A) = 0.3 and P(B) = 0.5. What is the probability that neither happens?
Submit
Q203 A fair coin is tossed 4 times. What is the probability of more heads than tails?
Submit
Q204 What comes next: 2, 6, 12, 20, 30, ?
Submit
Q205 What is the angle between the hour and minute hands at 3:15?
Submit
Q206 'All bloops are razzies and all razzies are lazzies.' What follows for certain?
Submit
Q207 'If it rains, the ground gets wet.' Which statement is logically equivalent?
Submit
Q208 Each islander is a knight (always truthful) or a knave (always lies). A says: 'We are both knaves.' What are A and B?
Submit
Q209 Of 12 balls one is heavier. What is the minimum number of weighings on a balance that always finds it?
Submit
Q210 A finishes a job alone in 6 hours, B in 3. How long do they take together?
Submit
Q211 Two trains 300 km apart head toward each other at 60 km/h and 90 km/h. When do they meet?
Submit
Q212 A bat and a ball cost $1.10 in total, and the bat costs $1 more than the ball. How much is the ball?
Submit
Q213 A lily patch doubles every day and covers the lake on day 48. On which day did it cover half?
Submit
Q214 5 machines make 5 widgets in 5 minutes. How long do 100 machines take to make 100 widgets?
Submit
Q215 NOT (A AND B) is equivalent to which expression?
Submit
Q216 A drawer has 10 black and 10 white socks. In the dark, how many must you take to be sure of a matching pair?
Submit
Q217 Ten people each shake hands with every other person once. How many handshakes?
Submit
Q218 Which is the odd one out: 2, 3, 5, 9, 11?
Submit
Q219 A father is 4 times his son's age now and will be twice the son's age in 20 years. How old is the son now?
Submit
Q220 How many trailing zeros does 100! have?
Submit
Q221 How many squares of all sizes are there on an 8×8 chessboard?
Submit
Q222 Today is Wednesday. What day is it 100 days from now?
Submit
Q223 What comes next: 1, 4, 9, 16, 25, ?
Submit
Q224 In a class of 30, 21 know Python and 17 know Java, and everyone knows at least one. How many know both?
Submit
Q225 Inserting one element at index 0 of a dynamic array (such as a Python list) holding n elements costs?
Submit
Q226 Why does a dynamic array grow by a constant factor (say, doubling its capacity) instead of by a fixed amount (say, 100 more slots)?
Submit
Q227 A chained hash table holds n keys in m buckets, load factor α = n/m. With keys spread uniformly, what is the expected cost of an unsuccessful lookup?
Submit
Q228 Which statements about hash tables are true? Select all that apply.
Submit
Q229 When building a long string in Python, why collect the pieces in a list and call "".join(parts) instead of doing s += part in a loop?
Submit
Q230 Two lowercase strings of length n are checked for being anagrams with a 26-slot count array. Time and extra space?
Submit
Q231 The opposite-ends two-pointer search for a pair summing to target (move left up when the sum is too small, right down when too big) is correct only when:
Submit
Q232 For "longest subarray with sum at most K", the usual sliding window grows the right end one step at a time and shrinks the left end while the sum exceeds K. What does it rely on?
Submit
Q233 Prefix sums are P[0] = 0 and P[i] = a[0] + … + a[i-1]. The sum of a[l..r], both ends included, is:
Submit
Q234 What is the standard way to merge a list of possibly overlapping intervals, and its time?
Submit
Q235 An array of length n gets q updates "add v to every element of a[l..r]" and is read once at the end. With a difference array, the total time is:
Submit
Q236 lo, hi = 0, len(a); while lo < hi: mid = (lo + hi) // 2; if a[mid] < x then lo = mid + 1 else hi = mid. On a sorted array a, what is lo when the loop ends?
Submit
Q237 Binary search on the answer (bisect a range of candidate answers, testing each with check(mid)) requires:
Submit
Q238 In Java or C++, why write mid = lo + (hi - lo) / 2 instead of mid = (lo + hi) / 2?
Submit
Q239 Building a binary heap from n unordered elements bottom-up (sift down from the last internal node back to the root) takes:
Submit
Q240 To keep the k largest numbers of a stream with a heap, the standard approach is:
Submit
Q241 Which of these is the classic use of a monotonic stack?
Submit
Q242 To pick the most pairwise non-overlapping intervals, the right greedy choice each step is the interval that:
Submit
Q243 With coins {1, 3, 4} and amount 6, how many coins does "always take the largest coin that fits" use, and what is the minimum?
Submit
Q244 After Floyd's tortoise and hare (slow moves 1, fast moves 2) meet inside a cycle, how do you find the node where the cycle starts?
Submit
Q245 A singly linked list keeps both head and tail pointers. Which operation is not O(1)?
Submit
Q246 Linked-list solutions often put a dummy node before the head. What is it for?
Submit
Q247 Recursive DFS on a binary tree with n nodes and height h uses how much extra (call stack) space?
Submit
Q248 A full binary tree (every node has 0 or 2 children) has n internal nodes. How many leaves does it have?
Submit
Q249 To compute every subtree's height bottom-up, a node must come after both of its subtrees. Which DFS order is that?
Submit
Q250 Maximum path sum between any two nodes of a binary tree: what should the recursive helper return to its parent? (L and R are what the children returned.)
Submit
Q251 Counting downward paths that sum to target, DFS keeps a hash map of prefix-sum counts along the root-to-node path. Why decrement the current prefix sum when leaving a node?
Submit
Q252 With distinct values, which traversal pairs determine a binary tree uniquely? Select all that apply.
Submit
Q253 Rebuilding a tree from preorder and inorder, what does a hash map from value to inorder index change?
Submit
Q254 Why is checking left child < node < right child at every node not enough to validate a binary search tree?
Submit
Q255 Inserting 1, 2, …, n in order into a plain (unbalanced) binary search tree gives what height, in edges?
Submit
Q256 How do you delete a node with two children from a BST?
Submit
Q257 Which search gives the fewest moves from start to target on an unweighted grid directly?
Submit
Q258 Why does BFS usually mark a cell visited when it is enqueued rather than when it is dequeued?
Submit
Q259 An R×C grid has k sources; every cell needs its distance to the nearest source. The efficient way is:
Submit
Q260 With both path compression and union by rank (or size), what is the amortized time per union-find operation?
Submit
Q261 Detecting a cycle in an undirected graph with union-find, edge by edge: when does edge (u, v) close a cycle?
Submit
Q262 After m edges on n vertices, union-find made s successful unions (the ends were in different sets). How many connected components are there?
Submit
Q263 Kahn's algorithm (repeatedly removing in-degree-0 vertices) outputs fewer than n vertices. What does that mean?
Submit
Q264 DFS-based topological sort outputs which order?
Submit
Q265 A directed graph has negative edges but no negative cycle. Which algorithm finds single-source shortest paths?
Submit
Q266 In 0-1 BFS (edge weights 0 or 1, using a deque), where do newly reached vertices go?
Submit
Q267 Kruskal's algorithm takes edges from lightest to heaviest. When does it skip an edge?
Submit
Q268 For a connected weighted undirected graph with V vertices, which are true? Select all that apply.
Submit
Q269 Backtracking generates every subset of n distinct items, copying each one out as a list. Total time?
Submit
Q270 To list unique permutations of [1, 1, 2]: sort, then at each position skip nums[i] when nums[i] == nums[i-1] and nums[i-1] is not in use. What does this rule guarantee?
Submit
Q271 When backtracking over all valid strings of n parenthesis pairs, when may you append ")"?
Submit
Q272 How many balanced strings can 3 pairs of parentheses form?
Submit
Q273 In N-Queens, queens at (r1, c1) and (r2, c2) share a diagonal exactly when:
Submit
Q274 In Combination Sum with positive candidates sorted ascending, why may the loop break (not just skip) once candidates[i] exceeds the remaining target?
Submit
Q275 Which two properties make a problem a good fit for dynamic programming?
Submit
Q276 Which are true of top-down memoization and bottom-up tabulation? Select all that apply.
Submit
Q277 On a 3×3 grid of cells, moving only right or down, how many paths lead from the top-left cell to the bottom-right cell?
Submit
Q278 A grid DP squeezed into one row runs dp[j] = dp[j] + dp[j-1] for j from left to right. Before the assignment, what do dp[j] and dp[j-1] hold?
Submit
Q279 In one-row 0/1 knapsack, for w in range(W, wt - 1, -1): dp[w] = max(dp[w], dp[w - wt] + val). Why go from high capacity to low?
Submit
Q280 Why is the O(n·W) 0/1 knapsack DP called pseudo-polynomial?
Submit
Q281 coins = [1, 2], amount 3. Run ways = [1, 0, 0, 0]; for c in coins: for a in range(c, 4): ways[a] += ways[a - c]. What is ways[3]?
Submit
Q282 The O(n log n) longest increasing subsequence method keeps an array tails. What is tails[k]?
Submit
Q283 What is the length of the longest strictly increasing subsequence of [8, 3, 6, 1, 7, 4, 9, 2]?
Submit
Q284 What is the edit distance (insert, delete, replace each cost 1) from "abc" to "yabd"?
Submit
Q285 LCS length of strings of lengths m and n uses O(m·n) memory as a full table. If only the length is needed, how low can the memory go?
Submit
Q286 Expand-around-center for palindromic substrings: how many centers does a string of length n have?
Submit
Q287 Longest palindromic subsequence: dp[i][j] needs dp[i+1][j-1], dp[i+1][j] and dp[i][j-1]. Which fill order works?
Submit
Q288 House Robber on a circle (first and last houses are neighbours) is usually solved how?
Submit
Q289 Stock trading with a one-day cooldown uses states hold, sold (sold today) and rest (not holding, no cooldown). Buying today comes from which state yesterday?
Submit
Q290 Prices are [6, 2, 9, 1, 4, 8]. Any number of trades is allowed, holding at most one share at a time. What is the maximum profit?
Submit
Q291 Stock trading with at most k transactions over n days: what can you do when k >= n / 2?
Submit
Q292 Weighted interval scheduling: with intervals sorted by end time, dp[i] = max(dp[i-1], w[i] + dp[p(i)]). What is p(i), and the total time?
Submit
Q293 Given meeting times, what is the minimum number of rooms?
Submit
Q294 Two players alternately take a number from either end of an array, both optimally. The DP is dp[i][j] = max(a[i] - dp[i+1][j], a[j] - dp[i][j-1]). What is dp[i][j]?
Submit
Q295 Longest increasing path in a matrix by memoized DFS: why is no visited set needed against walking in circles?
Submit
Q296 A stack with push, pop, top and O(1) getMin is usually built how?
Submit
Q297 Why use collections.deque instead of a list with pop(0) for a BFS queue in Python?
Submit
Q298 What gives an LRU cache O(1) get and put?
Submit
Q299 Why does an LRU cache use a doubly linked list rather than a singly linked one?
Submit
Q300 A trie holds N words. Checking whether a word of length L is present takes:
Submit
Q301 Why does preorder with explicit null markers (such as #) let a binary tree be rebuilt, while plain preorder does not?
Submit
Q302 For a positive integer x, what does x & (x - 1) == 0 mean?
Submit
Q303 What is the bitwise XOR of all of [7, 3, 5, 3, 7]?
Submit
Q304 In two's complement, what does x & -x give? Take x = 12.
Submit
Q305 "Can you reach the last index?" (a[i] is the longest jump from i): a greedy left-to-right scan keeps far, the farthest index reachable so far. When is the answer no?
Submit
Q306 When backtracking over every palindrome partition of s (length n), what does precomputing a table pal[i][j] (is s[i..j] a palindrome) change?
Submit
Q307 Searching a grid for a word by backtracking, why mark the current cell as in use before recursing and restore it afterwards?
Submit
Q308 Building a height-balanced BST from n distinct sorted values (recursing on index ranges, no slicing): which element of each range becomes the root, and what is the total time?
Submit
Q309 Does the diameter of a binary tree (the most edges on a path between any two nodes) always pass through the root?
Submit
Q310 Stock trading with a fee: each day hold = max(hold, cash - p); cash = max(cash, hold + p - fee), where the second line sees the updated hold. Why is updating in place safe?
Submit
Q311 What is the time complexity of this code (n = len(a), tightest bound)?def reverse_copy(a):
out = []
for x in a:
out.insert(0, x)
return out
Submit
Q312 What is the time complexity of this code (tightest bound)?def build(n):
a = []
for i in range(n):
a.append(i)
return a
Submit
Q313 What is the time complexity of this code (n = len(a), tightest bound)?def normalize(a):
return [x / max(a) for x in a]
Submit
Q314 What is the worst-case time complexity (n = len(a))?def count_repeats(a):
seen = []
repeats = 0
for x in a:
if x in seen:
repeats += 1
else:
seen.append(x)
return repeats
Submit
Q315 What is the time complexity of this code (n = len(a), tightest bound)?def has_pair(a, target):
seen = set()
for x in a:
if target - x in seen:
return True
seen.add(x)
return False
Submit
Q316 What is the time complexity of this code (n = len(a), tightest bound)?def most_common(a):
best = None
for x in a:
if best is None or a.count(x) > a.count(best):
best = x
return best
Submit
Q317 words has n entries and vocab is a dict with m keys. What is the time complexity?def count_known(words, vocab):
known = 0
for w in words:
if w in list(vocab):
known += 1
return known
Submit
Q318 What is the time complexity when s is a palindrome (n = len(s))?def is_pal(s):
if len(s) <= 1:
return True
return s[0] == s[-1] and is_pal(s[1:-1])
Submit
Q319 What is the time complexity of this Java method?static String repeatX(int n) {
String s = "";
for (int i = 0; i < n; i++) {
s += "x";
}
return s;
}
Submit
Q320 a holds non-negative integers and k >= 0. What is the time complexity (n = len(a))?def longest(a, k):
best = lo = total = 0
for hi in range(len(a)):
total += a[hi]
while total > k:
total -= a[lo]
lo += 1
best = max(best, hi - lo + 1)
return best
Submit
Q321 What is the time complexity of this code (n = len(a), tightest bound)?def count_pairs(a, t):
a.sort()
i, j, count = 0, len(a) - 1, 0
while i < j:
if a[i] + a[j] <= t:
count += j - i
i += 1
else:
j -= 1
return count
Submit
Q322 a has length n and queries holds q (l, r) ranges. What is the time complexity?def range_sums(a, queries):
p = [0]
for x in a:
p.append(p[-1] + x)
return [p[r + 1] - p[l] for l, r in queries]
Submit
Q323 a has length n and queries holds q (l, r) ranges. What is the worst-case time complexity?def range_sums(a, queries):
return [sum(a[l:r + 1]) for l, r in queries]
Submit
Q324 Initially hi - lo = n, and each call to ok costs O(m). What is the time complexity?def first_true(lo, hi, ok):
while lo < hi:
mid = (lo + hi) // 2
if ok(mid):
hi = mid
else:
lo = mid + 1
return lo
Submit
Q325 a is sorted. What is the worst-case time complexity (n = len(a))?def contains(a, x):
if not a:
return False
mid = len(a) // 2
if a[mid] == x:
return True
if a[mid] < x:
return contains(a[mid + 1:], x)
return contains(a[:mid], x)
Submit
Q326 What is the worst-case time complexity (n = len(a))?from bisect import insort
def sorted_stream(a):
out = []
for x in a:
insort(out, x)
return out
Submit
Q327 What is the time complexity of this code (n = len(a), tightest bound)?def next_greater(a):
res = [-1] * len(a)
stack = []
for i, x in enumerate(a):
while stack and a[stack[-1]] < x:
res[stack.pop()] = x
stack.append(i)
return res
Submit
Q328 What is the worst-case time complexity (n = len(a))?import heapq
def build(a):
h = []
for x in a:
heapq.heappush(h, x)
return h
Submit
Q329 1 <= k <= n. What is the time complexity (n = len(a))?import heapq
def top_k(a, k):
h = []
for x in a:
heapq.heappush(h, x)
if len(h) > k:
heapq.heappop(h)
return sorted(h, reverse=True)
Submit
Q330 tasks has n elements. What is the time complexity?def drain(tasks):
q = list(tasks)
done = 0
while q:
q.pop(0)
done += 1
return done
Submit
Q331 What is the time complexity of this code (n = len(a), tightest bound)?def running_medians(a):
out = []
for i in range(1, len(a) + 1):
s = sorted(a[:i])
out.append(s[(i - 1) // 2])
return out
Submit
Q332 The list has n nodes. What is the time complexity of suffix_lengths?def length(node):
n = 0
while node:
n += 1
node = node.next
return n
def suffix_lengths(head):
out = []
while head:
out.append(length(head))
head = head.next
return out
Submit
Q333 The tree has n nodes and height h. What are the time and extra space?def height(node):
if not node:
return 0
return 1 + max(height(node.left), height(node.right))
Submit
Q334 balanced(root) runs on a perfectly balanced binary tree with n nodes. What is the time complexity?def height(node):
if not node:
return 0
return 1 + max(height(node.left), height(node.right))
def balanced(node):
if not node:
return True
if abs(height(node.left) - height(node.right)) > 1:
return False
return balanced(node.left) and balanced(node.right)
Submit
Q335 This is a plain, unbalanced binary search tree. What is the total time of the loop?def insert(node, key):
if not node:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
else:
node.right = insert(node.right, key)
return node
root = None
for k in range(n):
root = insert(root, k)
Submit
Q336 next() is called n times to walk a BST with n nodes and height h in order. What does each next() cost?class InorderIter:
def __init__(self, root):
self.stack = []
self._push_left(root)
def _push_left(self, node):
while node:
self.stack.append(node)
node = node.left
def next(self):
node = self.stack.pop()
self._push_left(node.right)
return node.key
Submit
Q337 The grid has R rows and C columns. What is the time complexity?from collections import deque
def steps(grid, start):
R, C = len(grid), len(grid[0])
dist = {start: 0}
q = deque([start])
while q:
r, c = q.popleft()
for nr, nc in ((r + 1, c), (r - 1, c), (r, c + 1), (r, c - 1)):
if 0 <= nr < R and 0 <= nc < C and grid[nr][nc] == '.' and (nr, nc) not in dist:
dist[(nr, nc)] = dist[(r, c)] + 1
q.append((nr, nc))
return dist
Submit
Q338 m find or union calls on n elements (m >= n). What is the total time?def find(p, x):
while p[x] != x:
p[x] = p[p[x]]
x = p[x]
return x
def union(p, size, a, b):
a, b = find(p, a), find(p, b)
if a == b:
return False
if size[a] < size[b]:
a, b = b, a
p[b] = a
size[a] += size[b]
return True
Submit
Q339 m find or union calls on n elements. What is the worst-case total time?def find(p, x):
while p[x] != x:
x = p[x]
return x
def union(p, a, b):
p[find(p, a)] = find(p, b)
Submit
Q340 The graph has V = n vertices and E edges, stored as an n×n adjacency matrix. What is the time complexity?def components(n, matrix):
seen = [False] * n
def dfs(u):
seen[u] = True
for v in range(n):
if matrix[u][v] and not seen[v]:
dfs(v)
count = 0
for u in range(n):
if not seen[u]:
count += 1
dfs(u)
return count
Submit
Q341 V = n vertices and E = len(edges) edges. What is the time complexity?from collections import deque
def topo(n, edges):
adj = [[] for _ in range(n)]
indeg = [0] * n
for u, v in edges:
adj[u].append(v)
indeg[v] += 1
q = deque(i for i in range(n) if indeg[i] == 0)
order = []
while q:
u = q.popleft()
order.append(u)
for v in adj[u]:
indeg[v] -= 1
if indeg[v] == 0:
q.append(v)
return order
Submit
Q342 The graph has V vertices, E edges and non-negative weights. What is the time complexity?import heapq
def dijkstra(adj, s):
dist = {s: 0}
pq = [(0, s)]
while pq:
d, u = heapq.heappop(pq)
if d > dist[u]:
continue
for v, w in adj[u]:
if d + w < dist.get(v, float('inf')):
dist[v] = d + w
heapq.heappush(pq, (d + w, v))
return dist
Submit
Q343 V = n vertices and E = len(edges) edges. What is the time complexity?def bellman_ford(n, edges, s):
dist = [float('inf')] * n
dist[s] = 0
for _ in range(n - 1):
for u, v, w in edges:
if dist[u] + w < dist[v]:
dist[v] = dist[u] + w
return dist
Submit
Q344 d is a V×V distance matrix. What is the time complexity?def all_pairs(d):
n = len(d)
for k in range(n):
for i in range(n):
for j in range(n):
if d[i][k] + d[k][j] < d[i][j]:
d[i][j] = d[i][k] + d[k][j]
return d
Submit
Q345 V = n vertices, E = len(edges) edges, connected. What is the time complexity?def kruskal(n, edges):
p = list(range(n))
def find(x):
while p[x] != x:
p[x] = p[p[x]]
x = p[x]
return x
total = 0
for w, u, v in sorted(edges):
ru, rv = find(u), find(v)
if ru != rv:
p[ru] = rv
total += w
return total
Submit
Q346 What is the time complexity of this code (n = len(a), tightest bound)?def subsets(a):
out = []
def go(i, cur):
if i == len(a):
out.append(cur[:])
return
go(i + 1, cur)
cur.append(a[i])
go(i + 1, cur)
cur.pop()
go(0, [])
return out
Submit
Q347 What is the time complexity of this code (n = len(a), tightest bound)?def perms(a):
out = []
used = [False] * len(a)
def go(cur):
if len(cur) == len(a):
out.append(cur[:])
return
for i in range(len(a)):
if not used[i]:
used[i] = True
cur.append(a[i])
go(cur)
cur.pop()
used[i] = False
go([])
return out
Submit
Q348 What is the time complexity of this code?def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
Submit
Q349 What is the time of the first call fib(n) (treating integer addition as O(1))?from functools import lru_cache
@lru_cache(maxsize=None)
def fib(n):
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
Submit
Q350 The grid g has m rows and n columns. What are the time and extra space?def min_path(g):
m, n = len(g), len(g[0])
dp = [float('inf')] * n
dp[0] = 0
for i in range(m):
for j in range(n):
left = dp[j - 1] if j else float('inf')
dp[j] = g[i][j] + min(dp[j], left)
return dp[-1]
Submit
Q351 items has n items and the capacity is W. What is the time complexity?def knapsack(items, W):
dp = [0] * (W + 1)
for wt, val in items:
for w in range(W, wt - 1, -1):
dp[w] = max(dp[w], dp[w - wt] + val)
return dp[W]
Submit
Q352 What is the time complexity of this code (n = len(a), tightest bound)?from bisect import bisect_left
def lis(a):
tails = []
for x in a:
i = bisect_left(tails, x)
if i == len(tails):
tails.append(x)
else:
tails[i] = x
return len(tails)
Submit
Q353 m = len(a), n = len(b). What are the time and extra space?def lcs(a, b):
m, n = len(a), len(b)
dp = [[0] * (n + 1) for _ in range(m + 1)]
for i in range(m):
for j in range(n):
if a[i] == b[j]:
dp[i + 1][j + 1] = dp[i][j] + 1
else:
dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j])
return dp[m][n]
Submit
Q354 n = len(s); treat integer addition as O(1). What is the time complexity?from functools import lru_cache
def count_decodings(s):
@lru_cache(maxsize=None)
def go(t):
if not t:
return 1
ways = go(t[1:]) if t[0] != '0' else 0
if len(t) >= 2 and '10' <= t[:2] <= '26':
ways += go(t[2:])
return ways
return go(s)
Submit
Q355 n = len(s). What are the worst-case time and extra space?def count_pal(s):
n, total = len(s), 0
for c in range(2 * n - 1):
lo, hi = c // 2, c // 2 + c % 2
while lo >= 0 and hi < n and s[lo] == s[hi]:
total += 1
lo -= 1
hi += 1
return total
Submit
Q356 n = len(s). What is the time complexity?def count_pal(s):
n = len(s)
return sum(s[i:j] == s[i:j][::-1]
for i in range(n) for j in range(i + 1, n + 1))
Submit
Q357 n = len(prices), at most k transactions. What are the time and extra space?def max_profit(k, prices):
buy = [float('-inf')] * (k + 1)
sell = [0] * (k + 1)
for p in prices:
for t in range(1, k + 1):
buy[t] = max(buy[t], sell[t - 1] - p)
sell[t] = max(sell[t], buy[t] + p)
return sell[k]
Submit
Q358 jobs holds n (start, end, weight) triples. What is the time complexity?from bisect import bisect_right
def best(jobs):
jobs.sort(key=lambda j: j[1])
ends = [e for _, e, _ in jobs]
dp = [0] * (len(jobs) + 1)
for i, (s, e, w) in enumerate(jobs):
k = bisect_right(ends, s, 0, i)
dp[i + 1] = max(dp[i], dp[k] + w)
return dp[-1]
Submit
Q359 What is the time complexity of this code (n = len(a), tightest bound)?from functools import lru_cache
def first_player_margin(a):
@lru_cache(maxsize=None)
def go(i, j):
if i > j:
return 0
return max(a[i] - go(i + 1, j), a[j] - go(i, j - 1))
return go(0, len(a) - 1)
Submit
Q360 Starting empty, any n push and pop calls run. What does each operation cost?class Queue:
def __init__(self):
self.inbox, self.outbox = [], []
def push(self, x):
self.inbox.append(x)
def pop(self):
if not self.outbox:
while self.inbox:
self.outbox.append(self.inbox.pop())
return self.outbox.pop()
Submit
Q361 What does each get and put cost?from collections import OrderedDict
class LRU:
def __init__(self, cap):
self.cap, self.d = cap, OrderedDict()
def get(self, key):
if key not in self.d:
return -1
self.d.move_to_end(key)
return self.d[key]
def put(self, key, value):
self.d[key] = value
self.d.move_to_end(key)
if len(self.d) > self.cap:
self.d.popitem(last=False)
Submit
Q362 With cap keys in the cache, what does a get that hits cost?class LRU:
def __init__(self, cap):
self.cap, self.d, self.order = cap, {}, []
def get(self, key):
if key not in self.d:
return -1
self.order.remove(key)
self.order.append(key)
return self.d[key]
Submit
Q363 Building a trie from a list of words takes what time?def build(words):
root = {}
for w in words:
node = root
for ch in w:
node = node.setdefault(ch, {})
node['$'] = True
return root
Submit
Q364 x is a non-negative integer. How many times does the loop run?def ones(x):
count = 0
while x:
x &= x - 1
count += 1
return count
Submit
Q365 a and b are positive; treat one modulo as O(1). What is the time complexity?def gcd(a, b):
while b:
a, b = b, a % b
return a
Submit
Q366 n >= 1. What is the time complexity (tightest bound)?def primes(n):
is_p = [True] * (n + 1)
is_p[0] = is_p[1] = False
i = 2
while i * i <= n:
if is_p[i]:
for j in range(i * i, n + 1, i):
is_p[j] = False
i += 1
return [k for k in range(n + 1) if is_p[k]]
Submit
Q367 bits is a binary counter, lowest bit first, starting at all zeros; increment is called n times (enough bits). What is the total time?def increment(bits):
i = 0
while i < len(bits) and bits[i] == 1:
bits[i] = 0
i += 1
if i < len(bits):
bits[i] = 1
Submit
Q368 What is the worst-case time complexity (treating one modulo as O(1))?def is_prime(n):
if n < 2:
return False
d = 2
while d * d <= n:
if n % d == 0:
return False
d += 1
return True
Submit
Q369 What is the time complexity of this code (n = len(a), tightest bound)?def merge_sort(a):
if len(a) <= 1:
return a
mid = len(a) // 2
left, right = merge_sort(a[:mid]), merge_sort(a[mid:])
out, i, j = [], 0, 0
while i < len(left) and j < len(right):
if left[i] <= right[j]:
out.append(left[i])
i += 1
else:
out.append(right[j])
j += 1
return out + left[i:] + right[j:]
Submit
Q370 The call is range_max(a, 0, n - 1). What is the time complexity?def range_max(a, lo, hi):
if lo == hi:
return a[lo]
mid = (lo + hi) // 2
return max(range_max(a, lo, mid), range_max(a, mid + 1, hi))
Submit
Q371 What is the time complexity of this code (n = len(a), tightest bound)?def halves(a):
if len(a) <= 1:
return 0
return sum(a) + halves(a[:len(a) // 2])
Submit
Q372 What is the time complexity of this code?def work(n):
if n <= 1:
return 1
total = 0
for _ in range(n):
total += 1
return total + work(n // 2) + work(n // 2) + work(n // 2)
Submit
Q373 The input is n distinct numbers already in ascending order. What is the time complexity?def quick_sort(a):
if len(a) <= 1:
return a
pivot = a[0]
smaller = [x for x in a[1:] if x < pivot]
larger = [x for x in a[1:] if x >= pivot]
return quick_sort(smaller) + [pivot] + quick_sort(larger)
Submit
Q374 What is the time complexity of this code?def count(n):
c = 0
for i in range(n):
j = 1
while j < n:
j *= 2
c += 1
return c
Submit
Q375 What is the time complexity of this code?def count(n):
c = 0
for i in range(1, n + 1):
for j in range(i, n + 1, i):
c += 1
return c
Submit
Q376 What is the time complexity of this code?def count(n):
c = 0
for i in range(n):
for j in range(i, n):
c += 1
return c
Submit
Q377 How is -1 written in 8-bit two's complement?
Submit
Q378 What range does an 8-bit signed integer (two's complement) cover?
Submit
Q379 On an 8-bit two's complement adder, 100 + 100 is computed. Read as a signed number, what is the result?
Submit
Q380 For a positive integer x, what does x & (x - 1) do?
Submit
Q381 With x = 12, what is x & -x in two's complement?
Submit
Q382 In an array every number appears exactly twice except one that appears once. What do you get by XORing them all?
Submit
Q383 The 32-bit value 0x12345678 is stored little-endian in the 4 bytes starting at address 0x100. Which byte is at 0x100?
Submit
Q384 Which byte order do network protocols such as the TCP/IP headers use for multi-byte integers?
Submit
Q385 In Java, what are -8 >> 1 and -8 >>> 28?
Submit
Q386 Summing a large C/C++ array int a[N][N], why is row order (outer i, inner j, reading a[i][j]) usually much faster than column order?
Submit
Q387 Two threads each update their own counter, a and b, with no shared data, yet it runs slower than one thread. What is the likely cause?
Submit
Q388 A cache has a 1 ns hit time, a 10% miss rate and a 100 ns miss penalty. What is the average memory access time (AMAT)?
Submit
Q389 Changing a direct-mapped cache to 4-way set associative (same total size) mainly reduces which kind of miss?
Submit
Q390 In languages with IEEE 754 doubles, 0.1 + 0.2 == 0.3 is false. What is the root cause?
Submit
Q391 An IEEE 754 single-precision float has a 24-bit significand (counting the hidden bit). Which integer cannot be stored exactly in a float?
Submit
Q392 JavaScript's Number.MAX_SAFE_INTEGER is 2^53 - 1. Where does the 53 come from?
Submit
Q393 Under IEEE 754, if x is NaN, which expression is true?
Submit
Q394 With doubles, what are (1e20 + -1e20) + 1 and 1e20 + (-1e20 + 1)?
Submit
Q395 The loop "if (a[i] >= 128) sum += a[i];" runs over the same large array. It is much faster once the array is sorted. Why?
Submit
Q396 Which ordering goes from fastest to slowest access?
Submit
Q397 What does this C++ program print (g++ -std=c++17)?#include <iostream>
int main() {
int a[] = {10, 20, 30, 40};
int* p = a + 1;
std::cout << *p + 1 << " " << *(p + 2) << "\n";
}
Submit
Q398 What does this C++ program print (g++ -std=c++17)?#include <iostream>
int main() {
int x = 5;
int& r = x;
r += 3;
int y = r;
y *= 2;
std::cout << x << " " << y << "\n";
}
Submit
Q399 What does this C++ program print (g++ -std=c++17)?#include <iostream>
void f(int v) { v = 100; }
void g(int& v) { v = 200; }
int main() {
int a = 1, b = 1;
f(a);
g(b);
std::cout << a << " " << b << "\n";
}
Submit
Q400 What does this C++ program print (g++ -std=c++17)?#include <iostream>
void swapPtr(int* a, int* b) {
int* t = a;
a = b;
b = t;
}
int main() {
int x = 1, y = 2;
int* p = &x;
int* q = &y;
swapPtr(p, q);
std::cout << *p << " " << *q << "\n";
}
Submit
Q401 What does this C++ program print (g++ -std=c++17)?#include <iostream>
struct A {
A() { std::cout << "D"; }
A(const A&) { std::cout << "C"; }
};
void take(A a) {}
int main() {
A a;
take(a);
A b = a;
std::cout << "\n";
}
Submit
Q402 What does this C++ program print (g++ -std=c++17)?#include <iostream>
#include <utility>
#include <vector>
int main() {
std::vector<int> a{1, 2, 3};
std::vector<int> b = std::move(a);
std::cout << a.size() << " " << b.size() << "\n";
}
Submit
Q403 What does this C++ program print (g++ -std=c++17)?#include <iostream>
struct A {
A() { std::cout << "D"; }
A(const A&) { std::cout << "C"; }
A(A&&) { std::cout << "M"; }
};
A make() { return A(); }
int main() {
A a = make();
std::cout << "\n";
}
Submit
Q404 What does this C++ program print (g++ -std=c++17)?#include <iostream>
#include <utility>
struct A {
A() {}
A(const A&) { std::cout << "C"; }
A(A&&) { std::cout << "M"; }
};
int main() {
const A a;
A b = std::move(a);
A c = std::move(b);
std::cout << "\n";
}
Submit
Q405 What does this C++ program print (g++ -std=c++17)?#include <iostream>
struct Base {
virtual void hi() { std::cout << "B"; }
void plain() { std::cout << "b"; }
};
struct Derived : Base {
void hi() override { std::cout << "D"; }
void plain() { std::cout << "d"; }
};
int main() {
Derived d;
Base* p = &d;
p->hi();
p->plain();
std::cout << "\n";
}
Submit
Q406 What does this C++ program print (g++ -std=c++17)?#include <iostream>
struct Base {
virtual const char* name() const { return "Base"; }
};
struct Derived : Base {
const char* name() const override { return "Derived"; }
};
void byValue(Base b) { std::cout << b.name() << " "; }
void byRef(const Base& b) { std::cout << b.name() << "\n"; }
int main() {
Derived d;
byValue(d);
byRef(d);
}
Submit
Q407 What does this C++ program print (g++ -std=c++17)?#include <iostream>
struct Base {
Base() { hello(); }
virtual void hello() { std::cout << "Base\n"; }
};
struct Derived : Base {
void hello() override { std::cout << "Derived\n"; }
};
int main() {
Derived d;
}
Submit
Q408 What does this C++ program print (g++ -std=c++17)?#include <iostream>
struct T {
char c;
T(char c) : c(c) { std::cout << c; }
~T() { std::cout << char(c - 'a' + 'A'); }
};
int main() {
T a('a');
T b('b');
std::cout << "|";
}
Submit
Q409 What does this C++ program print (g++ -std=c++17)?#include <iostream>
struct Base {
~Base() { std::cout << "~B"; }
};
struct Derived : Base {
~Derived() { std::cout << "~D"; }
};
int main() {
Base* p = new Derived;
delete p;
std::cout << "\n";
}
Submit
Q410 What does this C++ program print (g++ -std=c++17)?#include <iostream>
int counter() {
static int n = 0;
return ++n;
}
int main() {
counter();
counter();
std::cout << counter() << "\n";
}
Submit
Q411 What does this C++ program print (g++ -std=c++17)?#include <iostream>
struct Dog {
static int count;
Dog() { ++count; }
};
int Dog::count = 0;
int main() {
Dog a, b;
{
Dog c;
}
std::cout << Dog::count << "\n";
}
Submit
Q412 What does this C++ program print (g++ -std=c++17)?#include <cstdint>
#include <iostream>
int main() {
std::uint32_t u = 0;
u = u - 1;
std::cout << u << "\n";
}
Submit
Q413 What does this C++ program print (g++ -std=c++17)?#include <climits>
#include <iostream>
int main() {
int x = INT_MAX;
x = x + 1;
std::cout << x << "\n";
}
Submit
Q414 What does this C++ program print (g++ -std=c++17)?#include <iostream>
int main() {
unsigned char a = 200, b = 100;
std::cout << a + b << "\n";
}
Submit
Q415 What does this C++ program print (g++ -std=c++17)?#include <iostream>
int main() {
int a = -1;
unsigned int b = 1;
std::cout << (a < b ? "less" : "not less") << "\n";
}
Submit
Q416 What does this C++ program print (g++ -std=c++17)?#include <iostream>
int main() {
std::cout << -7 / 2 << " " << -7 % 2 << "\n";
}
Submit
Q417 What does this C++ program print (g++ -std=c++17)?#include <iostream>
int main() {
int a[5] = {1, 2, 3, 4, 5};
int* p = &a[4];
int* q = a + 1;
std::cout << p - q << " " << *q << "\n";
}
Submit
Q418 What does this C++ program print (g++ -std=c++17)?#include <iostream>
int main() {
int x = 1, y = 2;
const int* p = &x;
p = &y;
*p = 5;
std::cout << *p << "\n";
}
Submit
Q419 What does this C++ program print (g++ -std=c++17)?#include <iostream>
int main() {
int a = 1, b = 2;
int& r = a;
r = b;
b = 3;
std::cout << a << r << b << "\n";
}
Submit
Q420 What does this C++ program print (g++ -std=c++17)?#include <iostream>
struct Box {
int* v;
Box(int x) : v(new int(x)) {}
};
int main() {
Box a(1);
Box b = a;
*b.v = 9;
std::cout << *a.v << "\n";
}
Submit
Q421 What does this C++ program print (g++ -std=c++17)?#include <iostream>
#include <memory>
#include <utility>
int main() {
auto p = std::make_unique<int>(7);
auto q = std::move(p);
std::cout << (p ? "p" : "null") << " " << *q << "\n";
}
Submit
Q422 What does this C++ program print (g++ -std=c++17)?#include <iostream>
#include <memory>
int main() {
auto a = std::make_shared<int>(1);
auto b = a;
{
auto c = b;
std::cout << a.use_count();
}
std::cout << a.use_count() << "\n";
}
Submit
Q423 What does this C++ program print (g++ -std=c++17)?#include <iostream>
struct B {
virtual void f(int x = 1) { std::cout << "B" << x; }
};
struct D : B {
void f(int x = 2) override { std::cout << "D" << x; }
};
int main() {
D d;
B& b = d;
b.f();
std::cout << "\n";
}
Submit
Q424 What does this C++ program print (g++ -std=c++17)?#include <iostream>
int main() {
int i = 5;
int a = i++;
int b = ++i;
std::cout << a << " " << b << " " << i << "\n";
}
Submit
Q425 What does this C++ program print (g++ -std=c++17)?#include <iostream>
int main() {
long long x = 100000 * 100000;
std::cout << x << "\n";
}
Submit
Q426 What does this C++ program print (g++ -std=c++17)?#include <iostream>
int main() {
int n = 1;
auto byVal = [n] { return n; };
auto byRef = [&n] { return n; };
n = 5;
std::cout << byVal() << " " << byRef() << "\n";
}
Submit
Q427 You just committed a change. After git reset --soft HEAD~1, what state is the repository in?
Submit
Q428 After git reset HEAD~1 with no option (that is, --mixed), where do the last commit's changes go?
Submit
Q429 After git reset --hard HEAD~1, can the commit you dropped still be recovered?
Submit
Q430 A commit on main has been pushed and pulled by teammates. What is the safest way to undo it?
Submit
Q431 feature branched from main at commit A and has B and C on top; main has nothing new. What does git merge feature on main do?
Submit
Q432 feature branched at A and has B and C; main has D after A. After git rebase main on feature, what is feature's history?
Submit
Q433 Why should you not rebase a branch that is already pushed and used by others?
Submit
Q434 You change only the message of your last commit with git commit --amend. What happens?
Submit
Q435 git checkout <a commit hash> says detached HEAD. What happens to commits you make now?
Submit
Q436 feature has commits not merged into your current branch. What does git branch -d feature do?
Submit
Q437 What is the difference between git fetch and git pull?
Submit
Q438 On main you run git cherry-pick <a commit from the hotfix branch>. What happens?
Submit
Q439 You edit app.js, run git add app.js, edit app.js again, then git commit without -a. Which version is committed?
Submit
Q440 Which is true of git stash with no options?
Submit
Q441 Which commits does git log main..feature list?
Submit
Q442 With umask 022, what permissions does a new regular file made by touch get?
Submit
Q443 With umask 027, what permissions does a directory made by mkdir get?
Submit
Q444 After chmod 754 report.sh, which permissions does ls -l show?
Submit
Q445 For a directory, what does the x (execute) permission allow?
Submit
Q446 Which command sends both a command's standard output and standard error to out.txt?
Submit
Q447 What does cat access.log | grep " 404 " | wc -l print?
Submit
Q448 Counting hits per IP is often written sort | uniq -c. Why sort first?
Submit
Q449 Which is true of kill -9 <pid>?
Submit
Q450 What happens when you press Ctrl+Z while a program runs in the terminal?
Submit
Q451 ps shows a process in state Z (defunct), a zombie. How did it get there?
Submit
Q452 A parent exits while its child is still running. What happens to the child?
Submit
Q453 In bash, what does $? hold?
Submit
Q454 In bash, without set -o pipefail, what does false | true; echo $? print?
Submit
Q455 After ln a.txt b and ln -s a.txt c, a.txt is deleted. Can b and c still be read?
Submit
Q456 script.sh has no execute permission and is not on PATH. Which way still runs it?
Submit
Q457 You want a long job to keep running after you close the SSH session. Which works?
Submit
Q458 What does find /var/log -name "*.log" -mtime +7 find?
Submit
Q459 /tmp shows drwxrwxrwt. What does the trailing t (the sticky bit) do?
Submit
Q460 What number does grep -c error app.log print?
Submit
Q461 In bash, you run X=1 and then bash -c 'echo $X'. What is printed?
Submit
Q462 A class makes its constructor private and offers a static getInstance() that always returns the same object. Which pattern is this?
Submit
Q463 Which is a common criticism of the Singleton pattern?
Submit
Q464 An HttpRequest has a dozen optional parameters, so it is built as HttpRequest.newBuilder().uri(u).header(k, v).timeout(t).build(). Which pattern is this?
Submit
Q465 The payment code depends on your own PaymentGateway interface. A third-party SDK has different method names and parameters, so you write a class that implements PaymentGateway and calls the SDK inside. Which pattern is this?
Submit
Q466 In Java, new BufferedInputStream(new GZIPInputStream(new FileInputStream(f))) stacks InputStreams, each adding a little behaviour. Which pattern is this?
Submit
Q467 An ImageProxy implements the same interface as the real Image and loads the image from disk only on the first display(). Which pattern is this?
Submit
Q468 Placing an order needs calls to inventory, payment, shipping and notification subsystems, so OrderService.placeOrder() wraps them all and callers use only that. Which pattern is this?
Submit
Q469 A button's addEventListener("click", handler) and a publish/subscribe message system are examples of which pattern?
Submit
Q470 Shipping cost can be computed by weight, by item count or as free shipping, switched at run time by campaign settings, each implementing one ShippingCost interface. Which pattern is this?
Submit
Q471 A text editor wraps each edit in an object with execute() and undo() and keeps them on a history stack for undo and redo. Which pattern is this?
Submit
Q472 The abstract DataExporter.export() calls open(), writeHeader(), writeRows() and close() in order; CsvExporter and JsonExporter override only some of these steps. Which pattern is this?
Submit
Q473 A vending machine can be waiting for coins, paid, dispensing or sold out, and the same button does different things in each. Each state is written as a class that decides what comes next. Which pattern is this?
Submit
Q474 In a file system, files and folders both implement getSize(); a folder sums its children's sizes, and callers need not tell files from folders. Which pattern is this?
Submit
Q475 Python's for x in obj works on lists, dicts, files and your own classes, as long as __iter__ returns an object with __next__. Which pattern is this?
Submit
Q476 ParserFactory.create(type) returns the right Parser for the config string "csv", "json" or "xml", and callers depend only on the Parser interface. What does this show?
Submit
Q477 An attacker posts a forum comment containing a <script>, and it runs in the browser of everyone who opens the thread. What kind of attack is this?
Submit
Q478 What is the most fundamental defence against XSS?
Submit
Q479 What does adding HttpOnly to a session cookie do?
Submit
Q480 The response has Content-Security-Policy: script-src 'self'. Which script will the browser block?
Submit
Q481 Which describes CSRF (cross-site request forgery)?
Submit
Q482 Which of these does not defend against CSRF?
Submit
Q483 The session cookie has SameSite=Lax. From another website, which request carries it?
Submit
Q484 The backend builds "SELECT * FROM users WHERE name = '" + name + "'" and the user enters ' OR '1'='1 as name. What happens?
Submit
Q485 What is the most reliable way to prevent SQL injection?
Submit
Q486 Which statement about CORS (cross-origin resource sharing) is true?
Submit
Q487 A page fetches a POST to an API on another origin with Content-Type: application/json. What does the browser do first?
Submit
Q488 A cross-origin request is sent with cookies (credentials: 'include') and the server answers Access-Control-Allow-Origin: *. What happens?
Submit
Q489 Which URL is same-origin with https://app.example.com/page?
Submit
Q490 What is the main difference between hashing and encryption?
Submit
Q491 Which is the right way to store user passwords?
Submit
Q492 What does a salt do in password hashing?
Submit
Q493 Which is true of a typical signed JWT (a JWS, say HS256)?
Submit
Q494 When the server checks an incoming JWT, what matters most?
Submit
Q495 With stateless JWTs for login, what happens to an issued token when the user logs out or the account is banned?
Submit
Q496 Once an HTTPS (TLS) connection is up, which kind of encryption carries the bulk of the data?
Submit
Q497 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE t (id INTEGER, bonus INTEGER);
INSERT INTO t VALUES (1, 100), (2, NULL), (3, 50), (4, NULL);
SELECT COUNT(*), COUNT(bonus), SUM(bonus), MAX(bonus) FROM t;
Submit
Q498 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE t (id INTEGER, bonus INTEGER);
INSERT INTO t VALUES (1, 100), (2, NULL), (3, 50), (4, NULL);
SELECT
(SELECT COUNT(*) FROM t WHERE bonus <> 100),
(SELECT COUNT(*) FROM t WHERE bonus IS NULL);
Submit
Q499 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE a (x INTEGER);
INSERT INTO a VALUES (1), (2), (3);
CREATE TABLE b (y INTEGER);
INSERT INTO b VALUES (2), (NULL);
SELECT COUNT(*) FROM a WHERE x NOT IN (SELECT y FROM b);
Submit
Q500 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER, amount INTEGER);
INSERT INTO users VALUES (1, 'ann'), (2, 'bo'), (3, 'cy');
INSERT INTO orders VALUES (1, 1, 30), (2, 1, 80), (3, 2, 20);
SELECT u.name, COUNT(o.id)
FROM users u
LEFT JOIN orders o ON o.user_id = u.id AND o.amount > 25
GROUP BY u.id
ORDER BY u.id;
Submit
Q501 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE orders (id INTEGER PRIMARY KEY, user_id INTEGER, amount INTEGER);
INSERT INTO users VALUES (1, 'ann'), (2, 'bo'), (3, 'cy');
INSERT INTO orders VALUES (1, 1, 30), (2, 1, 80), (3, 2, 20);
SELECT u.name, COUNT(o.id)
FROM users u
LEFT JOIN orders o ON o.user_id = u.id
WHERE o.amount > 25
GROUP BY u.id
ORDER BY u.id;
Submit
Q502 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE p (id INTEGER, tag TEXT);
INSERT INTO p VALUES (1, 'a'), (1, 'b'), (2, 'c');
CREATE TABLE q (id INTEGER, v INTEGER);
INSERT INTO q VALUES (1, 10), (1, 20), (3, 30);
SELECT COUNT(*) FROM p JOIN q ON p.id = q.id;
Submit
Q503 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE sales (region TEXT, amount INTEGER);
INSERT INTO sales VALUES ('east', 10), ('east', 30), ('west', 5), ('west', 6), ('north', 50);
SELECT region, SUM(amount)
FROM sales
GROUP BY region
HAVING COUNT(*) > 1
ORDER BY region;
Submit
Q504 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE sales (region TEXT, amount INTEGER);
INSERT INTO sales VALUES ('east', 10), ('east', 30), ('west', 5), ('west', 6), ('north', 50);
SELECT region, SUM(amount)
FROM sales
WHERE amount > 8
GROUP BY region
ORDER BY region;
Submit
Q505 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE a (x INTEGER);
INSERT INTO a VALUES (1), (2), (2);
CREATE TABLE b (x INTEGER);
INSERT INTO b VALUES (2), (3);
SELECT
(SELECT COUNT(*) FROM (SELECT x FROM a UNION SELECT x FROM b)),
(SELECT COUNT(*) FROM (SELECT x FROM a UNION ALL SELECT x FROM b));
Submit
Q506 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE emp (name TEXT, salary INTEGER);
INSERT INTO emp VALUES ('a', 100), ('b', 300), ('c', 300), ('d', 200);
SELECT DISTINCT salary FROM emp ORDER BY salary DESC LIMIT 1 OFFSET 1;
Submit
Q507 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE s (name TEXT, score INTEGER);
INSERT INTO s VALUES ('a', 90), ('b', 80), ('c', 90), ('d', 70);
SELECT name,
RANK() OVER (ORDER BY score DESC),
DENSE_RANK() OVER (ORDER BY score DESC)
FROM s
ORDER BY score DESC, name;
Submit
Q508 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE tx (day INTEGER, amount INTEGER);
INSERT INTO tx VALUES (1, 5), (2, -2), (3, 10);
SELECT day, SUM(amount) OVER (ORDER BY day) FROM tx ORDER BY day;
Submit
Q509 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)SELECT 7 / 2, 7 / 2.0, 7 % 3;
Submit
Q510 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)SELECT 'a' || NULL, COALESCE(NULL, NULL, 'z'), NULL + 1;
Submit
Q511 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE g (score INTEGER);
INSERT INTO g VALUES (95), (72), (88), (60);
SELECT
SUM(CASE WHEN score >= 80 THEN 1 ELSE 0 END),
COUNT(CASE WHEN score < 70 THEN 1 END)
FROM g;
Submit
Q512 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE e (v INTEGER);
SELECT COUNT(*), SUM(v), MAX(v) FROM e;
Submit
Q513 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE emp (name TEXT, dept TEXT, salary INTEGER);
INSERT INTO emp VALUES ('a', 'x', 100), ('b', 'x', 200), ('c', 'y', 150), ('d', 'y', 150), ('e', 'y', 300);
SELECT name FROM emp e1
WHERE salary > (SELECT AVG(salary) FROM emp e2 WHERE e2.dept = e1.dept)
ORDER BY name;
Submit
Q514 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE staff (id INTEGER PRIMARY KEY, name TEXT, manager_id INTEGER);
INSERT INTO staff VALUES (1, 'ann', NULL), (2, 'bo', 1), (3, 'cy', 1), (4, 'di', 2);
SELECT s.name, m.name
FROM staff s
LEFT JOIN staff m ON s.manager_id = m.id
ORDER BY s.id;
Submit
Q515 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE emails (id INTEGER, email TEXT);
INSERT INTO emails VALUES (1, 'a@x'), (2, 'b@x'), (3, 'a@x'), (4, 'c@x'), (5, 'b@x'), (6, 'a@x');
SELECT email, COUNT(*)
FROM emails
GROUP BY email
HAVING COUNT(*) > 1
ORDER BY COUNT(*) DESC;
Submit
Q516 Run these statements in SQLite. What does the last query return? (One row per line, columns separated by |)CREATE TABLE t (id INTEGER PRIMARY KEY, v INTEGER);
INSERT INTO t VALUES (1, 1), (2, 2), (3, NULL);
UPDATE t SET v = v * 10 WHERE v >= 2 OR v IS NULL;
SELECT id, v FROM t ORDER BY id;
Submit
Q517 What does the response header Cache-Control: no-cache mean?
Submit
Q518 A resource came with Cache-Control: max-age=3600. Requested again half an hour later, what does the browser do?
Submit
Q519 The browser requests a resource with If-None-Match: "abc123", and the resource's ETag on the server is still "abc123". What should the server return?
Submit
Q520 Built files carry a content hash in their name (app.3f9a1c.js) and the HTML references the new name. Which caching header suits these JS files best?
Submit
Q521 An endpoint returning a user's profile sends Cache-Control: private, max-age=60. What does that mean?
Submit
Q522 Which is true of localStorage and sessionStorage?
Submit
Q523 After localStorage.setItem("user", { id: 1 }), what does localStorage.getItem("user") return?
Submit
Q524 A cookie is set with Secure and HttpOnly. What does each do?
Submit
Q525 A cookie is set on www.example.com without a Domain attribute. Is it sent to api.example.com?
Submit
Q526 <body> contains a <div> that contains a <button>, and each registers a click handler with addEventListener("click", …) and default options. Clicking the button runs the handlers in which order?
Submit
Q527 Delegation on a <ul>: ul.addEventListener("click", e => …). The user clicks a <span> inside an <li>. In the handler, what are e.target and e.currentTarget?
Submit
Q528 A list has thousands of items that come and go. What is the main gain from event delegation (one listener on the parent) over one listener per item?
Submit
Q529 A click handler on <a href="/next"> calls only e.stopPropagation(). What happens?
Submit
Q530 A parent registers with addEventListener("click", f, true) and a child with the default options. Clicking the child, which handler runs first?
Submit
Q531 A div has width: 200px; padding: 20px; border: 5px solid; box-sizing: content-box. How wide is it on the page, margin excluded?
Submit
Q532 Two stacked block elements: the upper has margin-bottom: 20px, the lower margin-top: 30px. How much vertical space is between them?
Submit
Q533 A hovered link matches three rules, none with !important: #nav a { color: red }; .menu .item a { color: blue }; a:hover { color: green }. Which colour shows?
Submit
Q534 An element has the inline style style="color: red" and the stylesheet has p { color: blue !important; }. Which colour wins?
Submit
Q535 A container has display: flex; flex-direction: column. Which property centres the children vertically?
Submit
Q536 Three children of a flex container each have flex: 1 and no width. How do they share the width?
Submit
Q537 A 300px-wide container has display: grid; grid-template-columns: 1fr 2fr; and no gap. How wide is each column?
Submit
Q538 A container has grid-template-columns: repeat(3, 1fr), no rows defined, and 7 children. How many rows form?
Submit
Q539 Which style change triggers reflow (layout) rather than just a repaint?
Submit
Q540 A loop sets el.style.width = … on each element and immediately reads el.offsetHeight, and the page crawls. Why, and what fixes it?
Submit
Q541 Why animate transform and opacity rather than left and top?
Submit
Q542 Which is true of the critical rendering path?
Submit
Q543 How do <script defer src="a.js"> and <script async src="b.js"> differ?
Submit
Q544 You need a clickable button. Which markup is best?
Submit
Q545 A button shows only a close icon (an SVG ×) with no text. How do screen-reader users learn what it does?
Submit
Q546 After a form saves, a "Saved" message appears. How do you get screen readers to announce it without cutting off what the user is hearing?
Submit
Q547 What does the central limit theorem say?
Submit
Q548 A population has standard deviation σ = 20 and you draw n = 100 samples. What is the standard error of the sample mean?
Submit
Q549 A test gives p = 0.03. Which reading is correct?
Submit
Q550 A 95% confidence interval for a mean is [2.1, 3.4]. Which statement is correct?
Submit
Q551 An experiment has no real effect, but you test 20 independent metrics, each at α = 0.05. Roughly how likely is at least one "significant" result?
Submit
Q552 You run 10 tests and want the chance of any false positive at most 0.05. With a Bonferroni correction, what threshold does each test use?
Submit
Q553 Within each severity group (mild and severe), treatment A cures a higher share than B; pooled over all patients, B looks better. What is the most likely reason?
Submit
Q554 What is the power of a hypothesis test?
Submit
Q555 All else equal, how many times larger must the sample be to halve the width of a confidence interval for a mean?
Submit
Q556 Ice cream sales and drownings are strongly correlated. What is the most reasonable explanation?
Submit
Q557 Income is usually right-skewed (a few people earn a lot). How do the mean and median usually compare?
Submit
Q558 X and Y are independent with Var(X) = 4 and Var(Y) = 9. What is Var(X - Y)?
Submit
Q559 X ~ N(100, 15²). Roughly what is P(X > 130)?
Submit
Q560 For a normal distribution, about 95% of the data lie within how many standard deviations of the mean?
Submit
Q561 What does the law of large numbers guarantee?
Submit
Q562 An A/B test checks its p-value daily and stops as soon as it drops below 0.05, declaring a winner. What goes wrong?
Submit
Q563 You predicted beforehand that the new version raises conversion. The two-sided p-value is 0.08 and the effect goes the predicted way. What is the one-sided p-value?
Submit
Q564 You want to test whether two categorical variables are independent, say device type (phone, tablet, desktop) and whether an order was placed. Which test fits?
Submit
Q565 The same 30 users timed a task before and after a redesign. Which test best compares the two means?
Submit
Q566 Looking only at users who still use the product, those who used feature X have longer tenure, so feature X must drive retention. What is the main flaw?
Submit
Q567 The bottom 10% of students on a first exam took extra classes and scored clearly higher on the second. Does this show the classes work?
Submit
Q568 As the sample size grows, which of these clearly shrinks?
Submit
Q569 A disease has 1% prevalence. A test catches 90% of cases, and 9% of healthy people test positive. Given a positive test, roughly how likely is the disease?
Submit
Q570 Why does the sample variance divide by n - 1 rather than n?
Submit
Q571 Which practices lower the risk of a false-positive conclusion from an A/B test? (Select all that apply)
Submit
Q572 A model predicts whether an order will be returned within 30 days, scoring it at the moment the order is placed. Which features leak? (Select all that apply)
Submit
Q573 A model predicts whether a loan applicant will default within 12 months, scoring at approval time. Which features leak? (Select all that apply)
Submit
Q574 A hospital wants to predict pneumonia at triage on admission. Which features leak? (Select all that apply)
Submit
Q575 A subscription product predicts whether a user churns next month, scoring on the 1st with earlier data. Which features leak? (Select all that apply)
Submit
Q576 A model flags fraudulent card transactions, scoring in real time as the transaction happens. Which features leak? (Select all that apply)
Submit
Q577 A model predicts whether a candidate accepts an offer, scoring on the day the offer goes out. Which features leak? (Select all that apply)
Submit
Q578 Which practices leak test-set information into training? (Select all that apply)
Submit
Q579 You forecast a store's sales for tomorrow. Which evaluation or feature choices leak? (Select all that apply)
Submit
Q580 Each patient has several X-rays, and you split train and test at random by image. Test accuracy is very high. What is wrong?
Submit
Q581 A model has 2% training error and 25% validation error. What is the likely diagnosis and remedy?
Submit
Q582 What is the main difference between L1 (Lasso) and L2 (Ridge) regularization?
Submit
Q583 In card fraud detection, missing a fraud costs far more than blocking a good transaction. Which metric should threshold tuning favor?
Submit
Q584 99% of the examples are negative. Why is accuracy alone a poor metric?
Submit
Q585 What does a ROC-AUC of 0.8 mean?
Submit
Q586 What typically happens when gradient descent uses too large a learning rate?
Submit
Q587 Which models are sensitive to feature scale and usually need standardization first? (Select all that apply)
Submit
Q588 What objective does k-means minimize?
Submit
Q589 Compared with a single decision tree, what does a random forest mainly reduce?
Submit
Q590 In gradient boosting with squared loss, what does each new tree fit?
Submit
Q591 With softmax outputs p, cross-entropy loss and a one-hot true label y, what is the gradient of the loss with respect to the logits z?
Submit
Q592 A very deep network using sigmoid activations everywhere barely trains its early layers. What is the main reason?
Submit
Q593 Which statement about dropout is correct?
Submit
Q594 At inference time, what does batch normalization normalize with?
Submit
Q595 Why does scaled dot-product attention divide QKᵀ by √d_k?
Submit
Q596 In logistic regression a feature has weight 0.7. Holding the others fixed, what happens when it rises by 1?
Submit
Q597 A classifier has TP = 40, FP = 10 and FN = 20 on a test set. What are its precision and recall?
Submit
Q598 Raising a binary classifier's threshold from 0.5 to 0.8 usually does what?
Submit
Q599 Positives are only 1% of the data. Which ways of handling the imbalance are sound? (Select all that apply)
Submit
Q600 You target-encode a high-cardinality category such as a ZIP code (replacing it with the category's mean label). Which practices are sound? (Select all that apply)
Submit
Q601 A few months after launch a model degrades. Some features are now distributed differently from training, while the feature-label relationship is unchanged. What is this called?
Submit
Q602 What does this NumPy code print?import numpy as np
a = np.ones((3, 1))
b = np.ones(4)
print((a + b).shape)
Submit
Q603 What does this NumPy code print?import numpy as np
a = np.arange(5)
b = a[1:3]
b[0] = 99
print(a.tolist())A [0, 1, 2, 3, 4] B [99, 1, 2, 3, 4] C [0, 99, 2, 3, 4] D [99, 99, 2, 3, 4]
Submit
Q604 What does this NumPy code print?import numpy as np
a = np.arange(5)
b = a[[1, 2]]
b[0] = 99
print(a.tolist())A [0, 1, 2, 3, 4] B [0, 99, 2, 3, 4] C [99, 1, 2, 3, 4] D IndexError
Submit
Q605 What does this NumPy code print?import numpy as np
a = np.array([3, -1, 4, -5])
a[a < 0] = 0
print(a.tolist())A [3, 4] B [0, -1, 0, -5] C [3, -1, 4, -5] D [3, 0, 4, 0]
Submit
Q606 What does this NumPy code print?import numpy as np
a = np.array([1, 2, 3])
a[0] = 2.9
print(a.tolist())
Submit
Q607 What does this NumPy code print?import numpy as np
a = np.arange(6).reshape(2, 3)
print(a.sum(axis=0).tolist())
Submit
Q608 What does this NumPy code print?import numpy as np
a = np.arange(6).reshape(2, 3)
print((a - a.mean(axis=1, keepdims=True)).tolist())A [[-1.0, 0.0, 1.0], [-1.0, 0.0, 1.0]] B [[-2.5, -1.5, -0.5], [0.5, 1.5, 2.5]] C [[-1.5, -1.5, -1.5], [1.5, 1.5, 1.5]] D ValueError
Submit
Q609 What does this NumPy code print?import numpy as np
print(int(np.argmax([1, 3, 3, 2])))
Submit
Q610 What does this NumPy code print?import numpy as np
print(np.arange(6).reshape(3, 2).T.tolist())A [[0, 1], [2, 3], [4, 5]] B [[0, 1, 2], [3, 4, 5]] C [[0, 2, 4], [1, 3, 5]] D [[5, 4, 3], [2, 1, 0]]
Submit
Q611 What does this NumPy code print?import numpy as np
a = np.array([[1, 2], [3, 4]])
print((a * a).tolist(), (a @ a).tolist())A [[7, 10], [15, 22]] [[1, 4], [9, 16]] B [[1, 4], [9, 16]] [[1, 4], [9, 16]] C [[7, 10], [15, 22]] [[7, 10], [15, 22]] D [[1, 4], [9, 16]] [[7, 10], [15, 22]]
Submit
Q612 What does this NumPy code print?import numpy as np
v = np.array([1, 2, 3])
print(int(v @ v), (v[:, None] @ v[None, :]).shape)
Submit
Q613 What does this NumPy code print?import numpy as np
a = np.array([200], dtype=np.uint8)
print((a + a).tolist())
Submit
Q614 What does this NumPy code print?import numpy as np
a = np.array([1.0, np.nan, 3.0])
print(float(np.sum(a)), float(np.nansum(a)))
Submit
Q615 What does this NumPy code print?import numpy as np
a = np.zeros(4)
b = a.reshape(2, 2)
b[0, 0] = 1
print(a.tolist())A [0.0, 0.0, 0.0, 0.0] B [1.0, 0.0, 0.0, 0.0] C [[1.0, 0.0], [0.0, 0.0]] D [1, 0, 0, 0]
Submit
Q616 What does this NumPy code print?import numpy as np
values, counts = np.unique([3, 1, 3, 2, 3], return_counts=True)
print(values.tolist(), counts.tolist())A [3, 1, 2] [3, 1, 1] B [1, 2, 3] [1, 1, 3] C [1, 2, 3] [3, 1, 1] D [3, 1, 3, 2, 3] [5]
Submit
Q617 What does this NumPy code print?import numpy as np
print((np.arange(3)[:, None] * np.arange(3)).tolist())A [0, 1, 4] B [[0, 1, 4]] C 5 D [[0, 0, 0], [0, 1, 2], [0, 2, 4]]
Submit
Q618 What does this NumPy code print?import numpy as np
print(np.argsort([30, 10, 20]).tolist())
Submit
Q619 What does this NumPy code print?import numpy as np
a = np.array([1, 2, 3])
print(bool((a > 1).any()), bool((a > 1).all()))
Submit
Q620 What does this NumPy code print?import numpy as np
print(0.1 + 0.2 == 0.3, bool(np.isclose(0.1 + 0.2, 0.3)))
Submit
Q621 What does this NumPy code print?import numpy as np
a = np.array([1, 2, 3])
try:
a += 0.5
print(a.tolist())
except TypeError:
print("TypeError")
Submit
Your answers stay in this browser on this device; open this page signed in to keep them in your account.