Solving Leetcode Interviews in Seconds with AI: Beautiful Arrangement II
Introduction
In this blog post, we will explore how to solve the LeetCode problem "667" using AI. LeetCode is a popular platform for preparing for coding interviews, and with the help of AI tools like Chatmagic, we can generate solutions quickly and efficiently - helping you pass the interviews and get the job offer without having to study for months.
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. Constraints: 1 <= k < n <= 104
Explanation
Here's a breakdown of the approach, complexity, and Python code for the problem:
High-Level Approach:
- Generate the first k+1 elements of the array in a way that produces k distinct differences. The optimal way to achieve this is to alternate between the smallest and largest available numbers.
- Fill the remaining elements (from k+1 to n) in increasing order (if we started with decreasing) or decreasing order (if we started with increasing). This ensures that the difference between consecutive elements is always 1, adding no new distinct differences.
Complexity:
- Runtime: O(n)
- Storage: O(n)
Code
def construct_array(n: int, k: int) -> list[int]:
"""
Constructs an array of n distinct positive integers from 1 to n such that
the array of absolute differences of consecutive elements has exactly k distinct integers.
"""
result = []
low = 1
high = k + 1
toggle = True # True for increasing, False for decreasing
for _ in range(k + 1):
if toggle:
result.append(low)
low += 1
else:
result.append(high)
high -= 1
toggle = not toggle
remaining = list(range(k + 2, n + 1))
if result[-1] > result[-2]:
result.extend(remaining)
else:
result.extend(reversed(remaining))
return result