Python coding interview questions: one worked problem
Work through a Python coding interview question with a precise contract, a set-based solution, edge-case tests and an explanation of time and space costs.

On this page
- 1. What exactly should the function return?
- 2. Choose examples that expose different interpretations
- 3. Trace a tempting wrong solution
- 4. Implement a scan that remembers earlier IDs
- 5. Run the expected-result checks
- 6. Explain time and space with their assumptions
- 7. Rehearse the explanation, then change one requirement
- Frequently asked questions
- Sources
Practice Python coding interview questions by fixing the output contract, working through a counterexample and checking your code against explicit expected results. This original exercise finds the event ID whose repeat appears first in a left-to-right scan, with a complete Python solution and tests.
Microsoft’s technical interview guidance emphasizes clarifying ambiguity, planning before implementation, testing and explaining complexity. The sequence below practices those habits. The problem is an editorial practice exercise, not a question attributed to Microsoft or a report of what employers ask most often.
1. What exactly should the function return?
Return the ID whose second occurrence is encountered first while scanning the supplied list from left to right. Ask this question before treating “find the first duplicate” as a complete specification.
For ['A', 'B', 'B', 'A'], the answer is 'B'. Its repeat appears at the third position. Although 'A' appears earlier initially, its repeat comes later, at the fourth position.
Use this complete contract:
- The input is a finite Python list of nonempty built-in strings. An empty list is valid.
- Each complete string is an ID. Compare it exactly as supplied, including case and whitespace.
- Return the string at the earliest position whose value already appeared at an earlier position.
- Return
Noneif no ID repeats. - Preserve the input list, including its order and values.
- Assume the caller does not change the list while the function runs. Invalid inputs are outside this exercise; runtime validation is not required.
'A' and 'a' are different IDs, as are '07' and '7'. Do not lowercase, trim whitespace or parse an ID as a number. Those operations would change the contract.
Python documents None as a value used to represent absence. Here it is our chosen no-result value. Because every valid ID is a string, the caller can distinguish it from a returned ID.
Try stating the rule aloud without saying only “first duplicate.” A precise restatement should let another person predict the answer to the competing-repeat example.
2. Choose examples that expose different interpretations
Choose expected results before looking at the implementation. Otherwise, it is easy to make a test agree with the code’s mistaken interpretation.
| Input | Expected result | What it checks |
|---|---|---|
[] |
None |
No item exists to repeat. |
['A', 'B', 'B', 'A'] |
'B' |
The earliest repeat wins, rather than the earliest original position. |
['A', 'B', 'A', 'B'] |
'A' |
Swapping the repeat order changes the answer. |
['A', 'a'] |
None |
Case-sensitive comparison preserves distinct IDs. |
['07', '7', '07'] |
'07' |
An ID remains a string, including its leading zero. |
['A', 'A '] |
None |
A trailing space remains part of the ID. |
The two competing-repeat cases are especially useful together. A solution that always selects the earliest original value passes the second case but fails the first. A solution that sorts the IDs before scanning can also lose the required order.
Pause here and sketch a solution yourself. Identify what you must remember after reading a prefix of the list. You do not need the number of times every ID appears in the full input; you need to know whether the current ID occurred earlier.
After completing this walkthrough, use the practice question catalog to apply the same contract-first approach to a different prompt. Repeating only this solution can hide whether you can derive the reasoning again.
3. Trace a tempting wrong solution
Counting an ID across the entire list answers a different question. The following function is intentionally wrong for our contract:
def wrong_first_repeated_id(event_ids):
for event_id in event_ids:
if event_ids.count(event_id) > 1:
return event_id
return None
On ['A', 'B', 'B', 'A'], the loop starts with 'A'. The full list contains two copies, so the function returns 'A' immediately. It never reaches the position where 'B' repeats first.
The failure is a definition error, even though the returned value really is a duplicate. The function selects the earliest original value that appears more than once anywhere. Our contract selects the first repeated occurrence encountered during a scan.
Keep this input when correcting the algorithm. Changing only variable names or replacing count() with another full-list frequency lookup would preserve the mistaken selection rule. A useful debugging explanation names the operation that causes the wrong answer, then changes the information used at that point.
4. Implement a scan that remembers earlier IDs
Use a set for the distinct IDs already scanned, and let the list supply the order. Python’s set documentation describes sets as collections of distinct hashable objects without recorded positions or insertion order. The algorithm does not iterate over the set to choose a result.
Save the intentionally wrong function above and this correct function in first_repeat.py. The complete test harness below uses both definitions to reproduce their different results:
def first_repeated_id(event_ids):
seen = set()
for event_id in event_ids:
if event_id in seen:
return event_id
seen.add(event_id)
return None
Check membership before adding. If you add the current ID first, the membership check will succeed even for the first item in a nonempty list.
For the competing-repeat input, the state changes as follows. Set contents below show membership only; their displayed order has no significance.
| Current ID | Previously seen IDs | Action |
|---|---|---|
First 'A' |
Empty | Add 'A'. |
First 'B' |
'A' |
Add 'B'. |
Second 'B' |
'A', 'B' |
Return 'B'. |
Explain correctness through one invariant: just before processing an ID, seen contains exactly the distinct IDs in the already-scanned prefix.
The empty set satisfies that statement before the first item. An unseen ID is added, preserving the statement for the next iteration. An ID already in seen has occurred earlier. Because the scan has not returned before this position, no earlier position was a repeated occurrence. Returning now satisfies the contract. If the loop finishes, no repeat was encountered, so None is correct.
The function reads the list and adds references to a separate set. It does not sort, remove or replace list elements.
5. Run the expected-result checks
Append this harness to the same file after both function definitions. It checks ten valid inputs and compares each input with a copy after execution:
cases = [
([], None),
(["A"], None),
(["A", "B", "C"], None),
(["A", "A"], "A"),
(["A", "B", "B", "A"], "B"),
(["A", "B", "A", "B"], "A"),
(["A", "a"], None),
(["A", "a", "A"], "A"),
(["07", "7", "07"], "07"),
(["A", "A "], None),
]
for event_ids, expected in cases:
before = event_ids[:]
actual = first_repeated_id(event_ids)
if expected is None:
assert actual is None, (event_ids, actual)
else:
assert actual == expected, (event_ids, actual)
assert event_ids == before, "Input was changed"
counterexample = ["A", "B", "B", "A"]
assert wrong_first_repeated_id(counterexample) == "A"
assert first_repeated_id(counterexample) == "B"
print("10 cases passed; input lists unchanged.")
Run it with assertions enabled, without Python’s -O option:
python3 first_repeat.py
Expected output:
10 cases passed; input lists unchanged.
The final two assertions deliberately demonstrate that the wrong and correct functions disagree on the same input. The ten-case loop is the check of required behavior; the wrong function’s assertion records its specific failure.
These examples cover selected boundaries and interpretation mistakes. They are not exhaustive proof or a performance benchmark. The invariant explains the general selection rule, while the executable checks can expose implementation errors against that rule. If an assertion fails, inspect the failing input and actual value before changing the expected answer.
6. Explain time and space with their assumptions
For n IDs of bounded length, the scan takes O(n) time under the usual average-case hash-table assumptions, with O(n) auxiliary storage in the worst input shape. The set can hold up to n distinct IDs when nothing repeats. An early repeat can stop the scan sooner.
Python’s built-in operation complexity reference explicitly concerns CPython’s exact built-in types. It lists average-case constant-time set membership and amortized constant-time addition, subject to hashing and comparison assumptions. “Amortized” accounts for the cost across a sequence of operations, including occasional more expensive resizing.
This is not an unconditional worst-case guarantee for every Python implementation or input. Hash collisions can make operations more expensive. Arbitrarily long strings also add hashing and comparison costs; do not silently treat every string operation as constant-time when ID length can grow.
The function stores references to existing ID strings rather than constructing normalized copies. The O(n) auxiliary bound describes the extra set, not the already-supplied input list. Keep algorithmic storage separate from the test harness, which also makes copies to check preservation.
7. Rehearse the explanation, then change one requirement
Explain the selection rule before reciting the code: “I scan left to right. Before each item, the set contains the earlier IDs. Membership therefore identifies a repeat, and returning immediately selects the earliest repeated occurrence.” Then name the counterexample and the assumptions behind the cost analysis.
Ask a practice partner to change one requirement: return the earliest original ID that eventually repeats. The intentionally wrong function now matches that selection rule, though its repeated full-list counting gives you another efficiency question to investigate. Changing the requirement means revisiting correctness before discussing optimization.
For feedback on your explanation, compare AI practice, peer mocks and coaching and choose a format that lets someone challenge your assumptions. On a fresh problem, write the contract and expected examples before seeing a solution.
For another rehearsal, use Prepin’s role-focused mock interview practice: Practice this interview.
Frequently asked questions
What Python coding interview questions should I practice?
Choose problems that let you explain a requirement, implement a solution and test it. This walkthrough covers one list-and-set problem; it is not a complete Python syllabus or evidence that an employer asks this question. Use the actual role requirements to guide the rest of your preparation.
Can I solve this problem using only a set conversion?
Converting the entire list to a set discards repeated occurrences and their positions. It cannot by itself identify which repeat was encountered first. The solution above preserves the list’s scan order and uses the set only for earlier membership.
Should the function reject invalid inputs?
Runtime validation is outside this exercise’s contract. An API accepting untrusted data would need an explicit decision about accepted types, empty IDs and error behavior. Do not add arbitrary validation rules during an interview without first agreeing on them.
Can I use AI while practicing coding questions?
You can ask a practice tool to challenge your examples or explanation, then attempt the solution yourself. During an actual assessment, follow that assessment’s rules and the employer’s instructions. Our CodeSignal AI-use guide explains why permission depends on the assessment context.
Sources
Prepared with AI assistance. Official sources below were checked on November 20, 2026. The exercise, sample IDs, counterexample and test cases are editorial practice material.
- Microsoft Careers: Technical interviews, undated employer guidance.
- Python: Built-in Types, Set Types, living documentation.
- Python: Built-in Constants, None, living documentation.
- Python: Time complexity of operations on built-in types, living documentation scoped to CPython.
Practice the interview out loud
Run a realistic AI mock interview for your target role and get feedback on every answer.
Start a mock interview →Screen engineers before the first call
Send candidates one link. Prepin runs the technical voice interview and live coding, then gives you a scored report.
See how screening works →