Magicsheet logo

Apply Operations on Array to Maximize Sum of Squares

Hard
94.5%
Updated 6/1/2025

Apply Operations on Array to Maximize Sum of Squares

What is this problem about?

The "Apply Operations on Array to Maximize Sum of Squares interview question" is a bitwise optimization problem. You are allowed to pick two numbers in an array and replace them with their bitwise AND and bitwise OR. You can do this any number of times. The goal is to maximize the sum of squares of all elements in the array after the operations.

Why is this asked in interviews?

Sprinklr asks the "Apply Operations on Array to Maximize Sum of Squares coding problem" to test a candidate's understanding of how bitwise operations redistribute "set bits." The sum of squares is maximized when the values in the array are as "spread out" as possible (i.e., some numbers are very large and others are very small).

Algorithmic pattern used

This problem uses the Bit Counting and Greedy pattern.

  1. The Invariant: When you replace (a,b)(a, b) with (aextANDb,aextORb)(a ext{ AND } b, a ext{ OR } b), the total number of set bits at each bit position (0 to 30) remains the same. You are essentially moving "1" bits from one number to another.
  2. The Strategy: To maximize the sum of squares, you want to consolidate as many "1" bits as possible into the same numbers. A larger number has a much larger square (102+02=10010^2 + 0^2 = 100, while 52+52=505^2 + 5^2 = 50).
  3. Implementation:
    • Count how many times each bit (0-30) appears across all numbers in the input.
    • Reconstruct the maximum possible numbers by greedily taking one "1" from each bit-count that is greater than zero.

Example explanation

Array: [3, 5] (Binary: 011, 101)

  • Bit 0: Two 1s.
  • Bit 1: One 1.
  • Bit 2: One 1. Reconstruct to maximize squares:
  • Number 1: Take one 1 from Bit 0, 1, and 2 -> 111 (7).
  • Number 2: Take one 1 from Bit 0 -> 001 (1). Final sum of squares: 72+12=49+1=507^2 + 1^2 = 49 + 1 = 50. (Original was 9+25=349+25=34).

Common mistakes candidates make

  • Attempting Simulation: Trying to actually perform the AND/OR operations on pairs. There are N2N^2 pairs and infinite combinations.
  • Not using Modulo: Forgetting that the result can be very large and needs to be returned modulo 109+710^9 + 7.
  • Incorrect Squares: Squaring the total sum of bits instead of squaring the reconstructed numbers.

Interview preparation tip

Bitwise OR and AND operations often act like "gravity" for bits. OR pulls bits into one number, while AND leaves only the overlap. In optimization problems, "moving all bits to one side" is a common strategy to maximize squares or products.

Similar Questions