Dataford
Interview QuestionsInterview GuidesExperiencesMock InterviewsPricing
Get started

Common Elements From Two Lists

EasyPython00:00
Practice interviewer
In session
5 left
00:00

Your question is Common Elements From Two Lists. Start with the requirements on the right.

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.

Problem

Exiger DDI may compare supplier or entity identifiers from two screening results. Given two lists of values, return the unique values that occur in both lists, preserving the order in which they first appear in the first list.

Formal Specification

Implement common_elements(list1, list2):

  1. list1 and list2 are lists of integers.
  2. Return a new list containing each shared value exactly once.
  3. Preserve the order from list1.
  4. Do not modify either input list.
  5. Return an empty list when the lists have no common values.

Examples

Example 1

Input: list1 = [4, 2, 7, 2, 9], list2 = [8, 2, 4, 2]

Output: [4, 2]

Explanation: 4 and 2 occur in both lists. The result follows their first appearance in list1, and the duplicate 2 is returned once.

Example 2

Input: list1 = [5, 1, 3], list2 = [7, 8]

Output: []

Explanation: The lists contain no shared values.

Constraints

  • 0 <= len(list1), len(list2) <= 100,000
  • -10^9 <= list1[i], list2[i] <= 10^9
  • Inputs may contain duplicates.
  • The output must contain no duplicates.

Constraints

  • 0 <= len(list1), len(list2) <= 100,000
  • -10^9 <= list1[i], list2[i] <= 10^9
  • Inputs may contain duplicate values
  • The output must contain each common value at most once
  • Neither input list may be modified

Function Signature

def common_elements(list1, list2):
Your solutionPython 3
You need to log in / sign up to run or submit.
Run your code to see test output