Similar Problems
Similar Problems not available
Beautiful Arrangement Ii - Leetcode Solution
Companies:
LeetCode: Beautiful Arrangement Ii Leetcode Solution
Difficulty: Medium
Problem Statement: You are given two integers n and k where n is the number of integers in an array and k is the maximum number of swaps allowed. You need to create an array of length n such that each element is unique and at a distance max of k from its neighboring element. The array should be such that the sum of differences between adjacent elements is as small as possible.
Solution: We can solve this problem using a greedy approach. First, we can generate a sorted array from 1 to n. Then, we can choose any element a[i] in the sorted array and swap it with any a[j] where j = i+2k. This will ensure that the difference between a[i] and a[j] is equal to 2k. We can continue to do these swaps until we have exhausted all of our allowed k swaps.
Let's take an example to understand this approach more clearly. Suppose n = 6 and k = 2. Then, we start with the sorted array [1, 2, 3, 4, 5, 6]. We can swap 1 with 5 to get [5, 2, 3, 4, 1, 6]. Now, the maximum distance between any two adjacent elements is 4. We can apply the same swapping logic again to get [5, 4, 3, 2, 1, 6]. The maximum distance between any two adjacent elements is now 2 which is equal to k.
The above approach only works for even values of k. If k is odd, we can modify the approach slightly. We can apply the same swapping logic for the even indexed elements first and then for the odd indexed elements. This will ensure that the maximum distance between any two adjacent elements is equal to k.
Time Complexity: The time complexity of this approach is O(n). We only need to traverse the array once and apply the swapping logic at most k times.
Space Complexity: The space complexity of this approach is O(n) as we are creating an array of size n.
Implementation:
class Solution { public: vector<int> constructArray(int n, int k) { vector<int> res(n, 0); for(int i=0, l=1, r=n;i<n;i++) res[i] = k&1?l++:r--; for(int i=1;i<k;i+=2) swap(res[i], res[k]);
return res;
}
};
Beautiful Arrangement Ii Solution Code
1