Skip to content
Search lessons, topics, tests…
Esc

    ↑ ↓ moveEnter openEsc close

    Coding problem

    First, FirstOrDefault or Single?

    MediumAbout 25 minFull AccessLearn it: First, Last, ElementAt and Single: When They Are O(1) and When O(n)

    The task

    Sign-in looks up the account for an email address. An email must belong to one account only, so two accounts with the same email mean the data is broken, and sign-in must stop instead of picking one.

    Complete FindByEmail(List<Account> accounts, string email). Account is a record with an Id and an Email. Emails match ignoring letter case, and otherwise the whole address must match. Return the account whose Email matches email; return null when no account matches; and throw an InvalidOperationException when two or more accounts match. The list, its accounts and the emails are never null.

    Signature

    public record Account(int Id, string Email);
    public static Account? FindByEmail(List<Account> accounts, string email)

    Examples

    • accounts [(1, "amy@x.com"), (2, "ben@x.com")], email "BEN@x.com" → (2, "ben@x.com"). Emails match ignoring letter case, and exactly one account has this one.
    • accounts [(1, "amy@x.com")], email "zoe@x.com" → null. No account has that email.

    Limits: Up to 500,000 accounts.

    The tests check: one match, no match, two matches throwing, an empty list, letter case ignored, two matches that differ only in letter case, an address that only starts like the email, a match at the end of the list, and 500,000 accounts in time.

    Hints

      Your code

      C#Solution.csLoading the editor…

      Already included: using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Http; using System.Threading; using System.Threading.Tasks;

      public record Account(int Id, string Email);
      
      public static class Solution
      {
          // The account with this email (letter case ignored); null for none; InvalidOperationException for two or more.
          public static Account? FindByEmail(List<Account> accounts, string email)
          {
              throw new NotImplementedException();
          }
      }

      This problem comes with TechInterviewNotes Full Access

      Unlock all paid content on TechInterviewNotes.