Find distinct common array values
Return the distinct values found in both integer arrays, preserving their first-occurrence order in the first array.
Course progress
Problem 61 of 100
Example → approach → runnable solution
Worked example
See the problem in action
Trace a concrete input through to the verified result.
Example input
first = [4, 2, 4, 7, 1]; second = [2, 9, 4, 2]
Expected output
4 2
What is happening?
4 and 2 occur in both arrays. Their order follows the first array, and repeated appearances are omitted.
Solution strategy
Build the right mental model
Store the second array in a set, then scan the first array and emit a value only when it is present and has not already been emitted.
Core concepts
arrays · hash set
Complexity
Average time O(n + m), space O(m + k).
Runnable solution
Learn from working code
Compare languages, copy the code, or open it in the compiler.
Complete C# solution for distinct-array-intersection
using System;
using System.Collections.Generic;
class Program
{
static List<int> Intersection(int[] first, int[] second)
{
var available = new HashSet<int>(second);
var emitted = new HashSet<int>();
var result = new List<int>();
foreach (int number in first)
if (available.Contains(number) && emitted.Add(number)) result.Add(number);
return result;
}
static void Main()
{
Console.WriteLine(string.Join(" ", Intersection(
new[] { 4, 2, 4, 7, 1 }, new[] { 2, 9, 4, 2 })));
}
}Knowledge check
Questions students often ask
What is the main idea behind find distinct common array values?
Store the second array in a set, then scan the first array and emit a value only when it is present and has not already been emitted.
What is the time and space complexity of this solution?
Average time O(n + m), space O(m + k).
Do all language tabs solve the same problem?
Yes. Every program uses the same example and produces the verified output shown on this page. The syntax and a few language-specific data structures differ.