700662. Magical Number

Easy

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:

  1. Sort the array arr in ascending order.
  2. Initialize two pointers, left and right, to the start and end of the sorted array, respectively.
  3. While left is less than or equal to right:
    • Calculate the midpoint mid of the range [left, right].
    • Check if the number at index mid has exactly two distinct digits.
    • If it does, return this number as the magical number.
    • If not, update left and/or right based on whether the magical number is likely to be in the left or right half of the range.
  4. 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

View on GeeksforGeeks
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];
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.