Skip to main content

Practice · 2 of 4

HashSet Against the Quadratic

CHALLENGE
Difficulty: intermediate+25 XP

DuplicateFinder.HasAny(List<int>, List<int>) scans the whole List per candidate — O(n·m). Rewrite as Solution.HasAny(IEnumerable<int> haystack, List<int> needles) that puts the haystack in a System.Collections.Generic.HashSet<int> once (one enumeration) and tests each needle in ~O(1): - true iff at least one needle is present, - empty needles → false, empty haystack → false, - duplicates in either side are irrelevant. ``csharp public static class Solution { public static bool HasAny( System.Collections.Generic.IEnumerable<int> haystack, System.Collections.Generic.List<int> needles); } // provided: public sealed class CountingProbe { public int Hits; public IEnumerable<int> Src(params int[] xs); } ``

Back to lesson: Practice: Performance Practice: Build, Pick, Materialize