Adobe Interview Question

How to find the first non-repeating element in an array?

Interview Answer

Anonymous

Oct 6, 2020

This question is usually asked by many companies in their technical/coding round. You can implement this code in any language but I prefer python. #Code Start def find_first_non_repeating_element(A): """ This is the linear solution of non-repeating element interview question. If no non-repeating element is there in the given array this function will return -1. You can use customize if you wish to do so. In this code I have used a python dictionary which is same as Hashmap of C++/Java. Data Structures like dictionary works on a key-value pair basis. Key acts as a reference pointer and value acts as a container to hold/store a result. This is same as indexes in Array. Here main logic is: Iterate over given array and compare each element with dictionary keys if that element is with the key list means the element is repeating. In such case just increase it's container value by one. If element is not matching with any key of dictionary than add that element as a new key in the dictionary with value 1. Once for loop is completed we will check whether dictionary contains any key whose value is still 1? If yes means that element is non-repeating and return the corresponding key. If dictionary doesn't contain any key with value means no non-repeating element in the given array. Hence return -1. :param A: :return: """ temp_repo = {} for i in range(0, len(A)): if A[i] in temp_repo.keys(): temp_repo[A[i]] = temp_repo[A[i]] + 1 else: temp_repo[A[i]] = 1 if 1 in temp_repo.values(): return list(temp_repo.keys())[list(temp_repo.values()).index(1)] else: return -1 A = [1, 3, 2, 4, 5, 1, 3, 2, 6] print(find_first_non_repeating_element(A))