Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 494053
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 13, 20262026-05-13T05:27:43+00:00 2026-05-13T05:27:43+00:00

Given n enumerables of the same type that return distinct elements in ascending order,

  • 0

Given n enumerables of the same type that return distinct elements in ascending order, for example:

IEnumerable<char> s1 = "adhjlstxyz";
IEnumerable<char> s2 = "bdeijmnpsz";
IEnumerable<char> s3 = "dejlnopsvw";

I want to efficiently find all values that are elements of all enumerables:

IEnumerable<char> sx = Intersect(new[] { s1, s2, s3 });

Debug.Assert(sx.SequenceEqual("djs"));

“Efficiently” here means that

  1. the input enumerables should each be enumerated only once,
  2. the elements of the input enumerables should be retrieved only when needed, and
  3. the algorithm should not recursively enumerate its own output.

I need some hints how to approach a solution.


Here is my (naive) attempt so far:

static IEnumerable<T> Intersect<T>(IEnumerable<T>[] enums)
{
    return enums[0].Intersect(
        enums.Length == 2 ? enums[1] : Intersect(enums.Skip(1).ToArray()));
}

Enumerable.Intersect collects the first enumerable into a HashSet, then enumerates the second enumerable and yields all matching elements.
Intersect then recursively intersects the result with the next enumerable.
This obviously isn’t very efficient (it doesn’t meet the constraints). And it doesn’t exploit the fact that the elements are sorted at all.


Here is my attempt to intersect two enumerables. Maybe it can be generalized for n enumerables?

static IEnumerable<T> Intersect<T>(IEnumerable<T> first, IEnumerable<T> second)
{
    using (var left = first.GetEnumerator())
    using (var right = second.GetEnumerator())
    {
        var leftHasNext = left.MoveNext();
        var rightHasNext = right.MoveNext();

        var comparer = Comparer<T>.Default;

        while (leftHasNext && rightHasNext)
        {
            switch (Math.Sign(comparer.Compare(left.Current, right.Current)))
            {
            case -1:
                leftHasNext = left.MoveNext();
                break;
            case 0:
                yield return left.Current;
                leftHasNext = left.MoveNext();
                rightHasNext = right.MoveNext();
                break;
            case 1:
                rightHasNext = right.MoveNext();
                break;
            }
        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-13T05:27:43+00:00Added an answer on May 13, 2026 at 5:27 am

    OK; more complex answer:

    public static IEnumerable<T> Intersect<T>(params IEnumerable<T>[] enums) {
        return Intersect<T>(null, enums);
    }
    public static IEnumerable<T> Intersect<T>(IComparer<T> comparer, params IEnumerable<T>[] enums) {
        if(enums == null) throw new ArgumentNullException("enums");
        if(enums.Length == 0) return Enumerable.Empty<T>();
        if(enums.Length == 1) return enums[0];
        if(comparer == null) comparer = Comparer<T>.Default;
        return IntersectImpl(comparer, enums);
    }
    public static IEnumerable<T> IntersectImpl<T>(IComparer<T> comparer, IEnumerable<T>[] enums) {
        IEnumerator<T>[] iters = new IEnumerator<T>[enums.Length];
        try {
            // create iterators and move as far as the first item
            for (int i = 0; i < enums.Length; i++) {
                if(!(iters[i] = enums[i].GetEnumerator()).MoveNext()) {
                    yield break; // no data for one of the iterators
                }
            }
            bool first = true;
            T lastValue = default(T);
            do { // get the next item from the first sequence
                T value = iters[0].Current;
                if (!first && comparer.Compare(value, lastValue) == 0) continue; // dup in first source
                bool allTrue = true;
                for (int i = 1; i < iters.Length; i++) {
                    var iter = iters[i];
                    // if any sequence isn't there yet, progress it; if any sequence
                    // ends, we're all done
                    while (comparer.Compare(iter.Current, value) < 0) {
                        if (!iter.MoveNext()) goto alldone; // nasty, but
                    }
                    // if any sequence is now **past** value, then short-circuit
                    if (comparer.Compare(iter.Current, value) > 0) {
                        allTrue = false;
                        break;
                    }
                }
                // so all sequences have this value
                if (allTrue) yield return value;
                first = false;
                lastValue = value;
            } while (iters[0].MoveNext());
        alldone:
            ;
        } finally { // clean up all iterators
            for (int i = 0; i < iters.Length; i++) {
                if (iters[i] != null) {
                    try { iters[i].Dispose(); }
                    catch { }
                }
            }
        }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

According to the answer given for the same question: How to check IEnumerable<DataRow> returns
Given two IEnumerable s of the same size, how can I convert it to
Given that the web application doesn't have su privileges, I'd like to execute a
Given that an input String may be specified as follows: read(xpath(‘...’)) or xpath(‘...’) or
Given I have a IEnumerable (e) and a single value of T (t). What
I'm looking for a function that will generate an alphanumeric hash. Given a source
Given that map() is defined by Enumerable , how can Hash#map yield two variables
I have a utility function that enumerates all values of a type that is
Given this method to work on a HTML page in a webbrowser: bool semaphoreForDocCompletedEvent;
Given an NSMutableArray of dynamic CGPoint s, what is the fastest and most efficient

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.