2948. Make Lexicographically Smallest Array by Swapping Elements
Difficulty: Medium
Topics: Array, Union Find, Sorting
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]|
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
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.
Example 4:
- Input: nums = [1,60,34,84,62,56,39,76,49,38], limit = 4
- Output: [1,56,34,84,60,62,38,76,49,39]
Constraints:
- 1 5
- 1 9
- 1 9
Hint:
- Construct a virtual graph where all elements in nums are nodes and the pairs satisfying the condition have an edge between them.
- Instead of constructing all edges, we only care about the connected components.
- Can we use DSU?
- Sort nums. Now we just need to consider if the consecutive elements have an edge to check if they belong to the same connected component. Hence, all connected components become a list of position-consecutive elements after sorting.
- For each index of nums from 0 to nums.length - 1 we can change it to the current minimum value we have in its connected component and remove that value from the connected component.
Solution:
The problem asks us to find the lexicographically smallest array by swapping elements of an array, subject to a condition. Specifically, we can only swap two elements nums[i] and nums[j] if the absolute difference between them (|nums[i] - nums[j]|) is less than or equal to a given limit.
Key Points
- Lexicographical Order: An array a is lexicographically smaller than b if at the first differing index, a[i]
- Swapping Condition: Swaps are only allowed if the difference between the numbers being swapped is ≤ limit.
- Efficient Grouping: By using Disjoint Set Union (DSU) or sorting techniques, we can group elements that are connected by valid swaps.
- Optimal Arrangement: For each group, sort the indices and values to achieve the smallest order.
Approach
- Construct Groups: Treat the array as a virtual graph, where valid swaps define the edges. Use sorting to identify connected groups or DSU to group indices efficiently.
- Sort Groups: Within each group of connected indices, rearrange the elements in lexicographical order.
- Output Construction: Place the sorted values back into their respective positions.
Plan
- Extract (value, index) pairs and sort them by value to enable efficient group detection.
- Iterate through sorted values to form groups of indices that are connected based on the limit condition.
- For each group:
- Sort indices and values independently.
- Reassign values to their original positions in lexicographical order.
- Return the modified array.
Let's implement this solution in PHP: 2948. Make Lexicographically Smallest Array by Swapping Elements
<?php /** * @param Integer[] $nums * @param Integer $limit * @return Integer[] */ function lexicographicallySmallestArray($nums, $limit) { ... ... ... /** * go to ./solution.php */ } /** * @param $nums * @return array */ function getNumAndIndexes($nums) { ... ... ... /** * go to ./solution.php */ } // Example usage: $nums1 = [1, 5, 3, 9, 8]; $limit1 = 2; print_r(lexicographicallySmallestArray($nums1, $limit1)); // Output: [1, 3, 5, 8, 9] $nums2 = [1, 7, 6, 18, 2, 1]; $limit2 = 3; print_r(lexicographicallySmallestArray($nums2, $limit2)); // Output: [1, 6, 7, 18, 1, 2] $nums3 = [1, 7, 28, 19, 10]; $limit3 = 3; print_r(lexicographicallySmallestArray($nums3, $limit3)); // Output: [1, 7, 28, 19, 10] $nums4 = [1, 60, 34, 84, 62, 56, 39, 76, 49, 38]; $limit4 = 4; print_r(lexicographicallySmallestArray($nums4, $limit4)); // Output: [1, 56, 34, 84, 60, 62, 38, 76, 49, 39] ?>
Explanation:
-
Extracting and Sorting (getNumAndIndexes):
- Combine values and indices into pairs for easy reference.
- Sort the pairs by value to enable efficient grouping of connected components.
-
Grouping Logic:
- Traverse the sorted pairs. If the difference between consecutive values is ≤ limit, add them to the same group; otherwise, start a new group.
-
Sorting and Reassigning:
- For each group:
- Extract the indices and values.
- Sort both lists to ensure the smallest values are placed in the smallest indices.
- Reassign the sorted values to their respective positions in the answer array.
- For each group:
-
Result Construction:
- After processing all groups, return the updated array.
Example Walkthrough
Example 1
Input: nums = [1,5,3,9,8], limit = 2
-
Extract and Sort:
- Pairs: [(1, 0), (5, 1), (3, 2), (9, 3), (8, 4)]
- Sorted Pairs: [(1, 0), (3, 2), (5, 1), (8, 4), (9, 3)]
-
Grouping:
- Group 1: [(1, 0)]
- Group 2: [(3, 2), (5, 1)]
- Group 3: [(8, 4), (9, 3)]
-
Sorting Groups:
- Group 1: No change ([1])
- Group 2: Values = [3, 5], Indices = [1, 2] → Result: [1, 3, 5]
- Group 3: Values = [8, 9], Indices = [3, 4] → Result: [8, 9]
Final Result: [1, 3, 5, 8, 9]
Time Complexity
- Sorting: Sorting the nums array takes O(n log n).
- Grouping: Linear traversal through the sorted array takes O(n).
- Sorting Groups: Sorting indices and values for each group takes O(k log k), where k is the group size. Summed over all groups, this is O(n log n).
Overall Time Complexity: O(n log n)
Output for Examples
Example 2
Input: nums = [1,7,6,18,2,1], limit = 3
Output: [1,6,7,18,1,2]
Example 3
Input: nums = [1,7,28,19,10], limit = 3
Output: [1,7,28,19,10]
This approach efficiently handles the problem by using sorting to identify connected components and rearranging values within each component to achieve the lexicographically smallest array. By leveraging sorting and group processing, we ensure an optimal solution with O(n log n) complexity.
Contact Links
If you found this series helpful, please consider giving the repository a star on GitHub or sharing the post on your favorite social networks ?. Your support would mean a lot to me!
If you want more helpful content like this, feel free to follow me:
- GitHub
The above is the detailed content of Make Lexicographically Smallest Array by Swapping Elements. For more information, please follow other related articles on the PHP Chinese website!

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values and handle functions that may return null values.

In PHP, use the clone keyword to create a copy of the object and customize the cloning behavior through the \_\_clone magic method. 1. Use the clone keyword to make a shallow copy, cloning the object's properties but not the object's properties. 2. The \_\_clone method can deeply copy nested objects to avoid shallow copying problems. 3. Pay attention to avoid circular references and performance problems in cloning, and optimize cloning operations to improve efficiency.

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft