Beautiful Array - Problem

An array nums of length n is beautiful if:

  • nums is a permutation of the integers in the range [1, n]
  • For every 0 <= i < j < n, there is no index k with i < k < j where 2 * nums[k] == nums[i] + nums[j]

Given the integer n, return any beautiful array nums of length n. There will be at least one valid answer for the given n.

Input & Output

Example 1 — Small Case
$ Input: n = 4
Output: [1,3,2,4]
💡 Note: This is a beautiful array because for any i < j, there's no k with i < k < j where 2*nums[k] = nums[i] + nums[j]. For instance, checking all triplets: no middle element equals the average of two others.
Example 2 — Base Case
$ Input: n = 1
Output: [1]
💡 Note: Single element array is always beautiful since there are no triplets to violate the condition.
Example 3 — Larger Array
$ Input: n = 5
Output: [1,5,3,2,4]
💡 Note: Built using divide and conquer: odds from n=3 become [1,5,3], evens from n=2 become [2,4], combined to form beautiful array of length 5.

Constraints

  • 1 ≤ n ≤ 1000
  • It's guaranteed that for the given n, at least one valid answer exists.

Visualization

Tap to expand
Beautiful Array Problem INPUT n = 4 Need permutation of [1, n] Available Numbers: 1 2 3 4 Constraint: No i < k < j where 2*nums[k] == nums[i]+nums[j] Example: [1,2,3] is BAD 2*2 = 1+3 (arithmetic seq) ALGORITHM STEPS 1 Divide and Conquer Split into odd/even groups 2 Odd Numbers First Place: 1, 3 (left side) 3 Even Numbers After Place: 2, 4 (right side) 4 Recursively Apply Same rule within groups Transformation: [1,2,3,4] [1,3] + [2,4] odd+odd != 2*even even+even != 2*odd FINAL RESULT Beautiful Array: 1 3 2 4 [0] [1] [2] [3] Verification: OK Check all triplets (i,k,j): (0,1,2): 2*3 != 1+2 OK (0,1,3): 2*3 != 1+4 OK (0,2,3): 2*2 != 1+4 OK Output: [1, 3, 2, 4] Key Insight: The divide-and-conquer approach works because odd + odd = even, and even + even = even. So 2*nums[k] can never equal nums[i]+nums[j] when one side has all odds and other has all evens. Time Complexity: O(n log n) | Space Complexity: O(n) TutorialsPoint - Beautiful Array | Divide and Conquer Approach
Asked in
Google 15 Facebook 8
18.5K Views
Low Frequency
~25 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen