Search⌘ K
AI Features

Solution Review: Finding the First Unique Integer in an Array

Understand how to find the first unique integer in an array using the brute force method. Learn to traverse and compare elements step-by-step and grasp why this approach is less efficient. This lesson prepares you for more optimized solutions using hashing techniques.

We'll cover the following...

Solution: Brute force

C#
namespace chapter_2
{
class Challenge_6
{
//Find First Unique Integer in an Array
//Returns first unique integer from array
static int findFirstUnique(int []arr, int size)
{
//Inside the inner loop, check each index of the outer loop.
//If it's repeated in the array
//If it's not repeated then return this as the first unique integer
bool isRepeated = false;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (arr[i] == arr[j] && i != j)
{
isRepeated = true;
}
} //end of InnerLoop
if (isRepeated == false)
{
return arr[i];
}
isRepeated = false;
} //end of OuterLoop
return -1;
}
static void Main(string[] args)
{
int size = 6;
int []arr = { 2, 54, 7, 2, 6, 54 };
Console.Write( "Array: ");
for (int i = 0; i < size; i++)
Console.Write( arr[i] + " ");
Console.WriteLine("");
int unique = findFirstUnique(arr, size);
Console.WriteLine ("First Unique in an Array: " + unique );
return ;
}
}
}

Start from the first element, and traverse through the whole array by comparing it with all the other elements to see if any element is equal to it. If so, skip to the next element and repeat. If not, then this is the first unique element in the array.

Time complexity

The time complexity of this solution is O(n2 ...