Open In App

Finding the Missing Digit in the Largest Perfect Square

Last Updated : 29 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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:

C++




#include <bits/stdc++.h>
 
using namespace std;
 
// Define a function to find the missing digit in the
// largest perfect square.
int find_missing_digit_largest_square(string number)
{
    // Variable to store the index of
    // underscore in the original string
    int underscore_pos = number.find('_');
    // Iterate through all possible digits (9 to 0)
    for (int digit = 9; digit >= 0; digit--) {
        number[underscore_pos] = '0' + digit;
 
        // Convert the modified string to an integer.
        int num = stoi(number);
 
        // Calculate the square root of the
        // resulting number.
        int root = sqrt(num);
 
        // Check if the number is a perfect square
        if (root * root == num) {
            return digit;
        }
    }
    return -1;
}
// Driver Code
int main()
{
    int res = find_missing_digit_largest_square("14_");
    if (res != -1)
        cout << res << endl;
    else
        cout << "No perfect square possible\n";
    return 0;
}


Java




import java.util.Scanner;
 
public class Main {
    // Define a function to find the missing digit in the largest perfect square.
    public static int findMissingDigitLargestSquare(String number) {
        // Variable to store the index of underscore in the original string
        int underscorePos = number.indexOf('_');
         
        // Iterate through all possible digits (9 to 0)
        for (int digit = 9; digit >= 0; digit--) {
            StringBuilder modifiedNumber = new StringBuilder(number);
            modifiedNumber.setCharAt(underscorePos, (char)('0' + digit));
 
            // Convert the modified string to an integer.
            int num = Integer.parseInt(modifiedNumber.toString());
 
            // Calculate the square root of the resulting number.
            int root = (int) Math.sqrt(num);
 
            // Check if the number is a perfect square.
            if (root * root == num) {
                return digit;
            }
        }
        return -1;
    }
 
    // Driver Code
    public static void main(String[] args) {
        int res = findMissingDigitLargestSquare("14_");
        if (res != -1) {
            System.out.println(res);
        } else {
            System.out.println("No perfect square possible");
        }
    }
}
 
 
// This code is contributed by rambabuguphka


Python3




# Python Code for the above approach:
 
import math
 
# Define a function to find the missing digit
# in the largest perfect square.
def find_missing_digit_largest_square(number):
 
    # Iterate through all possible digits (9 to 0).
    for digit in range(9, -1, -1):
        # Replace the underscore (_) with the
        # current digit in the number.
        num_str = str(number).replace('_', str(digit))
 
        # Calculate the square root of the
        # resulting number.
        root = int(math.sqrt(int(num_str)))
 
        # Check if the number is a perfect square
        if root * root == int(num_str):
            return digit
 
    # Return -1 if no perfect square is possible
    return -1
 
 
# Example usage:
missing_digit = find_missing_digit_largest_square("16_")
 
# Check if a missing digit was found.
if missing_digit != -1:
    print(missing_digit)
else:
    print("No perfect square possible")


C#




// C# Implementation:
using System;
 
namespace MissingDigitLargestSquare
{
    class Program
    {
        // Define a function to find the missing digit in the largest perfect square.
        static int FindMissingDigitLargestSquare(string number)
        {
            // Variable to store the index of underscore in the original string
            int underscorePos = number.IndexOf('_');
 
            // Convert the string to a char array
            char[] modifiedNumber = number.ToCharArray();
 
            // Iterate through all possible digits (9 to 0)
            for (int digit = 9; digit >= 0; digit--)
            {
                modifiedNumber[underscorePos] = (char)('0' + digit);
 
                // Convert the modified char array back to a string.
                string modifiedString = new string(modifiedNumber);
 
                // Convert the modified string to an integer.
                int num = int.Parse(modifiedString);
 
                // Calculate the square root of the resulting number.
                int root = (int)Math.Sqrt(num);
 
                // Check if the number is a perfect square.
                if (root * root == num)
                {
                    return digit;
                }
            }
            return -1;
        }
 
        // Driver Code
        static void Main(string[] args)
        {
            int res = FindMissingDigitLargestSquare("14_");
            if (res != -1)
            {
                Console.WriteLine(res);
            }
            else
            {
                Console.WriteLine("No perfect square possible");
            }
        }
    }
}
 
// This code is contributed by Tapesh(tapeshdua420)


Javascript




// Define a function to find the missing digit in the
// largest perfect square.
function findMissingDigitLargestSquare(number) {
    // Find the index of the underscore
    // in the original string
    const underscorePos = number.indexOf('_');
   
    // Iterate through all possible digits (9 to 0)
    for (let digit = 9; digit >= 0; digit--) {
        number = number.substring(0, underscorePos) +
        digit + number.substring(underscorePos + 1);
     
        // Convert the modified string to an integer.
        const num = parseInt(number);
         
        // Calculate the square root of the resulting number.
        const root = Math.sqrt(num);
         
        // Check if the number is a perfect square
        if (root === Math.floor(root)) {
            return digit;
        }
    }
    return -1;
}
 
// Driver Code
 
const res = findMissingDigitLargestSquare("14_");
if (res !== -1) {
    console.log(res);
}
else {
    console.log("No perfect square possible");
}


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)



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads