667. Beautiful Arrangement II LeetCode Solution

In this guide, you will get 667. Beautiful Arrangement II LeetCode Solution with the best time and space complexity. The solution to Beautiful Arrangement II problem is provided in various programming languages like C++, Java, and Python. This will be helpful for you if you are preparing for placements, hackathons, interviews, or practice purposes. The solutions provided here are very easy to follow and include detailed explanations.

Table of Contents

  1. Problem Statement
  2. Complexity Analysis
  3. Beautiful Arrangement II solution in C++
  4. Beautiful Arrangement II solution in Java
  5. Beautiful Arrangement II solution in Python
  6. Additional Resources
667. Beautiful Arrangement II LeetCode Solution image

Problem Statement of Beautiful Arrangement II

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.

Constraints:

1 <= k < n <= 104

Complexity Analysis

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

667. Beautiful Arrangement II LeetCode Solution in C++

class Solution {
 public:
  vector<int> constructArray(int n, int k) {
    vector<int> ans;

    for (int i = 0; i < n - k; ++i)
      ans.push_back(i + 1);

    for (int i = 0; i < k; ++i)
      if (i % 2 == 0)
        ans.push_back(n - i / 2);
      else
        ans.push_back(n - k + (i + 1) / 2);

    return ans;
  }
};
/* code provided by PROGIEZ */

667. Beautiful Arrangement II LeetCode Solution in Java

class Solution {
  public int[] constructArray(int n, int k) {
    int[] ans = new int[n];

    for (int i = 0; i < n - k; ++i)
      ans[i] = i + 1;

    for (int i = 0; i < k; ++i) {
      if (i % 2 == 0)
        ans[n - k + i] = n - i / 2;
      else
        ans[n - k + i] = n - k + (i + 1) / 2;
    }

    return ans;
  }
}
// code provided by PROGIEZ

667. Beautiful Arrangement II LeetCode Solution in Python

class Solution:
  def constructArray(self, n: int, k: int) -> list[int]:
    ans = list(range(1, n - k + 1))

    for i in range(k):
      if i % 2 == 0:
        ans.append(n - i // 2)
      else:
        ans.append(n - k + (i + 1) // 2)

    return ans
# code by PROGIEZ

Additional Resources

Happy Coding! Keep following PROGIEZ for more updates and solutions.