I have come up with a recursive method to identify a unique item in an array (where all other items appear in pairs next to each other). I am wondering if it's possible to achieve the same result without recursion, perhaps using a while loop. Additionally, I am curious whether utilizing a loop within the function consumes less memory compared to recursion?
Solution at present:
function findSingularElement(arr, low, high) {
// base cases
if (arr.length < 3) return console.log('Invalid length of array.');
if (low > high) return;
if (low == high) return console.log(arr[low]);
var mid = low + (high - low) / 2;
if (mid % 2 === 0) {
if (arr[mid] == arr[mid + 1]) {
return findSingularElement(arr, mid + 2, high);
} else {
return findSingularElement(arr, low, mid);
}
} else {
if (arr[mid] == arr[mid - 1]) {
return findSingularElement(arr, mid + 1, high);
} else {
return findSingularElement(arr, low, mid - 1);
}
}
}
var array = [1, 1, 3, 3, 4, 5, 5, 7, 7, 8, 8];
Appreciate any insights.