DSAPROB18 - Editorial

Problem Link - Chef Square Tile Problem

Problem Statement:
The chef buys square tiles of size 1*1 from N shops. The i-th shop sells a[i] tiles. The chef wants to determine if he can create a larger square area using all the tiles he has purchased.

Approach:
To check if a number is a perfect square, we can use a binary search method. This approach efficiently narrows down the possible integer values whose square could equal the target sum. We start with a range of potential values and check the midpoint square until we find the target or exhaust the range.

Step-by-step process:

  1. Initialize Two Pointers:
    Set left to 1 and right to 10^9 to define the search range for potential square roots.

  2. Binary Search Loop:
    While left is less than or equal to right:

    • Calculate the midpoint mid as left + (right - left) / 2.
    • Compute sq as mid * mid.
  3. Check for Equality:

    • If sq equals sum, return true.
    • If sq is less than sum, move left to mid + 1.
    • If sq is greater than sum, move right to mid - 1.
  4. Exit Condition:
    If no perfect square is found, return false.

Time Complexity:
O(log(sum)), where sum is the total of the input integers, since we are performing a binary search up to the square root of the sum.

Space Complexity:
O(1) since we are using a fixed amount of extra space regardless of the input size.