Leetcode 2948: Make Lexicographically Smallest Array by Swapping Elements

grid47
grid47
Exploring patterns and algorithms
Jan 17, 2024 7 min read

You are given a list of integers, nums, and a positive integer limit. In each operation, you can choose two indices i and j and swap the elements at these indices if the absolute difference between nums[i] and nums[j] is less than or equal to the given limit. Your task is to return the lexicographically smallest array that can be obtained after applying the operation as many times as needed.
Problem
Approach
Steps
Complexity
Input: You are given an integer array `nums` of size `n` and an integer `limit`.
Example: nums = [1,5,3,9,8], limit = 2
Constraints:
• 1 <= nums.length <= 10^5
• 1 <= nums[i] <= 10^9
• 1 <= limit <= 10^9
Output: Return the lexicographically smallest array that can be obtained.
Example: Output: [1,3,5,8,9]
Constraints:
• The output array must be lexicographically smallest.
Goal: We need to determine the lexicographically smallest array by swapping elements based on the given limit.
Steps:
• Sort the elements of the array along with their indices.
• Group the elements that can be swapped (i.e., those whose absolute difference is less than or equal to the limit).
• Sort each group of swappable elements and place them back into their original indices.
Goal: Constraints on the length and values of `nums` and `limit`.
Steps:
• nums.length is between 1 and 10^5.
• Each element of `nums` is between 1 and 10^9.
• limit is between 1 and 10^9.
Assumptions:
• The operation is performed as many times as possible.
• The operation only applies when the absolute difference between two numbers is less than or equal to `limit`.
Input: nums = [1, 5, 3, 9, 8], limit = 2
Explanation: After sorting and applying the allowed swaps, we achieve the lexicographically smallest array [1, 3, 5, 8, 9].

Input: nums = [1, 7, 6, 18, 2, 1], limit = 3
Explanation: By swapping elements where the difference is within the limit, the array becomes [1, 6, 7, 18, 1, 2].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus