Lonely Integer

Sort by

recency

|

941 Discussions

|

  • + 0 comments

    List< Integer> passedNumbers = new ArrayList<>(); for (int i = 0; i a.size(); i++) { if(!passedNumbers.contains(a.get(i))) { passedNumbers.add(a.get(i)); } else { passedNumbers.remove(a.get(i)); } } return passedNumbers.get(0)

  • + 0 comments

    JAVA

    for(Integer n: a){ int frec = Collections.frequency(a, n); if(frec==1){ num=n; } } return num;

  • + 0 comments

    Scala Solution

    def lonelyinteger(a: Array[Int]): Int = {
        // Write your code here)
            a.reduce(_^_)
        }
    
  • + 0 comments

    My Python solution using Mathematical logic:

    def lonelyinteger(a):
        '''
        Mathematical solution
        
        The sum of the elements of a is the sum of the
        doubles of each repeated element, plus the lonely (b)
        sum(a) = sum[2.x] + b
        
        The sum of the unique elements is the sum of all
        the unique elements that are repeated, plus the lonely (b)
        sum(set(a)) = sum[x] + b
        
        Then, 2*sum(set(a)) - sum(a) = b
        
        Time complexity: O(n)
        Space complexity: O(1)
        '''
        
        return 2*sum(set(a)) - sum(a)
    
  • + 0 comments

    group the numbers find the group that has only one element first .Single gets the IGrouping second .Single gets the int from that Grouping.

    return a.GroupBy(i => i).Where(i => i.Count() ==1).Single().Single();