Squares of a Sorted Array (LeetCode)

Nwokocha Wisdom Maduabuchi
2 min readMay 20, 2021

--

Problem

Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.

Example 1:

Input: nums = [-4,-1,0,3,10]
Output: [0,1,9,16,100]
Explanation: After squaring, the array becomes [16,1,0,9,100].
After sorting, it becomes [0,1,9,16,100].

Example 2:

Input: nums = [-7,-3,2,3,11]
Output: [4,9,9,49,121]

Solution

First step: first learn about “squared number” then start coding.
Square number = is the result when a number has been multiplied by itself
Example:
3 Squared= 3 × 3 = 9

Note: you can also square negative numbers ((−5) × (−5) = 25), When we square a negative number we get a positive result.

since we now know how to square a number, you will square the values in the array.

val squared_value = nums.map { it * it }

you will square the elements of the array using the above code, what the code does is square the elements and convert them to a list. Remember what Hackerank wants is an IntArray and not a List.

Second Step: to return the squared ArrayList sorted in non-decreasing order

squared_value.toIntArray().sortedArray()

What the above code does is convert the List to an IntArray and sort the list.

Key points:
Kotlin has so many inbuilt functions that makes it easy to solve easy and complex Data Structure.

Thanks for reading.

--

--

Nwokocha Wisdom Maduabuchi
Nwokocha Wisdom Maduabuchi

Written by Nwokocha Wisdom Maduabuchi

A software engineer with considerable experience in mobile development, native Android, and IOS development(Xcode), flutter dev, technical writing and community

No responses yet