Code Logo

Catalog Shelf Lineup

Published at05 Jan 2026
Topological Sort Easy 17 views
Like5

You are given an array of catalog numbers and need to return them in ascending order, from the smallest to the largest. The array is not necessarily sorted, and it may contain negative values and duplicates.

Nothing is removed along the way. Negative values stay, duplicate values stay, and if the list is empty the answer is just an empty list. The only change is the arrangement of the elements.

For example, nums = [6,-1,6,2] becomes [-1,2,6,6]. Both copies of 6 are still present, just moved into their correct sorted positions. If nums = [3,1,4,1], the result is [1,1,3,4]. A single-element list like [0] returns [0] because it is already sorted.

Sorting is a core building block of computer science, underpinning binary search, range queries, and data normalization. For an array of numbers, the expected approach is a standard numeric sort in ascending order.

As with many sorting problems, the main pitfall is using a default string sort where a numeric sort is required. In JavaScript, for instance, sort() without a comparator treats values as strings, so you must supply (a, b) => a - b to get correct numeric ordering.

Edge cases include an empty array (return []), a single element (return it unchanged), arrays with only negative numbers (sorted from most negative to least negative), and arrays with many duplicates (every copy preserved).

Example Input & Output

Example 1
Input
nums = [6,-1,6,2]
Output
[-1,2,6,6]
Explanation

Negative placeholders and repeats remain visible in ascending order.

Example 2
Input
nums = [0]
Output
[0]
Explanation

A single sample remains unchanged because it is already in order.

Example 3
Input
nums = [3,1,4,1]
Output
[1,1,3,4]
Explanation

Matching labels appear together after sorting while the smallest value leads the list.

Algorithm Flow

Recommendation Algorithm Flow for Catalog Shelf Lineup

Solution Approach

Sort the array in ascending order with a numeric comparator. Copy the input first if you need to preserve the original, then apply the sort.

function lineup_catalog(nums) {
  return nums.slice().sort(function(a, b) { return a - b; });
}

The comparator a - b orders values numerically: negative values sort first, then smaller positive values, and equal values remain adjacent. Using slice() ensures the original array is not modified.

Most languages provide an equivalent one-call sort, such as Python's sorted(nums), Java's Arrays.sort(), or Rust's nums.sort(). The important thing is that the comparison is based on numeric value.

Time complexity is O(n log n), space complexity is O(n) for the copy.

Best Answers

java
import java.util.*;

class Solution {
    public int[] lineup_catalog(int[] nums) {
        int[] result = nums.clone();
        Arrays.sort(result);
        return result;
    }
}