Criteo interview questions & answers

10 real Criteo interview questions with full model answers — Coding. Drawn from the same verified bank ChannelPulse drills from (10 Criteo questions in total).

CodingEasyCriteoSoftware Engineer

1. Set Mismatch (LeetCode)

Model answer

The task

An array contains values from 1 through its length, except one value appears twice and another is absent. Return the repeated value and the missing value, in that order.

Key idea

XOR all array values with all values in the expected range. Matching values cancel, leaving the XOR of the duplicate and missing values. Split the values by a distinguishing bit to recover both candidates, then count one candidate to determine which is repeated.

Approach

  1. XOR each array value and each expected value together.
  2. Find a set bit in the resulting XOR; the two answers differ at that bit.
  3. XOR values in each group separately to get the two candidates.
  4. Count one candidate in the array to identify the duplicate and return the result.
class Solution:
    def findErrorNums(self, nums: list[int]) -> list[int]:
        n = len(nums)
        combined_xor = 0

        # Equal values cancel, leaving duplicate XOR missing.
        for expected, value in enumerate(nums, start=1):
            combined_xor ^= expected ^ value

        # The lowest set bit separates the two candidates.
        distinguishing_bit = combined_xor & -combined_xor
        candidate_a = 0
        candidate_b = 0

        for expected, value in enumerate(nums, start=1):
            if value & distinguishing_bit:
                candidate_a ^= value
            else:
                candidate_b ^= value

            if expected & distinguishing_bit:
                candidate_a ^= expected
            else:
                candidate_b ^= expected

        # Exactly one candidate occurs twice in nums.
        if sum(value == candidate_a for value in nums) == 2:
            return [candidate_a, candidate_b]
        return [candidate_b, candidate_a]

Complexity:

  • Time: O(n), using a constant number of linear passes.
  • Space: O(1), storing only a fixed number of variables.

Common follow-ups

  • What if the input may contain more than one error? This XOR partition relies on exactly one duplicate and one missing value.
  • Can you use a hash set? Yes; track seen values to find the duplicate, then scan 1..n for the missing value, using O(n) extra space.
  • Can the input be modified? Sign marking can find both values in O(n) time and O(1) extra space, but it changes the array unless restored.
CodingEasyCriteoSoftware Engineer

2. Flood Fill (LeetCode)

Model answer

The task

Given a grid of pixel colors and a starting cell, recolor the starting cell and every cell connected to it up, down, left, or right that has the same original color. Return the updated grid.

Key idea

Explore the connected region using DFS, recoloring cells as they are visited. The recoloring also marks cells as visited, so they are not processed again. If the requested color is already the starting cell’s color, return immediately to avoid revisiting cells.

Approach

  1. Save the starting cell’s original color.
  2. If it already matches the new color, return the grid unchanged.
  3. Initialize a stack with the starting coordinates.
  4. Pop cells, recolor them, and add any in-bounds neighbors that still have the original color.
  5. Return the modified grid.
class Solution:
    def floodFill(
        self,
        image: list[list[int]],
        sr: int,
        sc: int,
        color: int
    ) -> list[list[int]]:
        rows, cols = len(image), len(image[0])
        original = image[sr][sc]

        # Without this check, recolored cells would still match the original.
        if original == color:
            return image

        stack = [(sr, sc)]
        image[sr][sc] = color

        while stack:
            row, col = stack.pop()

            for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):
                nr, nc = row + dr, col + dc

                if (
                    0 <= nr < rows
                    and 0 <= nc < cols
                    and image[nr][nc] == original
                ):
                    # Recolor immediately so this cell is added only once.
                    image[nr][nc] = color
                    stack.append((nr, nc))

        return image

Complexity:

  • Time: O(mn) in the worst case, where every cell belongs to the connected region.
  • Space: O(mn) in the worst case for the DFS stack.

Common follow-ups

  • What if the region should connect diagonally too? Check all eight surrounding neighbors instead of four.
  • Can this be done with BFS? Yes; use a queue in place of the stack.
  • What if the grid is very large? Consider iterative traversal to avoid recursion-depth limits.
  • What if the input grid must remain unchanged? Copy it first and perform the traversal on the copy.
