Home Backend Development PHP Tutorial Make Lexicographically Smallest Array by Swapping Elements

Make Lexicographically Smallest Array by Swapping Elements

Jan 26, 2025 am 02:04 AM

Make Lexicographically Smallest Array by Swapping Elements

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]| <= 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.

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 <= nums.length <= 105
  • 1 <= nums[i] <= 109
  • 1 <= limit <= 109

Hint:

  1. Construct a virtual graph where all elements in nums are nodes and the pairs satisfying the condition have an edge between them.
  2. Instead of constructing all edges, we only care about the connected components.
  3. Can we use DSU?
  4. 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.
  5. 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

  1. Lexicographical Order: An array a is lexicographically smaller than b if at the first differing index, a[i] < b[i].
  2. Swapping Condition: Swaps are only allowed if the difference between the numbers being swapped is ≤ limit.
  3. Efficient Grouping: By using Disjoint Set Union (DSU) or sorting techniques, we can group elements that are connected by valid swaps.
  4. Optimal Arrangement: For each group, sort the indices and values to achieve the smallest order.

Approach

  1. 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.
  2. Sort Groups: Within each group of connected indices, rearrange the elements in lexicographical order.
  3. Output Construction: Place the sorted values back into their respective positions.

Plan

  1. Extract (value, index) pairs and sort them by value to enable efficient group detection.
  2. Iterate through sorted values to form groups of indices that are connected based on the limit condition.
  3. For each group:
    • Sort indices and values independently.
    • Reassign values to their original positions in lexicographical order.
  4. Return the modified array.

Let's implement this solution in PHP: 2948. Make Lexicographically Smallest Array by Swapping Elements






Explanation:

  1. 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.
  2. 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.
  3. 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.
  4. Result Construction:

    • After processing all groups, return the updated array.

Example Walkthrough

Example 1

Input: nums = [1,5,3,9,8], limit = 2

  1. 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)]
  2. Grouping:

    • Group 1: [(1, 0)]
    • Group 2: [(3, 2), (5, 1)]
    • Group 3: [(8, 4), (9, 3)]
  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]
  4. Final Result: [1, 3, 5, 8, 9]

Time Complexity

  1. Sorting: Sorting the nums array takes O(n log n).
  2. Grouping: Linear traversal through the sorted array takes O(n).
  3. 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:

  • LinkedIn
  • 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How does session hijacking work and how can you mitigate it in PHP? How does session hijacking work and how can you mitigate it in PHP? Apr 06, 2025 am 12:02 AM

Session hijacking can be achieved through the following steps: 1. Obtain the session ID, 2. Use the session ID, 3. Keep the session active. The methods to prevent session hijacking in PHP include: 1. Use the session_regenerate_id() function to regenerate the session ID, 2. Store session data through the database, 3. Ensure that all session data is transmitted through HTTPS.

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

See all articles