LeetCode 667: Beautiful Arrangement II Solution
Master LeetCode problem 667 (Beautiful Arrangement II), 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.
Problem Explanation
Explanation
To solve this problem, we can construct the array in such a way that we have a difference of 1 for the first k+1 elements and then the rest of the elements are in ascending order to meet the condition of having k distinct differences. This approach guarantees that the absolute differences between adjacent elements have exactly k distinct integers.
Solution Code
class Solution {
public int[] constructArray(int n, int k) {
int[] result = new int[n];
int left = 1;
int right = n;
for (int i = 0; i < k; i++) {
result[i] = (i % 2 == 0) ? left++ : right--;
}
int index = k;
for (int i = right; i >= left; i--) {
result[index++] = i;
}
return result;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 667 (Beautiful Arrangement II)?
This page provides optimized solutions for LeetCode problem 667 (Beautiful Arrangement II) 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 667 (Beautiful Arrangement II)?
The time complexity for LeetCode 667 (Beautiful Arrangement II) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 667 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 667 in Java, C++, or Python.