Ad

Given two Arrays a and b, Return True if arrays contain common item, else false

//Given 2 Arrays, Return True if arrays contain common item, else false.
//e.g a= ['a','b','g','c'] and b =['z','e','c'] returns true
// naive approach, loop through first array, with each item in a, loop through b and compare item to 
//each item in b returning true if a match is found or false.
//input : 2 arrays
//output: bool
using System.Collections.Generic;
public class Kata{
  public static bool ContainsCommonItem(char[] a, char[] b){ //naive O(a*b)
    for(int i=0;i<a.Length;i++)
      for(int j=0; j< b.Length; j++)
        if(a[i]==b[j])
          return true;
    return false;
  }
  public static bool ContainsCommonItemBetter(char[] a,char[]b){
    
    HashSet<char> items = new HashSet<char>();
    
    foreach(char item in a)
      items.Add(item);
    for (int i =0; i< b.Length; i++)
      if (items.Contains(b[i]))
        return true;
    return false;
  }
    
}