cswork / OAOpen practice workspace

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
Topic
Review
621 questions
  1. Which of these do threads of the same process share?
  2. What directly causes a page fault?
  3. Which scheduling policy can starve long jobs?
  4. Which is NOT a necessary condition for deadlock?
  5. What is the typical symptom of thrashing?
  6. A program calls fork() three times in a row without checking the return value. How many processes exist at the end, including the original?
  7. Why is switching between threads of one process usually cheaper than switching processes?
  8. Which kind of fragmentation does paging eliminate?
  9. 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?
  10. Which page replacement policy can show Belady's anomaly (more frames, more faults)?
  11. Which of these always needs a system call (a switch to kernel mode)?
  12. What is a zombie process?
  13. What does the TLB cache?
  14. With 32-bit virtual addresses and 4 KB pages, how many bits is the page offset?
  15. In round-robin scheduling, what does a very large time quantum degenerate into?
  16. What does copy-on-write do for fork?
  17. What is the main benefit of DMA?
  18. In the many-to-one user-level thread model, what happens when one thread makes a blocking system call?
  19. What usually crashes a very deep recursion?
  20. What happens to a child process when its parent exits first?
  21. What does the I in ACID stand for?
  22. Which isolation level prevents dirty reads but still allows non-repeatable reads?
  23. Under the SQL standard, which isolation level is guaranteed to prevent phantom reads?
  24. What does second normal form (2NF) remove?
  25. Employee(emp_id, dept_id, dept_name) has key emp_id, and dept_id determines dept_name. Which normal form does it violate?
  26. Which statements about PRIMARY KEY and UNIQUE are true? (Select all that apply)
  27. Why do databases usually prefer B+ trees over hash indexes for general-purpose indexing?
  28. Which statement about a clustered index is true?
  29. Table A has 5 rows. At least how many rows does SELECT * FROM A LEFT JOIN B ON ... return?
  30. Column x holds 1, NULL, 2, NULL. What are COUNT(*) and COUNT(x)?
  31. To keep only customers with more than 10 orders, where does the condition go?
  32. In standard SQL, which clause can refer to an alias defined in the SELECT list?
  33. What does SELECT * FROM t WHERE x = NULL return?
  34. What does two-phase locking (2PL) guarantee?
  35. What is the core rule of write-ahead logging (WAL)?
  36. What does a FOREIGN KEY constraint enforce?
  37. Which statement about adding an index is FALSE?
  38. How do UNION and UNION ALL differ?
  39. There is a composite B+ tree index on (a, b). Which predicates can use it efficiently? (Select all that apply)
  40. By the CAP theorem, during a network partition a distributed system must choose between which two?
  41. How does optimistic concurrency control usually detect a conflict?
  42. What is the most reliable defence against SQL injection?
  43. Which of these most commonly runs directly over UDP?
  44. What is the order of segments in the TCP three-way handshake?
  45. Which layer of the TCP/IP model does IP belong to?
  46. A server is temporarily overloaded and wants the client to retry later. Which status code fits best?
  47. What does ARP do?
  48. How many usable host addresses does a /24 subnet have?
  49. How many usable host addresses does a /26 subnet have?
  50. Which side of a TCP connection enters TIME_WAIT after it closes?
  51. Which port does HTTPS use by default?
  52. At which layers do a switch and a router mainly work?
  53. What does TCP flow control prevent?
  54. During TCP slow start, how does the congestion window grow?
  55. Which guarantees does TLS (HTTPS) provide? (Select all that apply)
  56. Which HTTP methods are idempotent by the spec? (Select all that apply)
  57. Which are private IPv4 addresses? (Select all that apply)
  58. How long does it take to put 1 MB (10^6 bytes) onto a 100 Mbps link, ignoring propagation delay?
  59. What is the main improvement of HTTP/2 over HTTP/1.1?
  60. Which protocol does ping use?
  61. What problem does NAT mainly solve?
  62. How is a WebSocket connection established?
  63. What is DHCP mainly for?
  64. Two threads each run count++ 1000 times on a shared count starting at 0, with no synchronisation. What is the final value?
  65. Thread A holds lock L1 and waits for L2; thread B holds L2 and waits for L1. What is the simplest reliable fix?
  66. A counting semaphore initialised to 3 guards a section. At most how many threads can be inside at once?
  67. Why should a condition-variable wait() sit inside a while loop that rechecks the condition?
  68. What is a livelock?
  69. In Java, count is declared volatile int and several threads run count++. What happens?
  70. What does a read-write lock allow?
  71. Which classic problem can a lock-free stack built on CAS run into?
  72. When is a spinlock a better fit than a blocking mutex?
  73. In default CPython (with the GIL), how do you usually use several cores for CPU-bound work?
  74. What makes a lock reentrant?
  75. A thread calls lock() twice in a row on the same non-reentrant mutex. What happens?
  76. A bounded-buffer producer-consumer built on semaphores usually needs which semaphores?
  77. In the dining philosophers problem, which change avoids deadlock?
  78. A program is 90% perfectly parallelisable. By Amdahl's law, what is the best speed-up on 4 cores?
  79. What does a single-threaded event loop (Node.js, asyncio) provide?
  80. What is priority inversion?
  81. In Java double-checked locking for a singleton, why must the instance field be volatile?
  82. What does a barrier do?
  83. What are the main benefits of a thread pool over a new thread per task? (Select all that apply)
  84. What is the key difference between Thread.sleep() and Object.wait() in Java?
  85. What exactly is a data race?
  86. Which kind of polymorphism do overriding and overloading give?
  87. Which statements about abstract classes and interfaces in Java are true? (Select all that apply)
  88. What does the Liskov substitution principle require?
  89. What does the O in SOLID (open/closed) mean?
  90. What does the dependency inversion principle recommend?
  91. Why 'favour composition over inheritance'?
  92. In Java, a subclass declares a static method with the same signature as one in its parent. What happens?
  93. What is the key step in implementing the Singleton pattern?
  94. Which situation suits the Observer pattern?
  95. Java forbids multiple inheritance of classes mainly to avoid what?
  96. What is the Strategy pattern for?
  97. In Java, why must you override hashCode when you override equals?
  98. What characterises the Decorator pattern?
  99. In Java, who can access a protected member?
  100. What is the main purpose of encapsulation?
  101. What problem does the Factory Method pattern solve?
  102. What does this Python code print?
    def add(x, items=[]):
        items.append(x)
        return items
    
    add(1)
    add(2)
    print(add(3))
  103. What does this Python code print?
    fs = [lambda: i for i in range(3)]
    print([f() for f in fs])
  104. What does this Python code print?
    print(-7 // 2, -7 % 2)
  105. What does this Python code print?
    a = [[0] * 2] * 2
    a[0][0] = 1
    print(a)
  106. What does this Python code print?
    a = [1, 2]
    b = a[:]
    print(a == b, a is b)
  107. What does this Python code print?
    s = "abcdef"
    print(s[::-2])
  108. What does this Python code print?
    d = {"a": 1, "b": 2}
    d["a"] = 3
    d["c"] = 4
    print(list(d))
  109. What does this Python code print?
    g = (x * x for x in range(4))
    print(sum(g), sum(g))
  110. What does this Python code print?
    t = ([1],)
    try:
        t[0] += [2]
    except TypeError:
        pass
    print(t)
  111. 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)
  112. 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())
  113. What does this Python code print?
    words = ["bb", "a", "ccc", "dd"]
    print(sorted(words, key=len))
  114. What does this Python code print?
    print(list(zip([1, 2, 3], "ab")))
  115. What does this Python code print?
    print(True + True * 3)
  116. What does this Python code print?
    print(1 < 3 > 2, 1 < 2 < 1)
  117. What does this Python code print?
    def f():
        try:
            return "try"
        finally:
            print("finally", end=" ")
    
    print(f())
  118. What does this Python code print?
    a = {1, 2, 3}
    b = {2, 3, 4}
    print(sorted(a ^ b))
  119. What does this Python code print?
    print("-".join("ab" * 2))
  120. What does this Python code print?
    x = 10
    
    def f():
        print(x)
        x = 5
    
    try:
        f()
    except UnboundLocalError:
        print("error")
  121. What does this Python code print?
    print([x for x in range(10) if x % 3 == 0][-1])
  122. What does this Python code print?
    d = {}
    d.setdefault("k", []).append(1)
    d.setdefault("k", []).append(2)
    print(d)
  123. 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])
  124. What does this Python code print?
    print(round(2.5), round(3.5))
  125. What does this Python code print?
    print(0.1 + 0.2 == 0.3)
  126. What does this Python code print?
    for i, c in enumerate("xyz", 1):
        pass
    print(i, c)
  127. What does this Python code print?
    def f(a, *rest, b=0):
        return a + sum(rest) + b
    
    print(f(1, 2, 3, b=4))
  128. What does this JavaScript print when run in Node.js?
    console.log(typeof null, typeof NaN);
  129. 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(" "));
  130. What does this JavaScript print when run in Node.js?
    console.log(0 == "", 0 === "", null == undefined);
  131. What does this JavaScript print when run in Node.js?
    console.log([10, 9, 1, 2].sort().join(","));
  132. 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");
  133. What does this JavaScript print when run in Node.js?
    console.log(typeof f, typeof g);
    function f() {}
    var g = function () {};
  134. 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());
  135. 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());
  136. What does this JavaScript print when run in Node.js?
    console.log("5" + 3, "5" - 3, "5" * "2");
  137. 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);
  138. 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(","));
  139. 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);
  140. What does this JavaScript print when run in Node.js?
    console.log(["1", "2", "3"].map(parseInt).join(","));
  141. What does this JavaScript print when run in Node.js?
    const { a = 1, b = 2 } = { a: undefined, b: null };
    console.log(a, b);
  142. What does this JavaScript print when run in Node.js?
    console.log(NaN === NaN, Object.is(NaN, NaN), [NaN].includes(NaN), [NaN].indexOf(NaN));
  143. 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);
  144. 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);
  145. 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);
  146. 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);
  147. 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);
  148. 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"));
  149. What does this JavaScript print when run in Node.js?
    var x = 1;
    function f() {
      console.log(x);
      var x = 2;
    }
    f();
  150. 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();
  151. 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(" "));
  152. What does this JavaScript print when run in Node.js?
    const before = typeof foo;
    var foo = 1;
    function foo() {}
    console.log(before, typeof foo);
  153. What does this JavaScript print when run in Node.js?
    try {
      new Dog();
    } catch (e) {
      console.log(e.name);
    }
    class Dog {}
  154. 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(""));
  155. What does this JavaScript print when run in Node.js?
    let msg = "hi";
    const say = () => msg;
    msg = "bye";
    console.log(say());
  156. 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);
  157. 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));
  158. 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(" "));
  159. 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));
  160. 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);
  161. 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);
  162. 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);
  163. What does this JavaScript print when run in Node.js?
    console.log(JSON.stringify([] + []), [] + {}, [1, 2] + [3]);
  164. What does this JavaScript print when run in Node.js?
    console.log([] == false, [0] == false, "0" == false, null == false);
  165. What does this JavaScript print when run in Node.js?
    console.log(Number(""), Number(" 12 "), Number("1e3"), parseInt("12px"), Number("12px"));
  166. What does this JavaScript print when run in Node.js?
    console.log(Boolean("0"), Boolean(""), !!NaN, !![], !!{});
  167. What does this JavaScript print when run in Node.js?
    console.log(true + 1, null + 1, undefined + 1, "3" * "4", [2] * [3]);
  168. 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));
        }
    }
  169. 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));
        }
    }
  170. What does this Java program print?
    public class Main {
        public static void main(String[] args) {
            System.out.println(('a' + 1) + " " + (char) ('a' + 1));
        }
    }
  171. 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);
        }
    }
  172. 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());
        }
    }
  173. 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);
        }
    }
  174. 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);
        }
    }
  175. 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());
        }
    }
  176. 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"));
        }
    }
  177. 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);
        }
    }
  178. 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());
        }
    }
  179. 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);
        }
    }
  180. Two fair dice are rolled. What is the probability that the sum is 7?
  181. Two fair dice are rolled. What is the probability of at least one six?
  182. A fair coin is tossed 3 times. What is the probability of exactly 2 heads?
  183. Two cards are drawn without replacement from a standard 52-card deck. What is the probability both are aces?
  184. A fair coin is tossed until the first head. What is the expected number of tosses?
  185. How many people are needed for the chance that two share a birthday to exceed 50% (365 equally likely days)?
  186. 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?
  187. Monty Hall: you pick a door, and the host, who knows, opens another empty door. If you switch, what is your chance of winning?
  188. A fair die is rolled until a six appears. What is the expected number of rolls?
  189. How many rolls of a fair die are expected before every face has appeared at least once?
  190. 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)
  191. A random permutation of 1..n is chosen. What is the expected number of fixed points?
  192. A bag holds 3 red and 5 blue balls. Two are drawn without replacement. What is the probability both are red?
  193. Two fair dice are rolled. What is the expected sum?
  194. P(A) = 0.5, P(B) = 0.4 and P(A∩B) = 0.2. What is P(A∪B)?
  195. A fair coin is tossed 10 times. What is the variance of the number of heads?
  196. Two fair dice are rolled. What is the expected value of the larger number, roughly?
  197. A stick is broken at two uniformly random points. What is the probability the three pieces form a triangle?
  198. 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?
  199. Two different numbers are chosen at random from 1 to 10. What is the probability their sum is even?
  200. How many distinct arrangements are there of the letters of LEVEL?
  201. A fair coin is tossed until two heads in a row appear. What is the expected number of tosses?
  202. Independent events A and B have P(A) = 0.3 and P(B) = 0.5. What is the probability that neither happens?
  203. A fair coin is tossed 4 times. What is the probability of more heads than tails?
  204. What comes next: 2, 6, 12, 20, 30, ?
  205. What is the angle between the hour and minute hands at 3:15?
  206. 'All bloops are razzies and all razzies are lazzies.' What follows for certain?
  207. 'If it rains, the ground gets wet.' Which statement is logically equivalent?
  208. Each islander is a knight (always truthful) or a knave (always lies). A says: 'We are both knaves.' What are A and B?
  209. Of 12 balls one is heavier. What is the minimum number of weighings on a balance that always finds it?
  210. A finishes a job alone in 6 hours, B in 3. How long do they take together?
  211. Two trains 300 km apart head toward each other at 60 km/h and 90 km/h. When do they meet?
  212. A bat and a ball cost $1.10 in total, and the bat costs $1 more than the ball. How much is the ball?
  213. A lily patch doubles every day and covers the lake on day 48. On which day did it cover half?
  214. 5 machines make 5 widgets in 5 minutes. How long do 100 machines take to make 100 widgets?
  215. NOT (A AND B) is equivalent to which expression?
  216. A drawer has 10 black and 10 white socks. In the dark, how many must you take to be sure of a matching pair?
  217. Ten people each shake hands with every other person once. How many handshakes?
  218. Which is the odd one out: 2, 3, 5, 9, 11?
  219. 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?
  220. How many trailing zeros does 100! have?
  221. How many squares of all sizes are there on an 8×8 chessboard?
  222. Today is Wednesday. What day is it 100 days from now?
  223. What comes next: 1, 4, 9, 16, 25, ?
  224. In a class of 30, 21 know Python and 17 know Java, and everyone knows at least one. How many know both?
  225. Inserting one element at index 0 of a dynamic array (such as a Python list) holding n elements costs?
  226. Why does a dynamic array grow by a constant factor (say, doubling its capacity) instead of by a fixed amount (say, 100 more slots)?
  227. 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?
  228. Which statements about hash tables are true? Select all that apply.
  229. 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?
  230. Two lowercase strings of length n are checked for being anagrams with a 26-slot count array. Time and extra space?
  231. 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:
  232. 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?
  233. Prefix sums are P[0] = 0 and P[i] = a[0] + … + a[i-1]. The sum of a[l..r], both ends included, is:
  234. What is the standard way to merge a list of possibly overlapping intervals, and its time?
  235. 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:
  236. 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?
  237. Binary search on the answer (bisect a range of candidate answers, testing each with check(mid)) requires:
  238. In Java or C++, why write mid = lo + (hi - lo) / 2 instead of mid = (lo + hi) / 2?
  239. Building a binary heap from n unordered elements bottom-up (sift down from the last internal node back to the root) takes:
  240. To keep the k largest numbers of a stream with a heap, the standard approach is:
  241. Which of these is the classic use of a monotonic stack?
  242. To pick the most pairwise non-overlapping intervals, the right greedy choice each step is the interval that:
  243. 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?
  244. 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?
  245. A singly linked list keeps both head and tail pointers. Which operation is not O(1)?
  246. Linked-list solutions often put a dummy node before the head. What is it for?
  247. Recursive DFS on a binary tree with n nodes and height h uses how much extra (call stack) space?
  248. A full binary tree (every node has 0 or 2 children) has n internal nodes. How many leaves does it have?
  249. To compute every subtree's height bottom-up, a node must come after both of its subtrees. Which DFS order is that?
  250. 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.)
  251. 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?
  252. With distinct values, which traversal pairs determine a binary tree uniquely? Select all that apply.
  253. Rebuilding a tree from preorder and inorder, what does a hash map from value to inorder index change?
  254. Why is checking left child < node < right child at every node not enough to validate a binary search tree?
  255. Inserting 1, 2, …, n in order into a plain (unbalanced) binary search tree gives what height, in edges?
  256. How do you delete a node with two children from a BST?
  257. Which search gives the fewest moves from start to target on an unweighted grid directly?
  258. Why does BFS usually mark a cell visited when it is enqueued rather than when it is dequeued?
  259. An R×C grid has k sources; every cell needs its distance to the nearest source. The efficient way is:
  260. With both path compression and union by rank (or size), what is the amortized time per union-find operation?
  261. Detecting a cycle in an undirected graph with union-find, edge by edge: when does edge (u, v) close a cycle?
  262. After m edges on n vertices, union-find made s successful unions (the ends were in different sets). How many connected components are there?
  263. Kahn's algorithm (repeatedly removing in-degree-0 vertices) outputs fewer than n vertices. What does that mean?
  264. DFS-based topological sort outputs which order?
  265. A directed graph has negative edges but no negative cycle. Which algorithm finds single-source shortest paths?
  266. In 0-1 BFS (edge weights 0 or 1, using a deque), where do newly reached vertices go?
  267. Kruskal's algorithm takes edges from lightest to heaviest. When does it skip an edge?
  268. For a connected weighted undirected graph with V vertices, which are true? Select all that apply.
  269. Backtracking generates every subset of n distinct items, copying each one out as a list. Total time?
  270. 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?
  271. When backtracking over all valid strings of n parenthesis pairs, when may you append ")"?
  272. How many balanced strings can 3 pairs of parentheses form?
  273. In N-Queens, queens at (r1, c1) and (r2, c2) share a diagonal exactly when:
  274. In Combination Sum with positive candidates sorted ascending, why may the loop break (not just skip) once candidates[i] exceeds the remaining target?
  275. Which two properties make a problem a good fit for dynamic programming?
  276. Which are true of top-down memoization and bottom-up tabulation? Select all that apply.
  277. 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?
  278. 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?
  279. 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?
  280. Why is the O(n·W) 0/1 knapsack DP called pseudo-polynomial?
  281. 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]?
  282. The O(n log n) longest increasing subsequence method keeps an array tails. What is tails[k]?
  283. What is the length of the longest strictly increasing subsequence of [8, 3, 6, 1, 7, 4, 9, 2]?
  284. What is the edit distance (insert, delete, replace each cost 1) from "abc" to "yabd"?
  285. 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?
  286. Expand-around-center for palindromic substrings: how many centers does a string of length n have?
  287. 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?
  288. House Robber on a circle (first and last houses are neighbours) is usually solved how?
  289. 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?
  290. 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?
  291. Stock trading with at most k transactions over n days: what can you do when k >= n / 2?
  292. 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?
  293. Given meeting times, what is the minimum number of rooms?
  294. 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]?
  295. Longest increasing path in a matrix by memoized DFS: why is no visited set needed against walking in circles?
  296. A stack with push, pop, top and O(1) getMin is usually built how?
  297. Why use collections.deque instead of a list with pop(0) for a BFS queue in Python?
  298. What gives an LRU cache O(1) get and put?
  299. Why does an LRU cache use a doubly linked list rather than a singly linked one?
  300. A trie holds N words. Checking whether a word of length L is present takes:
  301. Why does preorder with explicit null markers (such as #) let a binary tree be rebuilt, while plain preorder does not?
  302. For a positive integer x, what does x & (x - 1) == 0 mean?
  303. What is the bitwise XOR of all of [7, 3, 5, 3, 7]?
  304. In two's complement, what does x & -x give? Take x = 12.
  305. "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?
  306. 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?
  307. Searching a grid for a word by backtracking, why mark the current cell as in use before recursing and restore it afterwards?
  308. 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?
  309. Does the diameter of a binary tree (the most edges on a path between any two nodes) always pass through the root?
  310. 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?
  311. 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
  312. What is the time complexity of this code (tightest bound)?
    def build(n):
        a = []
        for i in range(n):
            a.append(i)
        return a
  313. What is the time complexity of this code (n = len(a), tightest bound)?
    def normalize(a):
        return [x / max(a) for x in a]
  314. 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
  315. 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
  316. 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
  317. 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
  318. 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])
  319. 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;
    }
  320. 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
  321. 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
  322. 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]
  323. 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]
  324. 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
  325. 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)
  326. 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
  327. 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
  328. 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
  329. 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)
  330. 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
  331. 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
  332. 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
  333. 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))
  334. 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)
  335. 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)
  336. 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
  337. 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
  338. 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
  339. 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)
  340. 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
  341. 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
  342. 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
  343. 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
  344. 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
  345. 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
  346. 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
  347. 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
  348. What is the time complexity of this code?
    def fib(n):
        if n < 2:
            return n
        return fib(n - 1) + fib(n - 2)
  349. 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)
  350. 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]
  351. 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]
  352. 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)
  353. 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]
  354. 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)
  355. 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
  356. 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))
  357. 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]
  358. 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]
  359. 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)
  360. 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()
  361. 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)
  362. 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]
  363. 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
  364. 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
  365. 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
  366. 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]]
  367. 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
  368. 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
  369. 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:]
  370. 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))
  371. 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])
  372. 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)
  373. 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)
  374. 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
  375. 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
  376. 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
  377. How is -1 written in 8-bit two's complement?
  378. What range does an 8-bit signed integer (two's complement) cover?
  379. On an 8-bit two's complement adder, 100 + 100 is computed. Read as a signed number, what is the result?
  380. For a positive integer x, what does x & (x - 1) do?
  381. With x = 12, what is x & -x in two's complement?
  382. In an array every number appears exactly twice except one that appears once. What do you get by XORing them all?
  383. The 32-bit value 0x12345678 is stored little-endian in the 4 bytes starting at address 0x100. Which byte is at 0x100?
  384. Which byte order do network protocols such as the TCP/IP headers use for multi-byte integers?
  385. In Java, what are -8 >> 1 and -8 >>> 28?
  386. 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?
  387. 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?
  388. 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)?
  389. Changing a direct-mapped cache to 4-way set associative (same total size) mainly reduces which kind of miss?
  390. In languages with IEEE 754 doubles, 0.1 + 0.2 == 0.3 is false. What is the root cause?
  391. An IEEE 754 single-precision float has a 24-bit significand (counting the hidden bit). Which integer cannot be stored exactly in a float?
  392. JavaScript's Number.MAX_SAFE_INTEGER is 2^53 - 1. Where does the 53 come from?
  393. Under IEEE 754, if x is NaN, which expression is true?
  394. With doubles, what are (1e20 + -1e20) + 1 and 1e20 + (-1e20 + 1)?
  395. 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?
  396. Which ordering goes from fastest to slowest access?
  397. 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";
    }
  398. 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";
    }
  399. 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";
    }
  400. 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";
    }
  401. 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";
    }
  402. 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";
    }
  403. 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";
    }
  404. 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";
    }
  405. 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";
    }
  406. 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);
    }
  407. 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;
    }
  408. 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 << "|";
    }
  409. 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";
    }
  410. 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";
    }
  411. 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";
    }
  412. 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";
    }
  413. 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";
    }
  414. 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";
    }
  415. 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";
    }
  416. What does this C++ program print (g++ -std=c++17)?
    #include <iostream>
    
    int main() {
        std::cout << -7 / 2 << " " << -7 % 2 << "\n";
    }
  417. 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";
    }
  418. 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";
    }
  419. 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";
    }
  420. 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";
    }
  421. 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";
    }
  422. 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";
    }
  423. 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";
    }
  424. 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";
    }
  425. What does this C++ program print (g++ -std=c++17)?
    #include <iostream>
    
    int main() {
        long long x = 100000 * 100000;
        std::cout << x << "\n";
    }
  426. 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";
    }
  427. You just committed a change. After git reset --soft HEAD~1, what state is the repository in?
  428. After git reset HEAD~1 with no option (that is, --mixed), where do the last commit's changes go?
  429. After git reset --hard HEAD~1, can the commit you dropped still be recovered?
  430. A commit on main has been pushed and pulled by teammates. What is the safest way to undo it?
  431. 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?
  432. 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?
  433. Why should you not rebase a branch that is already pushed and used by others?
  434. You change only the message of your last commit with git commit --amend. What happens?
  435. git checkout <a commit hash> says detached HEAD. What happens to commits you make now?
  436. feature has commits not merged into your current branch. What does git branch -d feature do?
  437. What is the difference between git fetch and git pull?
  438. On main you run git cherry-pick <a commit from the hotfix branch>. What happens?
  439. You edit app.js, run git add app.js, edit app.js again, then git commit without -a. Which version is committed?
  440. Which is true of git stash with no options?
  441. Which commits does git log main..feature list?
  442. With umask 022, what permissions does a new regular file made by touch get?
  443. With umask 027, what permissions does a directory made by mkdir get?
  444. After chmod 754 report.sh, which permissions does ls -l show?
  445. For a directory, what does the x (execute) permission allow?
  446. Which command sends both a command's standard output and standard error to out.txt?
  447. What does cat access.log | grep " 404 " | wc -l print?
  448. Counting hits per IP is often written sort | uniq -c. Why sort first?
  449. Which is true of kill -9 <pid>?
  450. What happens when you press Ctrl+Z while a program runs in the terminal?
  451. ps shows a process in state Z (defunct), a zombie. How did it get there?
  452. A parent exits while its child is still running. What happens to the child?
  453. In bash, what does $? hold?
  454. In bash, without set -o pipefail, what does false | true; echo $? print?
  455. After ln a.txt b and ln -s a.txt c, a.txt is deleted. Can b and c still be read?
  456. script.sh has no execute permission and is not on PATH. Which way still runs it?
  457. You want a long job to keep running after you close the SSH session. Which works?
  458. What does find /var/log -name "*.log" -mtime +7 find?
  459. /tmp shows drwxrwxrwt. What does the trailing t (the sticky bit) do?
  460. What number does grep -c error app.log print?
  461. In bash, you run X=1 and then bash -c 'echo $X'. What is printed?
  462. A class makes its constructor private and offers a static getInstance() that always returns the same object. Which pattern is this?
  463. Which is a common criticism of the Singleton pattern?
  464. 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?
  465. 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?
  466. In Java, new BufferedInputStream(new GZIPInputStream(new FileInputStream(f))) stacks InputStreams, each adding a little behaviour. Which pattern is this?
  467. 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?
  468. 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?
  469. A button's addEventListener("click", handler) and a publish/subscribe message system are examples of which pattern?
  470. 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?
  471. 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?
  472. 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?
  473. 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?
  474. 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?
  475. 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?
  476. 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?
  477. 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?
  478. What is the most fundamental defence against XSS?
  479. What does adding HttpOnly to a session cookie do?
  480. The response has Content-Security-Policy: script-src 'self'. Which script will the browser block?
  481. Which describes CSRF (cross-site request forgery)?
  482. Which of these does not defend against CSRF?
  483. The session cookie has SameSite=Lax. From another website, which request carries it?
  484. The backend builds "SELECT * FROM users WHERE name = '" + name + "'" and the user enters ' OR '1'='1 as name. What happens?
  485. What is the most reliable way to prevent SQL injection?
  486. Which statement about CORS (cross-origin resource sharing) is true?
  487. A page fetches a POST to an API on another origin with Content-Type: application/json. What does the browser do first?
  488. A cross-origin request is sent with cookies (credentials: 'include') and the server answers Access-Control-Allow-Origin: *. What happens?
  489. Which URL is same-origin with https://app.example.com/page?
  490. What is the main difference between hashing and encryption?
  491. Which is the right way to store user passwords?
  492. What does a salt do in password hashing?
  493. Which is true of a typical signed JWT (a JWS, say HS256)?
  494. When the server checks an incoming JWT, what matters most?
  495. With stateless JWTs for login, what happens to an issued token when the user logs out or the account is banned?
  496. Once an HTTPS (TLS) connection is up, which kind of encryption carries the bulk of the data?
  497. 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;
  498. 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);
  499. 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);
  500. 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;
  501. 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;
  502. 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;
  503. 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;
  504. 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;
  505. 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));
  506. 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;
  507. 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;
  508. 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;
  509. 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;
  510. 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;
  511. 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;
  512. 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;
  513. 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;
  514. 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;
  515. 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;
  516. 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;
  517. What does the response header Cache-Control: no-cache mean?
  518. A resource came with Cache-Control: max-age=3600. Requested again half an hour later, what does the browser do?
  519. 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?
  520. 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?
  521. An endpoint returning a user's profile sends Cache-Control: private, max-age=60. What does that mean?
  522. Which is true of localStorage and sessionStorage?
  523. After localStorage.setItem("user", { id: 1 }), what does localStorage.getItem("user") return?
  524. A cookie is set with Secure and HttpOnly. What does each do?
  525. A cookie is set on www.example.com without a Domain attribute. Is it sent to api.example.com?
  526. <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?
  527. 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?
  528. 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?
  529. A click handler on <a href="/next"> calls only e.stopPropagation(). What happens?
  530. A parent registers with addEventListener("click", f, true) and a child with the default options. Clicking the child, which handler runs first?
  531. A div has width: 200px; padding: 20px; border: 5px solid; box-sizing: content-box. How wide is it on the page, margin excluded?
  532. Two stacked block elements: the upper has margin-bottom: 20px, the lower margin-top: 30px. How much vertical space is between them?
  533. 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?
  534. An element has the inline style style="color: red" and the stylesheet has p { color: blue !important; }. Which colour wins?
  535. A container has display: flex; flex-direction: column. Which property centres the children vertically?
  536. Three children of a flex container each have flex: 1 and no width. How do they share the width?
  537. A 300px-wide container has display: grid; grid-template-columns: 1fr 2fr; and no gap. How wide is each column?
  538. A container has grid-template-columns: repeat(3, 1fr), no rows defined, and 7 children. How many rows form?
  539. Which style change triggers reflow (layout) rather than just a repaint?
  540. A loop sets el.style.width = … on each element and immediately reads el.offsetHeight, and the page crawls. Why, and what fixes it?
  541. Why animate transform and opacity rather than left and top?
  542. Which is true of the critical rendering path?
  543. How do <script defer src="a.js"> and <script async src="b.js"> differ?
  544. You need a clickable button. Which markup is best?
  545. A button shows only a close icon (an SVG ×) with no text. How do screen-reader users learn what it does?
  546. 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?
  547. What does the central limit theorem say?
  548. A population has standard deviation σ = 20 and you draw n = 100 samples. What is the standard error of the sample mean?
  549. A test gives p = 0.03. Which reading is correct?
  550. A 95% confidence interval for a mean is [2.1, 3.4]. Which statement is correct?
  551. 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?
  552. 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?
  553. 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?
  554. What is the power of a hypothesis test?
  555. All else equal, how many times larger must the sample be to halve the width of a confidence interval for a mean?
  556. Ice cream sales and drownings are strongly correlated. What is the most reasonable explanation?
  557. Income is usually right-skewed (a few people earn a lot). How do the mean and median usually compare?
  558. X and Y are independent with Var(X) = 4 and Var(Y) = 9. What is Var(X - Y)?
  559. X ~ N(100, 15²). Roughly what is P(X > 130)?
  560. For a normal distribution, about 95% of the data lie within how many standard deviations of the mean?
  561. What does the law of large numbers guarantee?
  562. 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?
  563. 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?
  564. 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?
  565. The same 30 users timed a task before and after a redesign. Which test best compares the two means?
  566. 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?
  567. 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?
  568. As the sample size grows, which of these clearly shrinks?
  569. 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?
  570. Why does the sample variance divide by n - 1 rather than n?
  571. Which practices lower the risk of a false-positive conclusion from an A/B test? (Select all that apply)
  572. 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)
  573. A model predicts whether a loan applicant will default within 12 months, scoring at approval time. Which features leak? (Select all that apply)
  574. A hospital wants to predict pneumonia at triage on admission. Which features leak? (Select all that apply)
  575. A subscription product predicts whether a user churns next month, scoring on the 1st with earlier data. Which features leak? (Select all that apply)
  576. A model flags fraudulent card transactions, scoring in real time as the transaction happens. Which features leak? (Select all that apply)
  577. A model predicts whether a candidate accepts an offer, scoring on the day the offer goes out. Which features leak? (Select all that apply)
  578. Which practices leak test-set information into training? (Select all that apply)
  579. You forecast a store's sales for tomorrow. Which evaluation or feature choices leak? (Select all that apply)
  580. Each patient has several X-rays, and you split train and test at random by image. Test accuracy is very high. What is wrong?
  581. A model has 2% training error and 25% validation error. What is the likely diagnosis and remedy?
  582. What is the main difference between L1 (Lasso) and L2 (Ridge) regularization?
  583. In card fraud detection, missing a fraud costs far more than blocking a good transaction. Which metric should threshold tuning favor?
  584. 99% of the examples are negative. Why is accuracy alone a poor metric?
  585. What does a ROC-AUC of 0.8 mean?
  586. What typically happens when gradient descent uses too large a learning rate?
  587. Which models are sensitive to feature scale and usually need standardization first? (Select all that apply)
  588. What objective does k-means minimize?
  589. Compared with a single decision tree, what does a random forest mainly reduce?
  590. In gradient boosting with squared loss, what does each new tree fit?
  591. 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?
  592. A very deep network using sigmoid activations everywhere barely trains its early layers. What is the main reason?
  593. Which statement about dropout is correct?
  594. At inference time, what does batch normalization normalize with?
  595. Why does scaled dot-product attention divide QKᵀ by √d_k?
  596. In logistic regression a feature has weight 0.7. Holding the others fixed, what happens when it rises by 1?
  597. A classifier has TP = 40, FP = 10 and FN = 20 on a test set. What are its precision and recall?
  598. Raising a binary classifier's threshold from 0.5 to 0.8 usually does what?
  599. Positives are only 1% of the data. Which ways of handling the imbalance are sound? (Select all that apply)
  600. 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)
  601. 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?
  602. What does this NumPy code print?
    import numpy as np
    
    a = np.ones((3, 1))
    b = np.ones(4)
    print((a + b).shape)
  603. What does this NumPy code print?
    import numpy as np
    
    a = np.arange(5)
    b = a[1:3]
    b[0] = 99
    print(a.tolist())
  604. What does this NumPy code print?
    import numpy as np
    
    a = np.arange(5)
    b = a[[1, 2]]
    b[0] = 99
    print(a.tolist())
  605. What does this NumPy code print?
    import numpy as np
    
    a = np.array([3, -1, 4, -5])
    a[a < 0] = 0
    print(a.tolist())
  606. What does this NumPy code print?
    import numpy as np
    
    a = np.array([1, 2, 3])
    a[0] = 2.9
    print(a.tolist())
  607. What does this NumPy code print?
    import numpy as np
    
    a = np.arange(6).reshape(2, 3)
    print(a.sum(axis=0).tolist())
  608. 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())
  609. What does this NumPy code print?
    import numpy as np
    
    print(int(np.argmax([1, 3, 3, 2])))
  610. What does this NumPy code print?
    import numpy as np
    
    print(np.arange(6).reshape(3, 2).T.tolist())
  611. What does this NumPy code print?
    import numpy as np
    
    a = np.array([[1, 2], [3, 4]])
    print((a * a).tolist(), (a @ a).tolist())
  612. 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)
  613. What does this NumPy code print?
    import numpy as np
    
    a = np.array([200], dtype=np.uint8)
    print((a + a).tolist())
  614. 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)))
  615. 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())
  616. 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())
  617. What does this NumPy code print?
    import numpy as np
    
    print((np.arange(3)[:, None] * np.arange(3)).tolist())
  618. What does this NumPy code print?
    import numpy as np
    
    print(np.argsort([30, 10, 20]).tolist())
  619. 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()))
  620. 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)))
  621. 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")

Your answers stay in this browser on this device; open this page signed in to keep them in your account.