KatInterview

948. Sort an Array

MediumSolutions in Python, Java, C++, TypeScript

Read the full problem statement on LeetCode and try it first. Below is how to approach it in an interview, followed by a complete answer in each language.

Approach

Method: Merge Sort

This problem requires sorting an array of integers in O(n log n) time without using built-in sorting functions. Merge Sort is a classic divide-and-conquer algorithm that perfectly fits these requirements.

Solution

Sort an Array in Python

class Solution:
    def sortArray(self, nums: List[int]) -> List[int]:
        # Allocate temporary buffer once
        temp = [0] * len(nums)
        self.merge_sort(nums, 0, len(nums) - 1, temp)
        return nums

    def merge_sort(self, nums: List[int], left: int, right: int, temp: List[int]):
        # Base case: if the subarray has 0 or 1 element, it's already sorted.
        if left >= right:
            return
        
        # Find the middle point to divide the array into two halves
        mid = (left + right) // 2

        # Recursively sort the two halves
        self.merge_sort(nums, left, mid, temp)
        self.merge_sort(nums, mid + 1, right, temp)

        # Merge the sorted halves
        self.merge(nums, left, mid, right, temp)

    def merge(self, nums: List[int], left: int, mid: int, right: int, temp: List[int]):
        # Copy the current segment of nums to the temp array
        for i in range(left, right + 1):
            temp[i] = nums[i]

        i = left        # Pointer for the left half (in temp array)
        j = mid + 1     # Pointer for the right half (in temp array)

        # Merge the two halves from temp back into the original nums array
        for k in range(left, right + 1):
            if i > mid:
                # If left half is exhausted, take from the right half
                nums[k] = temp[j]
                j += 1
            elif j > right:
                # If right half is exhausted, take from the left half
                nums[k] = temp[i]
                i += 1
            elif temp[i] <= temp[j]:
                # If element in left half is smaller or equal, take it
                nums[k] = temp[i]
                i += 1
            else:
                # If element in right half is smaller, take it
                nums[k] = temp[j]
                j += 1

Sort an Array in Java

class Solution {
    public int[] sortArray(int[] nums) {
        if (nums == null || nums.length == 0) {
            return nums;
        }
        // Allocate temporary buffer once to avoid repeated allocations
        int[] temp = new int[nums.length];
        mergeSort(nums, 0, nums.length - 1, temp);
        return nums;
    }

    private void mergeSort(int[] nums, int left, int right, int[] temp) {
        // Base case: if the subarray has 0 or 1 element, it's already sorted.
        if (left >= right) {
            return;
        }

        // Find the middle point to divide the array into two halves
        int mid = left + (right - left) / 2;

        // Recursively sort the two halves
        mergeSort(nums, left, mid, temp);
        mergeSort(nums, mid + 1, right, temp);

        // Merge the sorted halves
        merge(nums, left, mid, right, temp);
    }

    private void merge(int[] nums, int left, int mid, int right, int[] temp) {
        // Copy the current segment of nums to the temp array
        for (int i = left; i <= right; i++) {
            temp[i] = nums[i];
        }

        int i = left;       // Pointer for the left half (in temp array)
        int j = mid + 1;    // Pointer for the right half (in temp array)
        
        // Merge the two halves from temp back into the original nums array
        for (int k = left; k <= right; k++) {
            if (i > mid) {
                // If left half is exhausted, take from the right half
                nums[k] = temp[j++];
            } else if (j > right) {
                // If right half is exhausted, take from the left half
                nums[k] = temp[i++];
            } else if (temp[i] <= temp[j]) {
                // If element in left half is smaller or equal, take it
                nums[k] = temp[i++];
            } else {
                // If element in right half is smaller, take it
                nums[k] = temp[j++];
            }
        }
    }
}

Sort an Array in C++

class Solution {
public:
    vector<int> sortArray(vector<int>& nums) {
        if (nums.empty()) {
            return {};
        }
        // Allocate temporary buffer once to avoid repeated allocations
        vector<int> temp(nums.size());
        mergeSort(nums, 0, nums.size() - 1, temp);
        return nums;
    }

private:
    void mergeSort(vector<int>& nums, int left, int right, vector<int>& temp) {
        // Base case: if the subarray has 0 or 1 element, it's already sorted.
        if (left >= right) {
            return;
        }

        // Find the middle point to divide the array into two halves
        int mid = left + (right - left) / 2;

        // Recursively sort the two halves
        mergeSort(nums, left, mid, temp);
        mergeSort(nums, mid + 1, right, temp);

        // Merge the sorted halves
        merge(nums, left, mid, right, temp);
    }

    void merge(vector<int>& nums, int left, int mid, int right, vector<int>& temp) {
        // Copy the current segment of nums to the temp array
        for (int i = left; i <= right; ++i) {
            temp[i] = nums[i];
        }

        int i = left;       // Pointer for the left half (in temp array)
        int j = mid + 1;    // Pointer for the right half (in temp array)

        // Merge the two halves from temp back into the original nums array
        for (int k = left; k <= right; ++k) {
            if (i > mid) {
                // If left half is exhausted, take from the right half
                nums[k] = temp[j++];
            } else if (j > right) {
                // If right half is exhausted, take from the left half
                nums[k] = temp[i++];
            } else if (temp[i] <= temp[j]) {
                // If element in left half is smaller or equal, take it
                nums[k] = temp[i++];
            } else {
                // If element in right half is smaller, take it
                nums[k] = temp[j++];
            }
        }
    }
};

Sort an Array in TypeScript

function sortArray(nums: number[]): number[] {
    if (nums === null || nums.length === 0) {
        return nums;
    }
    // Allocate temporary buffer once to avoid repeated allocations
    const temp: number[] = new Array(nums.length);

    const merge = (left: number, mid: number, right: number) => {
        // Copy the current segment of nums to the temp array
        for (let i = left; i <= right; i++) {
            temp[i] = nums[i];
        }

        let i = left;       // Pointer for the left half (in temp array)
        let j = mid + 1;    // Pointer for the right half (in temp array)
        
        // Merge the two halves from temp back into the original nums array
        for (let k = left; k <= right; k++) {
            if (i > mid) {
                // If left half is exhausted, take from the right half
                nums[k] = temp[j++];
            } else if (j > right) {
                // If right half is exhausted, take from the left half
                nums[k] = temp[i++];
            } else if (temp[i] <= temp[j]) {
                // If element in left half is smaller or equal, take it
                nums[k] = temp[i++];
            } else {
                // If element in right half is smaller, take it
                nums[k] = temp[j++];
            }
        }
    };

    const mergeSortRecursive = (left: number, right: number) => {
        // Base case: if the subarray has 0 or 1 element, it's already sorted.
        if (left >= right) {
            return;
        }

        // Find the middle point to divide the array into two halves
        const mid = Math.floor(left + (right - left) / 2);

        // Recursively sort the two halves
        mergeSortRecursive(left, mid);
        mergeSortRecursive(mid + 1, right);

        // Merge the sorted halves
        merge(left, mid, right);
    };

    mergeSortRecursive(0, nums.length - 1);
    return nums;
};

Preparing for interviews beyond LeetCode? Practise system design, SQL and behavioral questions with an in-browser runner on KatInterview.

LeetCode is a trademark of LeetCode LLC. KatInterview is not affiliated with LeetCode.