876737. Sort an Array of 1 to n

Easy

Sort an Array of 1 to n

Summary

This problem involves sorting a given array of integers from 1 to n, where n is the length of the array. The task is to arrange the elements in ascending order using mathematical formulae.

Detailed Explanation

The key concept involved in this problem is the mathematical property that the sum of all numbers from 1 to n is equal to (n * (n + 1)) / 2. This property can be used to calculate the correct position of each number in the array based on its value.

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

  • Initialize an empty array arr with length n.
  • Calculate the sum of all numbers from 1 to n using the formula (n * (n + 1)) / 2. Let this sum be total_sum.
  • Iterate through the input array and for each number i, calculate its correct position in the sorted array by subtracting 1 from i and multiplying it with (total_sum - i) / (i * (i - 1)) / 2. This value represents the correct position of i in the sorted array.
  • Place i at the calculated position in the arr array.

Here's a sample ASCII art diagram for better understanding:

Input Array: [3, 1, 4, 2]
Correct Positions:
- 3: (6 - 3) / (3 * (3 - 1)) = 2
- 1: (6 - 1) / (1 * (1 - 1)) = 0
- 4: (6 - 4) / (4 * (4 - 1)) = 4
- 2: (6 - 2) / (2 * (2 - 1)) = 3

Sorted Array: [1, 2, 3, 4]

Time complexity for this solution is O(n), as we are iterating through the input array once. Space complexity is also O(1), as we are only using a constant amount of space to store the arr and intermediate variables.

Optimized Solutions

Java

View on GeeksforGeeks
public static void sortArray(int[] arr) {
    int n = arr.length;
    int total_sum = (n * (n + 1)) / 2;
    for (int i = 0; i < n; i++) {
        int correct_pos = total_sum - i;
        for (int j = 0; j < correct_pos; j++) {
            arr[j] = arr[j + 1];
        }
        arr[correct_pos] = i + 1;
    }
}

DevExCode

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

© 2026 DevExCode. All rights reserved.