Given an integer array nums sorted in non-decreasing order, return an array of the squares of each number sorted in non-decreasing order.
Follow up: Squaring each element and sorting the new array is very trivial, could you find an O(n) solution using a different approach?
Solution
When I saw this question, my first thought was to loop through, square each element, and then sort. I thought it was too simple.
C# Solution
⚠️Solution1
public class Solution {
public int[] SortedSquares(int[] nums) {
for(int i=0; i<nums.Length; i++){
nums[i]*=nums[i];
}
Array.Sort(nums);
return nums;
}
}
Time Complexity : O(n log n)
⚠️Solution1.1 – LINQ
public class Solution {
public int[] SortedSquares(int[] nums) {
var newNums = nums.Select(x => x * x).ToArray();
Array.Sort(newNums);
return newNums;
}
}
Time Complexity : O(n log n)
When faced with the time complexity constraint in the follow-up, it’s important to search for an approach that can solve the problem within a single loop.
I thought about using the concept of two pointers to tackle this problem. We set up two pointers to initially point to the beginning and end of the array. Then, in each iteration of the loop, we compare the absolute values of the elements pointed to by these pointers.
Since the array is sorted, we don’t need to worry about elements suddenly becoming larger or smaller. Instead, we can simply compare the absolute values of the elements. This allows us to accurately determine which element has a larger square value. Therefore, we calculate the square of the element with the larger absolute value and add it to the new array. We fill the new array starting from the last position and moving backwards.
⭐Solution2 – two pointers
public class Solution {
public int[] SortedSquares(int[] nums) {
int i = 0;
int j = nums.Length-1;
int nowIdx = nums.Length-1;
int[] newNums = new int[nums.Length];
while(i<=j){
var iNum = nums[i];
var jNum = nums[j];
if(Math.Abs(iNum)>Math.Abs(jNum)){
newNums[nowIdx] = iNum*iNum;
i+=1;
}
else {
newNums[nowIdx] = jNum*jNum;
j-=1;
}
nowIdx-=1;
}
return newNums;
}
}
Time Complexity : O(n)
The advantage of this method is that it requires only one loop to complete all operations, without the need for additional sorting of the new array. Thus, its time complexity is O(n), meeting the requirement in the follow-up and achieving the goal of solving the problem in linear time.
Java Solution
Solution1
class Solution {
public int[] sortedSquares(int[] nums) {
int i = 0;
int j = nums.length-1;
int nowIdx = nums.length-1;
int[] newNums = new int[nums.length];
while(i<=j){
int iNum = nums[i];
int jNum = nums[j];
if(Math.abs(iNum)>Math.abs(jNum)){
newNums[nowIdx] = iNum*iNum;
i+=1;
}
else {
newNums[nowIdx] = jNum*jNum;
j-=1;
}
nowIdx-=1;
}
return newNums;
}
}
Time Complexity : O(n)
Conclusion
🧡If my solution helps, that is my honor!
🧡You can support me by sharing my posts, thanks a lot
✅If you got any problem about the explanation, please feel free to let me know
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"0863b228f5"};
var uagb_data = {"ajax_url":"https:\/\/zyrastory.com\/wp-admin\/admin-ajax.php","uagb_masonry_ajax_nonce":"0863b228f5","uagb_grid_ajax_nonce":"3712d10075"};
( function() {
let elements = document.querySelectorAll( '.uagb-post-grid.uagb-block-f4bc3f3d .uagb-post-pagination-wrap a' );
elements.forEach(function(element) {
element.addEventListener("click", function(event){
event.preventDefault();
const link = event.target.getAttribute('href').match( /\/page\/\d+\// )?.[0] || '';
const regex = /\d+/; // regular expression to match a number at the end of the string
const match = link.match( regex ) ? link.match( regex )[0] : 1; // match the regular expression with the link
const pageNumber = parseInt( match ); // extract the number and parse it to an integer
window.UAGBPostGrid._callAjax({"btnBorderStyle":"none","overallBorderColor":"","block_id":"f4bc3f3d","categories":"62","displayPostExcerpt":false,"displayPostComment":false,"displayPostImage":false,"imgSize":"medium","linkBox":false,"orderBy":"rand","excludeCurrentPost":true,"postPagination":true,"pageLimit":0,"imageRatio":"2-3","imgEqualHeight":true,"extended_widget_opts":{"id_base":-1,"column":{"desktop":"12","tablet":"12","mobile":"12"},"alignment":{"desktop":"default","tablet":"default","mobile":"default"},"roles":{"state":"","options":"hide"},"visibility":{"selected":"0","options":"hide","acf":{"visibility":"hide","field":"","condition":"","value":""}},"author_page":{"author_pages":{"selections":"1"}},"devices":{"options":"hide"},"days":{"options":"hide"},"dates":{"options":"hide","from":"","to":""},"styling":{"selected":"0","bg_image":"","background":"","background_hover":"","heading":"","text":"","links":"","links_hover":"","border_color":"","border_type":"","border_width":"","background_input":"","text_input":"","border_color_input":"","border_type_input":"","border_width_input":"","background_submit":"","background_submit_hover":"","text_submit":"","border_color_submit":"","border_type_submit":"","border_width_submit":"","list_border_color":"","table_border_color":""},"class":{"selected":"0","link":"","id":"","classes":"","animation":"","event":"enters","speed":"","offset":"","delay":"","logic":""},"tabselect":"0"},"btnBorderLink":true,"btnBorderRadiusLink":true,"overallBorderLink":true,"overallBorderRadiusLink":true,"inheritFromTheme":true,"postType":"post","postDisplaytext":"No post found!","taxonomyType":"category","postsToShow":6,"enableOffset":false,"postsOffset":0,"displayPostDate":true,"excerptLength":15,"displayPostAuthor":false,"displayPostTitle":true,"displayPostTaxonomy":false,"hideTaxonomyIcon":true,"taxStyle":"default","displayPostTaxonomyAboveTitle":"withMeta","imgPosition":"top","bgOverlayColor":"#000000","overlayOpacity":"50","displayPostLink":true,"newTab":false,"ctaText":"Read More","inheritFromThemeBtn":false,"buttonType":"primary","btnHPadding":"","btnVPadding":"","columns":3,"tcolumns":2,"mcolumns":1,"align":"left","width":"wide","order":"desc","rowGap":20,"rowGapTablet":20,"rowGapMobile":20,"columnGap":20,"bgType":"color","bgColor":"#f6f6f6","titleTag":"h4","titleFontSize":"","titleFontSizeType":"px","titleFontFamily":"","titleLineHeightType":"em","titleLoadGoogleFonts":false,"metaColor":"","highlightedTextColor":"#fff","highlightedTextBgColor":"#3182ce","metaFontSize":"","metaFontSizeType":"px","metaFontFamily":"","metaLineHeightType":"em","metaLoadGoogleFonts":false,"excerptColor":"","excerptFontSize":"","excerptFontSizeType":"px","excerptFontFamily":"","excerptLineHeightType":"em","excerptLoadGoogleFonts":false,"displayPostContentRadio":"excerpt","ctaBgType":"color","ctaBgHType":"color","ctaFontSize":"","ctaFontSizeType":"px","ctaFontFamily":"","ctaLineHeightType":"em","ctaLoadGoogleFonts":false,"paddingTop":20,"paddingBottom":20,"paddingRight":20,"paddingLeft":20,"contentPadding":20,"ctaBottomSpace":0,"ctaBottomSpaceTablet":0,"ctaBottomSpaceMobile":0,"imageBottomSpace":15,"titleBottomSpace":15,"metaBottomSpace":15,"excerptBottomSpace":25,"contentPaddingUnit":"px","rowGapUnit":"px","columnGapUnit":"px","excerptBottomSpaceUnit":"px","paginationSpacingUnit":"px","imageBottomSpaceUnit":"px","titleBottomSpaceUnit":"px","metaBottomSpaceUnit":"px","ctaBottomSpaceUnit":"px","paddingBtnUnit":"px","mobilePaddingBtnUnit":"px","tabletPaddingBtnUnit":"px","paddingUnit":"px","mobilePaddingUnit":"px","tabletPaddingUnit":"px","isPreview":false,"taxDivider":", ","titleLetterSpacing":"","titleLetterSpacingType":"px","metaLetterSpacing":"","metaLetterSpacingType":"px","ctaLetterSpacing":"","ctaLetterSpacingType":"px","excerptLetterSpacing":"","excerptLetterSpacingType":"px","useSeparateBoxShadows":true,"boxShadowColor":"#00000070","boxShadowHOffset":0,"boxShadowVOffset":0,"boxShadowBlur":"","boxShadowSpread":"","boxShadowPosition":"outset","boxShadowColorHover":"","boxShadowHOffsetHover":0,"boxShadowVOffsetHover":0,"boxShadowBlurHover":"","boxShadowSpreadHover":"","boxShadowPositionHover":"outset","borderWidth":"","borderStyle":"none","borderColor":"","borderRadius":"","blockName":"post-grid","equalHeight":true,"paginationBgActiveColor":"#e4e4e4","paginationActiveColor":"#333333","paginationBgColor":"#e4e4e4","paginationColor":"#777777","paginationMarkup":"","paginationLayout":"filled","paginationBorderColor":"#888686","paginationBorderSize":1,"paginationSpacing":20,"paginationAlignment":"left","paginationPrevText":"\u00ab Previous","paginationNextText":"Next \u00bb","layoutConfig":[["uagb\/post-image"],["uagb\/post-taxonomy"],["uagb\/post-title"],["uagb\/post-meta"],["uagb\/post-excerpt"],["uagb\/post-button"]],"post_type":"grid","equalHeightInlineButtons":false,"paginationType":"ajax","isLeftToRightLayout":false,"wrapperTopPadding":"","wrapperRightPadding":"","wrapperLeftPadding":"","wrapperBottomPadding":"","wrapperTopPaddingTablet":"","wrapperRightPaddingTablet":"","wrapperLeftPaddingTablet":"","wrapperBottomPaddingTablet":"","wrapperTopPaddingMobile":"","wrapperRightPaddingMobile":"","wrapperLeftPaddingMobile":"","wrapperBottomPaddingMobile":"","wrapperPaddingUnit":"px","wrapperPaddingUnitTablet":"px","wrapperPaddingUnitMobile":"px","wrapperPaddingLink":false,"wrapperAlign":"row","wrapperAlignPosition":"center","extended_widget_opts_block":{},"extended_widget_opts_state":"","extended_widget_opts_clientid":"","dateUpdated":""}, pageNumber, 'f4bc3f3d');
});
});
} )();
ai_front = {"insertion_before":"BEFORE","insertion_after":"AFTER","insertion_prepend":"PREPEND CONTENT","insertion_append":"APPEND CONTENT","insertion_replace_content":"REPLACE CONTENT","insertion_replace_element":"REPLACE ELEMENT","visible":"VISIBLE","hidden":"HIDDEN","fallback":"FALLBACK","automatically_placed":"Automatically placed by AdSense Auto ads code","cancel":"Cancel","use":"Use","add":"Add","parent":"Parent","cancel_element_selection":"Cancel element selection","select_parent_element":"Select parent element","css_selector":"CSS selector","use_current_selector":"Use current selector","element":"ELEMENT","path":"PATH","selector":"SELECTOR"};