Microsoft Interview Question

Given an unsorted array of integers in O(n) time complexity. find the first unrepeated element in that array. For example: A = [1 2 3 3 2 1 4 5 6] the answer is 4.

Interview Answers

Anonymous

Jun 30, 2018

static void Main(string[] args) { int[] myArray = new int[] { 1, 2, 3, 3, 2, 1, 4, 5, 6 }; int? number = null; GetFirstUnRepeatedNumber(myArray, ref number); if (number != null) System.Console.WriteLine(number); } private static void GetFirstUnRepeatedNumber(int[] myArray , ref int? number) { for (int i = 0; i < myArray.Length; i++) { byte counter = 0; for (int j = 0; j < myArray.Length; j++) { if (i == j) continue; if (myArray[i] == myArray[j]) { counter++; break; } } if (counter == 0) { number = myArray[i]; break; } } }

Anonymous

Mar 4, 2020

Use hashmap for each element write it's value as a key and index value. If the element is encountered again update it value to MaxInteger. In the end loop the the array again and store the minimum index this is what you use to return as the answer :)