Utility Function: Common Elements Between Two Lists

Easy ⏱ 8 min 88% acceptance ★★★★★ 4.6
Write a function common_elements(list_a, list_b) that returns a sorted list of the distinct values that appear in both list_a and list_b.

Examples

Example 1
Input
common_elements([1, 2, 3, 4], [3, 4, 5])
Output
[3, 4]
Explanation

3 and 4 are the only values present in both lists.

Example 2
Input
common_elements([1, 2], [3, 4])
Output
[]
Explanation

No overlap between the two lists.

Constraints

  • Result must contain no duplicates and be sorted ascending.

Topics

Functionsutility functions

Companies

CiscoHCLTech

Hints

Hint 1

Convert both lists to sets and use the & (intersection) operator.

Hint 2

Wrap the result in sorted(...) to get a sorted list back.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.