852210. Sort last M elements

Medium

Here is the detailed Markdown blog post for the problem:

Sort last M elements

Summary

The problem requires sorting the last M elements of an array in ascending order, given a pre-existing sorted array. This problem involves concepts from Sorting and Merge Sort.

Detailed Explanation

Sorting the last M elements of an array is a subproblem that can be solved by merging the last M elements of two arrays in ascending order. To solve this problem, we will use the merge part of the Merge Sort algorithm.

Here's a step-by-step breakdown of the solution:

  1. Create two temporary arrays: leftArr and rightArr. The size of leftArr is n - M, where n is the size of the original array.
  2. Copy the first n - M elements to leftArr.
  3. Copy the last M elements to rightArr.
  4. Merge leftArr and rightArr in ascending order using the merge part of the Merge Sort algorithm.

The time complexity for this solution is O(M log M) as we are performing a merge operation on an array of size M. The space complexity is O(M), as we need to create two temporary arrays of size M.

Optimized Solutions

Here are optimized solutions in various programming languages:

Java

View on GeeksforGeeks
public static void sortLastMElements(int[] arr, int M) {
    if (arr.length <= M) {
        Arrays.sort(arr);
        return;
    }

    int[] leftArr = new int[arr.length - M];
    System.arraycopy(arr, 0, leftArr, 0, arr.length - M);

    int[] rightArr = new int[M];
    System.arraycopy(arr, arr.length - M, rightArr, 0, M);

    int i = 0;
    int j = 0;
    for (int k = 0; k < arr.length; k++) {
        if (i < leftArr.length && j < rightArr.length) {
            if (leftArr[i] <= rightArr[j]) {
                arr[k] = leftArr[i];
                i++;
            } else {
                arr[k] = rightArr[j];
                j++;
            }
        } else if (i < leftArr.length) {
            arr[k] = leftArr[i];
            i++;
        } else {
            arr[k] = rightArr[j];
            j++;
        }
    }
}

DevExCode

Master coding interviews with Leetcode, system design, TechBit, QuickLearn, DevTips, Tech Battles, and career services.

© 2026 DevExCode. All rights reserved.