CodingEasyCriteoSoftware Engineer

3. Two Sum (LeetCode)

Model answer

The task

Given a list of integers and a target, return the indices of two distinct elements whose values add up to the target. The usual version guarantees a valid pair.

Key idea

As we scan the list, store each value’s index in a hash table. For the current value, check whether its needed complement has already appeared; this finds a pair in one pass.

Approach

  1. Create a dictionary mapping previously seen values to their indices.
  2. For each element, compute the complement needed to reach the target.
  3. If that complement is in the dictionary, return its stored index and the current index.
  4. Otherwise, store the current value and index, then continue.
from typing import List

class Solution:
    def twoSum(self, nums: List[int], target: int) -> List[int]:
        # Map each value already visited to its index.
        seen = {}

        for index, value in enumerate(nums):
            complement = target - value

            # A match must come from an earlier, distinct element.
            if complement in seen:
                return [seen[complement], index]

            seen[value] = index

        # The standard problem guarantees a solution.
        raise ValueError("No two elements sum to the target")

Complexity:

  • Time: O(n), where n is the number of elements; each lookup and insertion is O(1) on average.
  • Space: O(n), for the dictionary of values seen so far.

Common follow-ups

  • What if there may be multiple valid pairs? Return the first pair found, or keep searching and collect pairs according to the required output rules.
  • What if the input is sorted? Use two pointers from opposite ends for O(1) extra space; preserve original indices if those are required.
  • What if values repeat? The dictionary stores indices, and checking before insertion ensures the current element is not paired with itself.
CodingEasyCriteoSoftware Engineer

4. Valid Parentheses (LeetCode)

Model answer

The task

Determine whether a string of opening and closing round, square, and curly brackets is correctly nested and matched. Return a boolean.

Key idea

A closing bracket must match the most recent unmatched opening bracket. A stack captures that order: push openings, and check each closing bracket against the stack’s top.

Approach

  1. Return False if the string has odd length.
  2. Map each closing bracket to its matching opening bracket.
  3. Scan the string from left to right.
  4. Push opening brackets onto the stack.
  5. For a closing bracket, return False if the stack is empty or its top does not match; otherwise pop.
  6. Return True only if the stack is empty after the scan.
class Solution:
    def isValid(self, s: str) -> bool:
        pairs = {")": "(", "]": "[", "}": "{"}
        openings = set(pairs.values())
        stack = []

        for char in s:
            if char in openings:
                stack.append(char)
            else:
                # A closing bracket must match the latest unmatched opening.
                if not stack or stack[-1] != pairs.get(char):
                    return False
                stack.pop()

        # Unmatched opening brackets make the sequence invalid.
        return not stack

Complexity:

  • Time: O(n), where n is the string length; each character is processed once.
  • Space: O(n) in the worst case, when all characters are opening brackets.

Common follow-ups

  • How would you support additional bracket types? Add their matching pairs to the map.
  • Can you stop early? Yes; return False as soon as a closing bracket mismatches or has no opening bracket.
  • What if the input includes non-bracket characters? Define how to handle them, then either ignore them or reject them during the scan.
CodingEasyCriteoSoftware Engineer

5. Intersection of Two Arrays II (LeetCode)

Model answer

The task

Return the values that occur in both integer arrays, including each value only as many times as it appears in both. The order of the returned values does not matter.

Key idea

Count the values in the shorter array, then scan the longer array. When a value still has a positive count, add it to the result and decrement its count.

Approach

  1. Identify the shorter and longer arrays.
  2. Build a frequency map for the shorter array.
  3. Scan the longer array, checking whether each value has a remaining count.
  4. Append matches and decrement their counts so no value is used too many times.
  5. Return the collected matches.
from collections import Counter
from typing import List

class Solution:
    def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
        # Count the shorter array to reduce auxiliary space.
        if len(nums1) > len(nums2):
            nums1, nums2 = nums2, nums1

        remaining = Counter(nums1)
        result = []

        for value in nums2:
            if remaining.get(value, 0) > 0:
                result.append(value)
                remaining[value] -= 1

        return result

