Skip to content
Tutorials Center
My learning

Topics

Lesson 71 of 77 ยท Practice

Practice: JavaScript and Python Question Set

Practice 15 JavaScript and Python interview questions: predict-the-output puzzles and short coding tasks, with hidden solutions and clear explanations.

Reading about interview questions is not the same as answering them. This lesson is a practice set of 15 questions: eight for JavaScript and seven for Python. Some ask you to predict what code prints; others ask you to write a short function. Every question has a solution hidden in a "Show solution" box with an explanation, so you can commit to an answer first and check it afterwards.

How to use it: set a timer (about five minutes per question is a fair interview pace), write your answer on paper or in the editor, and only then open the solution. If you miss one, note the topic and revisit the matching lesson, linked at the end of each group. For the theory behind the puzzles, see the JavaScript and Python chapters of this track.

How to practice

Commit Write your answer first.
Time it About five minutes each.
Check Open the solution after.
Log misses Note the topic to review.
1 / 2

JavaScript: predict the output

Run the editor only after you have written down your predictions for questions 1, 2, 3 and 6. Running it first spoils the exercise.

Question 1. What do the three values in the first console.log print?

Question 2. The first loop uses var and the second uses let. What is logged, and in what order?

Question 3. In what order are the letters A to E printed?

Question 6. What does calling a class method that was copied into a variable do?

JS JavaScript predictions (run after you answer)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solutions for questions 1, 2, 3 and 6

Question 1: it prints [object Object] true object. [] + {} converts both sides to strings ("" and "[object Object]") and concatenates. [] == false converts the array to "", then to 0, and false to 0, so the comparison is true. typeof null is the historic quirk "object". See JavaScript: Types, Coercion and Equality.

Question 2: it prints var 3 three times, then let 0, let 1, let 2. var has one i for the whole function, and by the time the timers fire the loop has ended with i === 3. let creates a fresh binding for each iteration, so each callback keeps its own value. The timers fire in the order they were scheduled. See JavaScript: Scope, Hoisting and Closures.

Question 3: A E C D B. Synchronous code runs first (A, E). Then the microtask queue drains in the order it was filled (the promise callback C, then D). Only after that does the timer callback (a macrotask) run, printing B. See JavaScript: Promises, async/await and the Event Loop.

Question 6: it throws a TypeError. A method copied out of its object loses its this. Class bodies are always in strict mode, so a plain call has this set to undefined, and ++this.count fails. The fixes are .bind(instance), an arrow function field, or calling instance.inc(). See JavaScript: this, Prototypes and Classes.

JavaScript: write the function

Question 4. Write once(fn): it returns a function that calls fn only the first time and returns that same result every later time.

Question 5. Write groupBy(items, keyFn): it returns an object whose keys are keyFn(item) and whose values are arrays of the items with that key, in the original order.

Question 7. Write chunk(array, size): split an array into pieces of at most size items. Do not change the input.

Question 8. Write an async retry(fn, times): call fn up to times times and resolve with the first successful result. If every attempt fails, reject with the last error.

The editor contains stubs that fail on purpose. Replace them with your own code until every line says pass.

JS JavaScript: write once, groupBy, chunk and retry

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Show solutions for questions 4, 5, 7 and 8
JavaScript
function once(fn) {
  let called = false;
  let result;
  return function (...args) {
    if (!called) {
      called = true;
      result = fn.apply(this, args);
    }
    return result;
  };
}

function groupBy(items, keyFn) {
  const groups = {};
  for (const item of items) {
    const key = keyFn(item);
    (groups[key] ??= []).push(item);
  }
  return groups;
}

function chunk(array, size) {
  const pieces = [];
  for (let i = 0; i < array.length; i += size) {
    pieces.push(array.slice(i, i + size));
  }
  return pieces;
}

async function retry(fn, times) {
  let lastError;
  for (let attempt = 1; attempt <= times; attempt++) {
    try {
      return await fn();
    } catch (error) {
      lastError = error;
    }
  }
  throw lastError;
}

once stores the result in a closure and uses a flag rather than checking for undefined, so a function that legitimately returns undefined still runs only once. groupBy uses ??= to create each array on first use; use Object.create(null) or a Map if keys could clash with built-in names. chunk uses slice, which copies, so the input is never changed; mention that size must be a positive integer, or the loop would never end. retry must await inside the try, otherwise a rejected promise escapes the catch. In real systems you would add a delay between attempts, ideally growing with each failure.

