Skip to main content

Command Palette

Search for a command to run...

Solving Leetcode Interviews in Seconds with AI: Make Lexicographically Smallest Array by Swapping Elements

Updated
3 min read

Introduction

In this blog post, we will explore how to solve the LeetCode problem "2948" 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

You are given a 0-indexed array of positive integers nums and a positive integer limit. In one operation, you can choose any two indices i and j and swap nums[i] and nums[j] if |nums[i] - nums[j]| <= limit. Return the lexicographically smallest array that can be obtained by performing the operation any number of times. An array a is lexicographically smaller than an array b if in the first position where a and b differ, array a has an element that is less than the corresponding element in b. For example, the array [2,10,3] is lexicographically smaller than the array [10,2,3] because they differ at index 0 and 2 < 10. Example 1: Input: nums = [1,5,3,9,8], limit = 2 Output: [1,3,5,8,9] Explanation: Apply the operation 2 times: - Swap nums[1] with nums[2]. The array becomes [1,3,5,9,8] - Swap nums[3] with nums[4]. The array becomes [1,3,5,8,9] We cannot obtain a lexicographically smaller array by applying any more operations. Note that it may be possible to get the same result by doing different operations. Example 2: Input: nums = [1,7,6,18,2,1], limit = 3 Output: [1,6,7,18,1,2] Explanation: Apply the operation 3 times: - Swap nums[1] with nums[2]. The array becomes [1,6,7,18,2,1] - Swap nums[0] with nums[4]. The array becomes [2,6,7,18,1,1] - Swap nums[0] with nums[5]. The array becomes [1,6,7,18,1,2] We cannot obtain a lexicographically smaller array by applying any more operations. Example 3: Input: nums = [1,7,28,19,10], limit = 3 Output: [1,7,28,19,10] Explanation: [1,7,28,19,10] is the lexicographically smallest array we can obtain because we cannot apply the operation on any two indices. Constraints: 1 <= nums.length <= 105 1 <= nums[i] <= 109 1 <= limit <= 109

Explanation

Here's the breakdown of the approach, complexity, and the Python code:

  • High-Level Approach:

    • Use Disjoint Set Union (DSU) to find connected components where elements can be swapped. Two indices belong to the same component if the absolute difference between their corresponding values is within the limit.
    • For each connected component, gather the indices and the values present at those indices.
    • Sort both the indices and values within each component. Then, place the sorted values back into the original array at the sorted indices to achieve the lexicographically smallest arrangement within that component.
  • Complexity:

    • Runtime Complexity: O(N log N), dominated by the sorting within each connected component and the initial sorting of indices. The DSU operations are nearly O(1) on average.
    • Storage Complexity: O(N), for the DSU parent array, index lists, and value lists.

Code

    class DSU:
    def __init__(self, n):
        self.parent = list(range(n))

    def find(self, x):
        if self.parent[x] != x:
            self.parent[x] = self.find(self.parent[x])  # Path compression
        return self.parent[x]

    def union(self, x, y):
        root_x = self.find(x)
        root_y = self.find(y)
        if root_x != root_y:
            self.parent[root_x] = root_y


def lexicographically_smallest(nums, limit):
    n = len(nums)
    dsu = DSU(n)

    for i in range(n):
        for j in range(i + 1, n):
            if abs(nums[i] - nums[j]) <= limit:
                dsu.union(i, j)

    components = {}
    for i in range(n):
        root = dsu.find(i)
        if root not in components:
            components[root] = {"indices": [], "values": []}
        components[root]["indices"].append(i)
        components[root]["values"].append(nums[i])

    for component in components.values():
        component["indices"].sort()
        component["values"].sort()

        for i, index in enumerate(component["indices"]):
            nums[index] = component["values"][i]

    return nums

More from this blog

C

Chatmagic blog

2894 posts