Complexity:

  • Time: O(m + n), where m and n are the array lengths.
  • Space: O(min(m, n)) auxiliary space for the frequency map, excluding the result.

Common follow-ups

  • What if both arrays are already sorted? Use two pointers and advance the pointer holding the smaller value.
  • What if the first array is too large to fit in memory? Count the smaller array if possible, or process sorted data in chunks.
  • What if the result must be returned in sorted order? Sort the result, or use the two-pointer approach on sorted arrays.
CodingEasyCriteoSoftware Engineer

6. Ransom Note (LeetCode)

Model answer

The task

Determine whether the characters in one string can be assembled from the characters in another. Each available character can be used at most once.

Key idea

Count how many times each character is available, then check that the required count for every character does not exceed its available count.

Approach

  1. Count the characters in the available string.
  2. Count the characters needed for the target string.
  3. If any required count is greater than the available count, return False.
  4. Otherwise, return True.
from collections import Counter

class Solution:
    def canConstruct(self, ransomNote: str, magazine: str) -> bool:
        available = Counter(magazine)
        needed = Counter(ransomNote)

        # Every required character must be available in sufficient quantity.
        for char, count in needed.items():
            if available[char] < count:
                return False

        return True

Complexity:

  • Time: O(m + n), where m and n are the string lengths; counting and checking take linear time.
  • Space: O(k), where k is the number of distinct characters stored in the counters.

Common follow-ups

  • What if characters are case-insensitive? Normalize both strings, such as with .lower(), before counting.
  • What if the character set is fixed and small? Use a fixed-size array instead of a hash map.
  • Can you stop early while counting? Yes; decrement available counts as you scan the target and return False if a count goes below zero.
CodingEasyCriteoSoftware Engineer

7. Intersection of Two Arrays (LeetCode)

Model answer

The task

Return the distinct values that appear in both integer arrays. The result may be in any order.

Key idea

Put one array’s values in a hash set, then scan the other array and collect values found in that set. Use a second set so duplicate values appear only once in the result.

Approach

  1. Convert the first array to a set for expected constant-time membership checks.
  2. Initialize an empty set for the common values.
  3. Scan the second array and add each value present in the first set.
  4. Convert the result set to a list.
class Solution:
    def intersection(self, nums1: list[int], nums2: list[int]) -> list[int]:
        values = set(nums1)
        common = set()

        for value in nums2:
            if value in values:
                common.add(value)

        return list(common)

Complexity:

  • Time: O(m + n) expected, to build the set and scan both arrays.
  • Space: O(m + k), for the set of first-array values and the distinct common values.

Common follow-ups

  • What if duplicates should be preserved? Count occurrences in a hash map and consume a count when a match is found.
  • What if both arrays are sorted? Use two pointers to find common values in O(m + n) time.
  • What if memory is limited? Sort the arrays in place and use two pointers, trading the hash-set space for sorting time.
  • What if one array is much smaller? Build the set from the smaller array to reduce lookup-set space.
CodingMediumCriteoSoftware Engineer

8. Search in Rotated Sorted Array (LeetCode)

Model answer

The task

Given an ascending array that has been rotated at an unknown position, find the index of a target value, or return -1 if it is absent. The values are distinct.

Key idea

At each binary-search step, at least one half of the current range is still sorted. Check whether the target falls within that half; if so, keep it, otherwise search the other half.

Approach

  1. Initialize two pointers at the ends of the array.
  2. While the pointers have not crossed, inspect the middle value.
  3. If it matches the target, return its index.
  4. If the left half is sorted, check whether the target lies within its bounds and discard the other half if it does.
  5. Otherwise, use the sorted right half in the same way.
  6. Return -1 if the range becomes empty.
class Solution:
    def search(self, nums: list[int], target: int) -> int:
        left, right = 0, len(nums) - 1

        while left <= right:
            mid = (left + right) // 2

            if nums[mid] == target:
                return mid

            # The left half is sorted.
            if nums[left] <= nums[mid]:
                if nums[left] <= target < nums[mid]:
                    right = mid - 1
                else:
                    left = mid + 1
            # Otherwise, the right half is sorted.
            else:
                if nums[mid] < target <= nums[right]:
                    left = mid + 1
                else:
                    right = mid - 1

        return -1

