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)acceptsTrueandFalsebecauseboolinherits fromint. On[False, 0, True, 1]it keeps all four.- Exact type check
type(item) is intcompares the concrete type, soboolfails it while0and1pass. On[False, 0, True, 1]it keeps[0, 1].
def filter_integers(items):
result = []
for item in items:
if isinstance(item, int): # True and False pass here
result.append(item)
return resultLooks 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.
def filter_integers(items):
result = []
for item in items:
if type(item) is int:
result.append(item)
return resultO(n) time, O(k) extra space for the k integers kept.
Common follow-up questions
- What does `True + True` evaluate to, and why? (Checks that the candidate understands `bool` values behave as `1` and `0` in arithmetic.)
- How would you also accept `int` subclasses you trust, but still reject `bool`? (Tests `isinstance(item, int) and not isinstance(item, bool)` as the more extensible form.)
- What changes if the data comes from numpy and holds `numpy.int64` values? (Tests whether the candidate sees that exact-type identity rejects foreign integer types and would need a whitelist.)