Leetcode 667. Beautiful Arrangement II

Problem Explanation

You are given two numbers: n and k. The goal is to construct a list with exactly n distinct numbers ranging from 1 to n. These numbers should be arranged in such a way that if you were to make a second list where each entry i is the absolute difference of entry i and i+1 in the first list, then this second list should have exactly k distinct numbers.

Consider the example where n=3 and k=2. A possible first list is [1, 3, 2]. The second list would consist of the absolute differences: [|1-3|, |3-2|] = [2, 1], which has exactly two distinct integers as required.

The approach to solve this problem is relatively simple. First, push the numbers from 1 to n - k in the result. Then, starting from 0, for each i till k, if i is even, append n - i/2 else append n - k + (i+1)/2.

Python Solution

1
2python
3class Solution:
4    def constructArray(self, n, k):
5        result = []
6        for i in range(n - k):
7            result.append(i + 1) 
8        for i in range(k):
9            if i % 2 == 0:
10                result.append(n - i // 2) 
11            else:
12                result.append(n - k + (i + 1) // 2)
13        return result

Java Solution

1
2java
3class Solution {
4    public int[] constructArray(int n, int k) {
5        int[] result = new int[n];
6        int idx = 0;
7        
8        for (int i = 1; i < n - k; i++) 
9            result[idx++] = i;
10        
11        for (int i = 0; i <= k; i++) 
12           result[idx++] = (i % 2 == 0) ? (n - i / 2) : (n - k + i / 2 + 1);
13            
14        return result;
15    }
16}

JavaScript Solution

1
2javascript
3class Solution {
4    constructArray(n, k) {
5        let result = []
6        for (let i = 0; i < n - k; i++)
7            result.push(i + 1)
8        for (let i = 0; i < k; i++)
9            result.push(i % 2 === 0 ? n - i / 2 : n - k + (i + 1) / 2)
10        return result
11    }
12}

C++ Solution

1
2c++
3class Solution {
4public:
5    vector<int> constructArray(int n, int k) {
6        vector<int> result;
7        
8        for (int i = 0; i < n - k; i++)
9            result.push_back(i + 1);
10        for (int i = 0; i < k; i++)
11            result.push_back(i % 2 == 0 ? n - i / 2 : n - k + (i + 1) / 2);
12            
13        return result;
14    }
15};

C# Solution

1
2csharp
3public class Solution {
4    public int[] ConstructArray(int n, int k) {
5        int[] result = new int[n];
6        int idx = 0;
7        
8        for (int i = 1; i < n - k; i++) 
9            result[idx++] = i;
10        
11        for (int i = 0; i <= k; i++) 
12           result[idx++] = (i % 2 == 0) ? (n - i / 2) : (n - k + i / 2 + 1);
13            
14        return result;
15    }
16}

In the above solutions, we have focused on creating a list as per the requirement where entries are absolute differences of successive numbers and have distinct values. First, we handled a subarray with (n-k) elements where the difference of each element and the next one is 1. Second, for the remaining k elements, we either subtracted half of the index from n based on if the index is even or odd.

We iterated over the range of n-k since they add no real differences to the sequence. These can directly be pushed into the result starting from 1 to n-k because they'll always yield a difference of 1 which is the minimum. The 'for' loops iterate first for the easy constants and next for the ones which vary in distinguishing the List from k.

These solutions approach the problem efficiently, providing optimal runtime for larger values of n and k. The space complexity for all solutions is O(n) as it requires an array/list of size n to store the results. The time complexity is also O(n) as we populate the result array/list in linear time.

These solutions can be effectively used in various problems involving permutations and combinations, where a particular order of numbers is to be found out following some rule. Moreover, this particular problem also improves the understanding of how a clever algorithm can choose to generate and organize numbers in a certain manner that satisfies specific restrictions or conditions.

Both the given n and k need to be within the established limits for the solution to work properly. If the inputs are invalid or exceed the expected limits, errors or inaccurate solutions might be encountered. Hence, it's always necessary to ensure a valid range for n and k. In logic that involves mathematical operations, the validation of input plays a crucial role. If not properly handled, the program can yield unforeseen and unnecessary errors.


Got a question? Ask the Teaching Assistant anything you don't understand.

Still not clear? Ask in the Forum,  Discord or Submit the part you don't understand to our editors.


TA 👨‍🏫