Prepin
Log in

Square of an arranged array

Approach / Explanation

The task requires you to create a function or program that accepts an array of sorted integers and produces an array of their squares in sorted order. This is a common exercise designed to assess your skills in handling arrays and your understanding of sorting algorithms. There are three main aspects to consider for this problem: Squaring Each Element: The initial step involves iterating through the array and squaring each element. Sorting the Result: After squaring each element, the next step is to sort the results. Although the input array is sorted, it’s important to realize that squaring the elements can disrupt their order. Negative numbers will become positive upon squaring and could exceed the value of the next element. Return the Result: Finally, you will need to return the newly sorted array of squares. Keep in mind that there are various ways to tackle this problem, including using built-in sorting functions or implementing a two-pointer technique if an optimized solution is required.

Suggested Answer

Below is a Python code example that demonstrates this technique using list comprehensions and built-in functions: def sortedSquares(nums): return sorted([i*i for i in nums]) In this example, the expression [i*i for i in nums] computes the square of each element in the nums list, and then the sorted function arranges the resulting list of squares in ascending order.

Alternative Answer

If you have been instructed to refrain from using the built-in sort() function to enhance the solution, here’s a method that employs the two-pointers technique: public int[] sortedSquares(int[] nums) { int n = nums.length; int[] result = new int[n]; int i = 0, j = n - 1; for (int p = n - 1; p >= 0; p--) { if (Math.abs(nums[i]) > Math.abs(nums[j])) { result[p] = nums[i] * nums[i]; i++; } else { result[p] = nums[j] * nums[j]; j--; } } return result; } This Java code initializes two pointers at either end of the array, comparing the absolute values of the elements at these positions. The square of the larger value is placed at the end of the result array, and the pointers are then moved inward accordingly.

Question Details

Difficulty & Category

Medium

Companies

Meta (Facebook)

Product

For CandidatesFor RecruitersCompaniesBrowse JobsInterview QuestionsDeep ProfileSkill AssessmentOpportunity Matching
Prepin.ai

© 2026 Prepin LLC · Philadelphia, PA · All rights reserved.