FastPrepPerfect Squares Matching a Pattern

Perfect Squares Matching a Pattern

Nielsen logoNielsen● MediumINTERNOA

Problem statement

You are given a string pattern made of digits and underscores (_). Each underscore can stand for any one digit from 0 to 9.

Return all positive perfect squares that match pattern in ascending order. A matching number must:

  • Have exactly pattern.length digits.
  • Use the given digit at every position that is not an underscore.
  • Have no leading zero.

Return an empty array if no square matches. Zero is not a valid result.

Function

findMatchingSquares(pattern: String) → long[]

Examples

Example 1

pattern = "1_0_5"return = [11025]

11025 = 105 * 105. It has five digits and matches 1_0_5. No other positive perfect square matches this pattern.

Example 2

pattern = "12_4_9"return = [120409,127449]
  • 120409 = 347 * 347.
  • 127449 = 357 * 357.

These are the two matching squares, listed in ascending order.

Example 3

pattern = "_"return = [1,4,9]

The positive one-digit squares are 1, 4, and 9. Zero is excluded.

Constraints

  • 1 <= pattern.length <= 13
  • pattern contains only digits 0 to 9 and underscores (_).
  • Every matching value is at most 10^13 - 1 and fits in a signed 64-bit integer.
  • For interactive practice, pattern has at most 1000 matching positive perfect squares. This practice limit is not stated in the source.

More Nielsen problems

See Nielsen hiring insights
Saved
public long[] findMatchingSquares(String pattern) {
    // write your code here
}
Checking account…