LeetCode 932: Beautiful Array Solution

Master LeetCode problem 932 (Beautiful Array), a medium challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.

932. Beautiful Array

Problem Explanation

Explanation:

To construct a beautiful array of length n, we can use a divide and conquer approach. The idea is to first build two sub-arrays, one containing odd numbers and the other containing even numbers, and then merge these arrays to form the final beautiful array. By doing so, we can ensure that the condition for a beautiful array is satisfied.

  1. Divide the problem by constructing beautiful arrays for odd and even numbers separately.
  2. For odd numbers, we can map a beautiful array of length n to a beautiful array of length (n+1)/2 by doubling each element and subtracting 1.
  3. For even numbers, we can map a beautiful array of length n to a beautiful array of length n/2 by doubling each element.

This recursive process helps in building the beautiful array efficiently.

Time Complexity: O(n)
Space Complexity: O(n)

:

Solution Code

class Solution {
    public int[] beautifulArray(int n) {
        List<Integer> res = new ArrayList<>();
        res.add(1);
        while (res.size() < n) {
            List<Integer> tmp = new ArrayList<>();
            for (int num : res) {
                if (2 * num - 1 <= n) {
                    tmp.add(2 * num - 1);
                }
            }
            for (int num : res) {
                if (2 * num <= n) {
                    tmp.add(2 * num);
                }
            }
            res = tmp;
        }
        return res.stream().mapToInt(i -> i).toArray();
    }
}

Try It Yourself

Loading code editor...

Related LeetCode Problems

Frequently Asked Questions

How to solve LeetCode 932 (Beautiful Array)?

This page provides optimized solutions for LeetCode problem 932 (Beautiful Array) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.

What is the time complexity of LeetCode 932 (Beautiful Array)?

The time complexity for LeetCode 932 (Beautiful Array) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.

Can I run code for LeetCode 932 on DevExCode?

Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 932 in Java, C++, or Python.

Back to LeetCode Solutions