VOOZH about

URL: https://www.geeksforgeeks.org/dsa/finding-the-missing-digit-in-the-largest-perfect-square/

⇱ Finding the Missing Digit in the Largest Perfect Square - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Finding the Missing Digit in the Largest Perfect Square

Last Updated : 29 Nov, 2023

Given a perfect square number with one missing digit represented by an underscore (_). Find the missing digit that when inserted, creates the largest perfect square.

Examples:

Input: "14_"
Output: 4
Explanation: The missing digit 4 makes the largest perfect square, 144.

Input: 6_25
Output: 1
Explanation: The missing digit 1 makes the largest perfect square, 6125.

Approach: The problem can be solved using the following approach:

Iterate through all possible digits in reverse order (9 to 0) and replace the underscore with the current digit, calculate the square root of the resulting number, and check if it is a perfect square. We have iterated in reverse order (9 to 0) because we want to have the largest perfect square.

Steps to solve the problem:

  • Initialize variable missing_digit to -1.
  • Iterate through digits from 9 to 0.
  • For each digit, replace the underscore in the input number with the current digit.
  • Calculate the square root of the modified number.
  • If the square root is an integer, return the digit.

Below is the implementation of the approach:


Output
4

Time Complexity: O(10 * sqrt(N)), where N is the largest number which can be formed during the check for the digits.
Auxiliary Space: O(1)

Comment
Article Tags: