The Integer Sieve

An easy Python interview practice problem on DataDriven. Write the Python and run it against test cases, with instant feedback.

Domain
Python
Difficulty
easy
Seniority
L3
Asked in
WarnerMedia

Problem

An on-call engineer traced an inflated row count to a job that treats every number in its JSON-decoded items as a genuine integer count, when the payload also carries booleans, floats and strings. Return only the genuine integers from items, in the order they arrived.

Not everything in this list belongs here.

Example

Input:

items = [1,"hello",2.5,true,3,null]

Output:

[1,3]

Worked solution and explanation

This is a type-identity question that looks like a list filter. Everyone writes the single pass. What separates candidates is knowing that bool is a subclass of int in Python, so isinstance(True, int) is True. Reach for isinstance and [False, 0, True, 1] comes back untouched instead of [0, 1], and every flag in the payload gets summed downstream as a 1 or a 0.

Why the obvious check lies

When JSON is decoded, 'true' and 'false' arrive as Python True and False. Those are real int instances by inheritance, which is why True + True is 2. A check that asks "is this an int or anything built on one" lets them through. The question this problem actually asks is narrower: is the exact type int?

Subclass-aware check
isinstance(item, int) accepts True and False because bool inherits from int. On [False, 0, True, 1] it keeps all four.
Exact type check
type(item) is int compares the concrete type, so bool fails it while 0 and 1 pass. On [False, 0, True, 1] it keeps [0, 1].
The version that leaks booleans
def filter_integers(items):
    result = []
    for item in items:
        if isinstance(item, int):  # True and False pass here
            result.append(item)
    return result

Looks right on most inputs, keeps every True and False.

The solution

Step 1: Ask for the exact type

Test each element with type(item) is int. That one comparison rejects bool, float (even a whole-looking 2.0), str and None in a single rule, with no special cases stacked on top.

Step 2: Keep survivors in arrival order

Append each qualifying element to a fresh list as you meet it. The input is never mutated, and the output order is the input order, which is what the grader checks.

Exact type identity, one pass
def filter_integers(items):
    result = []
    for item in items:
        if type(item) is int:
            result.append(item)
    return result

O(n) time, O(k) extra space for the k integers kept.

Common follow-up questions