Given two arrays of postive integers, the second formed by shuffling the first and removing any random item from it, find the missing item.

Let’s write a code to solve the above problem in order of n i.e. O(N) using groovy.

To solve the above problem we will use hasmap to maintain a count of each item from the second array, them again iterate over the first array and return the item if not found or count equal to 0 else decrement the count if item was already present.

def map = [:] // shorhand to define hashmap
def missingElement = {arr1,arr2->

for(item in arr2){
    map[item] = (map[item]?: 0) + 1 // groovy way of null check using elvis operator
}

for(item in arr1){
    if(!map[(item)]){
      return item
    }else{
    map[(item)] = map[item] -1 
    }
}

}
def result = missingElement([1,2,4,5,6,7],[1,2,4,6,7])
println result