Last updated on October 5th, 2024 at 04:21 pm
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
Topics
Array
Companies
Level of Question
Medium
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 are 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.
1. Beautiful Arrangement II LeetCode 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; } };
2. Beautiful Arrangement II LeetCode 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; } }
3. Beautiful Arrangement II LeetCode 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 };
4. Beautiful Arrangement II LeetCode 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