Review: JavaScript: Arrays, Objects and Functional Patterns and JavaScript: Classic Coding Questions.

Python: predict the output

Question 9. What do the three print calls show? Question 10. What does the list print? Question 11. What are a, c and the identity check?

Python Python predictions (run after you answer)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solutions for questions 9, 10 and 11

Question 9: [1], then [1, 2], then [3]. The default list is created once, when def runs, and shared by every call that does not pass its own. The usual fix is bucket=None and if bucket is None: bucket = []. See Python: Mutability, Identity and the Data Model.

Question 10: [2, 2, 2]. The lambdas capture the variable i, not its value at that moment. By the time they run, i is 2. Bind the value with a default argument: lambda i=i: i. See Python: Decorators, Closures and Context Managers.

Question 11: [1, 2, 3] [1, 2, 3, 4] True. b += [3] extends the same list in place, and b and a are the same object. a + [4] builds a new list, so a is not changed by it.

Python: write the function

Question 12. first_unique_char(s) returns the index of the first character that appears exactly once, or -1.

Question 13. is_valid(s) returns True if the brackets ()[]{} in s are balanced and correctly nested.

Question 14. running_max(numbers) is a generator that yields the largest value seen so far, for each input item.

Question 15. merge_intervals(intervals) merges overlapping [start, end] pairs and returns them sorted. Touching intervals such as [1, 3] and [3, 5] count as overlapping.

Python Python: write the four functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Show solutions for questions 12 to 15
Python
from collections import Counter

def first_unique_char(s):
    counts = Counter(s)
    for index, char in enumerate(s):
        if counts[char] == 1:
            return index
    return -1

def is_valid(s):
    pairs = {")": "(", "]": "[", "}": "{"}
    stack = []
    for char in s:
        if char in pairs.values():
            stack.append(char)
        elif char in pairs:
            if not stack or stack.pop() != pairs[char]:
                return False
    return not stack

def running_max(numbers):
    best = None
    for number in numbers:
        if best is None or number > best:
            best = number
        yield best

def merge_intervals(intervals):
    merged = []
    for start, end in sorted(intervals):
        if merged and start <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], end)
        else:
            merged.append([start, end])
    return merged

first_unique_char counts in one pass and scans in a second: O(n) time. is_valid uses a stack; the final not stack catches unclosed brackets, and the not stack test inside catches a closer with nothing open. running_max uses a generator, so it works on huge or endless input with O(1) memory; checking best is None rather than starting at 0 handles all-negative input. merge_intervals sorts by start (O(n log n)), then either extends the last merged interval or starts a new one; copying the pairs into new lists avoids changing the caller's data.

Review: Python: Iterators, Generators and Comprehensions and Python: Classic Coding Questions.

Scoring yourself

Count one point for each question you answered correctly before opening the solution, and half a point if you were right but could not explain why. Fourteen or more means you are ready for most screens in these two languages; ten to thirteen means a short review of the weak topics; below ten, redo the matching lessons and try the set again in a week. The explanation counts as much as the answer: interviewers ask "why" after every correct output.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does for (var i...) setTimeout(() => console.log(i)) print the same number three times?

    var is function scoped, so every callback closes over the same variable, and the loop has already finished.
  2. 2. What is the problem with def add(item, bucket=[]) in Python?

    Defaults are evaluated once at definition time, so mutations to the default object persist between calls.
  3. 3. Which data structure is the natural fit for checking balanced brackets?

    The most recently opened bracket must be the first one closed, which is last-in, first-out.
  4. 4. Why should retry use return await fn() inside the try block?

    Without await, the rejection happens after the function has already returned the promise, so the catch never sees it.

Summary

  • Commit to an answer before checking; explain why, not just what.
  • Closures, event-loop order, this loss, mutable defaults and late binding are the favorite puzzles.
  • Write small functions with edge cases in mind: empty input, one item, duplicates, touching ranges.
  • Name the time and space cost of every solution you write.
  • Keep a log of missed topics and revisit the lessons for them.

Next: Practice: Data Structures, Databases and Systems Set.