700662. Magical Number
Magical Number
Summary
This problem, "Magical Number", involves finding a specific number within an array using binary search. The key concept involved is arrays and binary search.
Detailed Explanation
Given an unsorted array arr of integers, we need to find the magical number x. The magical number is defined as the first occurrence of any number in the array that has exactly two distinct digits (0-9). If no such number exists, return -1.
To solve this problem, we can use a binary search approach. First, we sort the array arr in ascending order. Then, we iterate through the sorted array using a binary search algorithm to find the first occurrence of any number that has exactly two distinct digits.
Here's a step-by-step breakdown of the solution:
- Sort the array
arrin ascending order. - Initialize two pointers,
leftandright, to the start and end of the sorted array, respectively. - While
leftis less than or equal toright:- Calculate the midpoint
midof the range[left, right]. - Check if the number at index
midhas exactly two distinct digits. - If it does, return this number as the magical number.
- If not, update
leftand/orrightbased on whether the magical number is likely to be in the left or right half of the range.
- Calculate the midpoint
- If no magical number is found after iterating through the entire array, return -1.
Time complexity: O(log n), where n is the size of the input array. Space complexity: O(1), as we only use a constant amount of space to store the pointers and midpoint.
Optimized Solutions
Java
public int magicalNumber(int[] arr) {
Arrays.sort(arr);
int left = 0, right = arr.length - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (hasTwoDistinctDigits(arr[mid])) {
return arr[mid];
}
if (arr[mid] < 10 || arr[mid] > 99) {
left = mid + 1;
} else {
right = mid - 1;
}
}
return -1;
}
private boolean hasTwoDistinctDigits(int num) {
int digits[] = Integer.toString(num).chars().distinct().toArray();
return digits.length == 2 && digits[0] != digits[1];
}