Here, We see Beautiful Arrangement II LeetCode Solution. This Leetcode problem is done in many programming languages like C++, Java, JavaScript, Python, etc. with different approaches.
List of all LeetCode Solution
![Beautiful Arrangement II LeetCode Solution](https://i0.wp.com/totheinnovation.com/wp-content/uploads/2024/02/LeetCode-Problem-Solution.png?resize=200%2C200&ssl=1)
Beautiful Arrangement II LeetCode Solution
Table of Contents
Problem Statement
Given two integers n and k, construct a list answer that contains n different positive integers ranging from 1 to n and obeys the following requirement:
- Suppose this list is answer = [a1, a2, a3, … , an], then the list [|a1 – a2|, |a2 – a3|, |a3 – a4|, … , |an-1 – an|] has exactly
k
distinct integers.
Return the list answer. If there multiple valid answers, return any of them.
Example 1:
Input: n = 3, k = 1
Output: [1,2,3]
Explanation: The [1,2,3] has three different positive integers ranging from 1 to 3, and the [1,1] has exactly 1 distinct integer: 1
Example 2:
Input: n = 3, k = 2
Output: [1,3,2]
Explanation: The [1,3,2] has three different positive integers ranging from 1 to 3, and the [2,1] has exactly 2 distinct integers: 1 and 2.
Beautiful Arrangement II Solution C++
class Solution {
public:
vector<int> constructArray(int n, int k) {
int diff = n - k;
int lo = 1;
int hi = n;
vector<int> out;
int i = 0;
while(i < diff){
out.push_back(lo);
lo++;
i++;
}
bool flag = true;
for(int i = out.size() ; i < n ; i++){
if(flag){
out.push_back(hi);
hi--;
flag = false;
}
else{
out.push_back(lo);
lo++;
flag = true;
}
}
return out;
}
};
Code language: PHP (php)
Beautiful Arrangement II Solution Java
class Solution {
public int[] constructArray(int n, int k) {
int diff = n - k;
int lo = 1;
int hi = n;
int[] out = new int[n];
int i = 0;
while(i < diff){
out[i] = lo;
lo++;
i++;
}
boolean flag = true;
for( ; i < n ; i++){
if(flag){
out[i] = hi;
hi--;
flag = false;
}
else{
out[i] = lo;
lo++;
flag = true;
}
}
return out;
}
}
Code language: PHP (php)
Beautiful Arrangement II Solution JavaScript
var constructArray = function(n, k) {
let ans = new Array(n)
for (let i = 0, a = 1, z = k + 1; i <= k; i++)
ans[i] = i % 2 ? z-- : a++
for (let i = k + 1; i < n;)
ans[i] = ++i
return ans
};
Code language: JavaScript (javascript)
Beautiful Arrangement II Solution Python
class Solution(object):
def constructArray(self, n, k):
ans, a, z = [0] * n, 1, k + 1
for i in range(k+1):
if i % 2:
ans[i] = z
z -= 1
else:
ans[i] = a
a += 1
for i in range(k+1,n):
ans[i] = i + 1
return ans