Beautiful Array

medium math divide and conquer recursion

Problem

An array nums of length n is beautiful if it is a permutation of the integers 1..n and there is no triple of indices i < k < j with 2·nums[k] == nums[i] + nums[j] (no element is the average of two elements flanking it). For a given n, return any beautiful array.

Inputn = 4
Output[1, 3, 2, 4]
All odd values come before all even values, so no element equals the average of one earlier and one later element.

def beautiful_array(n):
    res = [1]
    while len(res) < n:
        odds = [2 * x - 1 for x in res]
        evens = [2 * x for x in res]
        res = [x for x in odds + evens if x <= n]
    return res
function beautifulArray(n) {
  let res = [1];
  while (res.length < n) {
    const odds = res.map(x => 2 * x - 1);
    const evens = res.map(x => 2 * x);
    res = odds.concat(evens).filter(x => x <= n);
  }
  return res;
}
class Solution {
    public int[] beautifulArray(int n) {
        List<Integer> res = new ArrayList<>();
        res.add(1);
        while (res.size() < n) {
            List<Integer> next = new ArrayList<>();
            for (int x : res) if (2 * x - 1 <= n) next.add(2 * x - 1);
            for (int x : res) if (2 * x <= n) next.add(2 * x);
            res = next;
        }
        return res.stream().mapToInt(Integer::intValue).toArray();
    }
}
vector<int> beautifulArray(int n) {
    vector<int> res = {1};
    while ((int)res.size() < n) {
        vector<int> next;
        for (int x : res) if (2 * x - 1 <= n) next.push_back(2 * x - 1);
        for (int x : res) if (2 * x <= n) next.push_back(2 * x);
        res = next;
    }
    return res;
}
Time: O(n log n) Space: O(n)