Complexity:

  • Time: O(log n), because each step discards about half the remaining range.
  • Space: O(1), since the search uses only a fixed number of variables.

Common follow-ups

  • What changes if duplicates are allowed? If the endpoints and midpoint are equal, discard one endpoint; worst-case time can become O(n).
  • How would you find the rotation pivot? Binary-search for the minimum element, then search the appropriate sorted portion.
  • How would you return all matching indices with duplicates? First locate a match, then scan outward across adjacent equal values.
CodingMediumCriteoSoftware Engineer

9. Random Pick with Weight (LeetCode)

Model answer

The task

Implement a picker that returns an index at random, with each index’s chance of being selected proportional to its weight.

Key idea

Build prefix sums of the weights. Draw a uniformly random integer from the total weight’s range, then binary-search for the first prefix sum greater than the draw.

Approach

  1. Store cumulative weight sums during initialization.
  2. Keep the total weight, which is the last cumulative sum.
  3. For each pick, draw an integer in [0, total).
  4. Use binary search to find the first cumulative sum greater than that integer.
  5. Return the corresponding index.
import random
from bisect import bisect_right
from typing import List

class Solution:
    def __init__(self, w: List[int]):
        # Each index owns a range of integer outcomes proportional to its weight.
        self.prefix = []
        total = 0

        for weight in w:
            total += weight
            self.prefix.append(total)

        self.total = total

    def pickIndex(self) -> int:
        # The target is uniformly chosen from [0, total).
        target = random.randrange(self.total)

        # Find the first prefix sum strictly greater than target.
        return bisect_right(self.prefix, target)

Complexity:

  • Time: O(n) to initialize; O(log n) per pick due to binary search.
  • Space: O(n) for the cumulative sums.

Common follow-ups

  • What if weights change between picks? Use a Fenwick tree to support weight updates and weighted selection in O(log n).
  • How would you handle very frequent picks? The current approach already provides O(log n) picks; an alias table can provide O(1) picks after O(n) preprocessing if weights are static.
  • What if some weights are zero? The prefix search naturally skips indices with zero weight, so they are never selected.
CodingMediumCriteoSoftware Engineer

10. Maximum Subarray (LeetCode)

Model answer

The task

Given an integer array, find the largest sum obtainable from a nonempty contiguous subarray. The array may contain only negative numbers.

Key idea

At each position, the best subarray ending there either starts at the current value or extends the best subarray ending just before it. Track that running best and the largest sum seen so far; this naturally handles all-negative arrays.

Approach

  1. Initialize both the running sum and overall maximum to the first value.
  2. Scan the remaining values from left to right.
  3. For each value, either start a new subarray there or extend the previous one.
  4. Update the overall maximum whenever the running sum improves.
  5. Return the overall maximum.
from typing import List

class Solution:
    def maxSubArray(self, nums: List[int]) -> int:
        # The subarray must be nonempty, so start with the first element.
        current_sum = best_sum = nums[0]

        for value in nums[1:]:
            # Either begin at this value or extend the prior subarray.
            current_sum = max(value, current_sum + value)
            best_sum = max(best_sum, current_sum)

        return best_sum

Complexity:

  • Time: O(n), where n is the number of array elements; each is processed once.
  • Space: O(1), since only two running sums are stored.

Common follow-ups

  • How would you return the subarray’s start and end indices? Track the current start index and record both indices whenever the overall maximum improves.
  • What if the input can be empty? Define the desired empty-input result, then handle it before accessing the first element.
  • How does divide and conquer solve this? Recursively compute the best sum on each half, plus the best suffix on the left and prefix on the right; combine the three results.

Practice these out loud, don't memorise them

Reading an answer is not the same as being able to give one under pressure. ChannelPulse plays the interviewer, asks the follow-ups, and scores each answer with feedback and a model answer so you can hear the gap between what you said and what lands.

Get ChannelPulse Browse all questions