Efficient algorithm to determine if two sets of numbers are disjoint

后端 未结 4 1891
生来不讨喜
生来不讨喜 2020-12-21 11:07

Practicing for software developer interviews and got stuck on an algorithm question.

Given two sets of unsorted integers with array of length m and other of          


        
4条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-21 11:24

    Using a datastructure that has O(1) lookup/insertion you can easily insert all elements of first set.

    Then foreach element in second set, if it exists not disjoint, otherwise it is disjoint

    Pseudocode

    function isDisjoint(list1, list2)
        HashMap = new HashMap();
        foreach( x in list1)
            HashMap.put(x, true);
    
        foreach(y in list2)
            if(HashMap.hasKey(y))
                 return false;
        return true;
    

    This will give you an O(n + m) solution

提交回复
热议问题