Magicsheet logo

Beautiful Array

Medium
12.5%
Updated 8/1/2025

Beautiful Array

What is this problem about?

The "Beautiful Array interview question" is a unique construction challenge. An array is considered "beautiful" if for every i<ji < j, there is no kk such that i<k<ji < k < j and A[k]imes2=A[i]+A[j]A[k] imes 2 = A[i] + A[j]. In simpler terms, no three elements in the array form an arithmetic progression. Your task is to return any beautiful array of length nn containing numbers from 1 to nn.

Why is this asked in interviews?

Microsoft, Meta, and Google use the "Beautiful Array coding problem" to test a candidate's ability to think about "Divide and Conquer" in a non-traditional way. It’s not about sorting or searching; it’s about using mathematical properties to build a valid structure. It evaluates whether you can recognize how to preserve a property (no arithmetic progression) while scaling a solution.

Algorithmic pattern used

This problem relies on the Divide and Conquer and Mathematical Transformation patterns.

  1. The Core Property: If an array is beautiful, any linear transformation f(x)=ax+bf(x) = ax + b will also result in a beautiful array.
  2. Odd and Even Split: An arithmetic progression cannot consist of one odd and one even number if their average is not an integer. For example, (Odd+Even)/2(Odd + Even) / 2 is never an integer.
  3. Recursive Step:
    • Split the numbers into Odds (transformed from a beautiful array of size (n+1)/2(n+1)/2) and Evens (transformed from a beautiful array of size n/2n/2).
    • The "Odds" are generated as 2x12x - 1.
    • The "Evens" are generated as 2x2x.
    • Combining them ensures that any A[i]A[i] and A[j]A[j] from different groups cannot have an A[k]A[k] from either group as their average.

Example explanation

n=4n = 4

  1. Start with n=1n=1: [1].
  2. n=2n=2:
    • Odds: 2(1)1=12(1) - 1 = 1.
    • Evens: 2(1)=22(1) = 2.
    • Result: [1, 2].
  3. n=4n=4:
    • Use [1, 2] to generate Odds: 2(1)1=1,2(2)1=32(1)-1=1, 2(2)-1=3. -> [1, 3]
    • Use [1, 2] to generate Evens: 2(1)=2,2(2)=42(1)=2, 2(2)=4. -> [2, 4]
    • Result: [1, 3, 2, 4]. Check: 1,2,31, 2, 3 are present. Average of 1 and 2 is 1.5 (not 3). Average of 1 and 4 is 2.5 (not 3 or 2). No arithmetic progressions!

Common mistakes candidates make

  • Trying Brute Force: Attempting to generate permutations and check the property. This is O(n!)O(n!), which is far too slow for n=1000n=1000.
  • Incorrect Transformation: Using x+1x+1 or x1x-1 instead of 2x2x and 2x12x-1, which fails to separate the numbers into odd and even parity.
  • Complexity: Over-complicating the base cases or merging logic.

Interview preparation tip

When a problem mentions avoiding a specific mathematical relationship (like an arithmetic progression), think about Parity. Splitting a problem into odd and even subsets is a powerful "Divide and Conquer interview pattern" that often simplifies complex constraints.

Similar Questions