Dataford
Interview QuestionsInterview GuidesExperiencesCoaching
New
Pricing
Get started
Dataford
Popular roles
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Browse
Browse All RolesEvery role hub, from analyst to MLBrowse All CompaniesCompany-specific interview loopsAll Interview GuidesThe full guide library
Top questions by role
Software EngineerData AnalystData ScientistData EngineerBusiness AnalystAI EngineerMachine Learning EngineerProduct Manager
Top questions by skill
SQLPythonStatisticsMachine LearningA/B TestingSystem DesignGenerative AIProduct SenseMetricsBehavioral
Browse all questions →Try a mock interview
Experiences
Practice
Mock InterviewsTimed interview simulations with feedbackCoaching1:1 coaching with people at your target companiesSuccess PathYour 6-week structured planModulesCurated lessons by topicWebinarsTalks from ex-Big Tech data leadsPlaygroundA free-form scratch editor
Learn
BlogInterview strategy and career adviceTech Job Market ReportHiring trends across data and AI rolesFor UniversitiesDataford for career centersAbout DatafordWho we are and how we build
Pricing
Build my plan
Explain Why Code Is Wrong and How to Improve It
00:00
5 left

Explain Why Code Is Wrong and How to Improve It

MediumPython

Problem

Given a piece of code, explain why it is wrong and how it could be improved.

Asked in the technical interview stage. Reported by a hired USAA SWE as part of their interview.

Task

You are given a Python function that is intended to return the first duplicate value in a list, or -1 if no duplicate exists.

def first_duplicate(nums):
    seen = []
    for i in range(len(nums)):
        if nums[i] in seen:
            return nums[i]
        seen.append(nums[i])
    return 0

Write a corrected version of the function and explain what is wrong with the original code.

Input

  • nums: a list of integers

Output

  • Return the first value that appears more than once, or -1 if there is no duplicate.

Requirements

  1. Identify the bug in the return value.
  2. Improve the implementation for better performance.
  3. Preserve the intended behavior of returning the first duplicate encountered during a left-to-right scan.

Constraints

  • 0 <= len(nums) <= 10^5
  • -10^9 <= nums[i] <= 10^9
  • Return the first duplicate encountered during a left-to-right scan
  • Return -1 when no duplicate exists

Function Signature

def first_duplicate(nums):
Interviewer

Your question is Explain Why Code Is Wrong and How to Improve It. Start with the requirements in the Question tab.

Run and submit as often as you like. When you're ready, talk me through your approach or go straight to the code.

You need to log in / sign up to run or submit.
CodePython 3
Sign up free to run your codeLog inLn 2
Run your code to see test output here.