We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
define a helper for detecting if an array is sorted
define another helper to recursively go through the array using the sliding window technique
for the recursive helper
check if the array is sorted, and if so return true (base case)
using the sliding window technique, slide through the array three elements at a time
if the minimum of these elements is not in the right spot and can be put in the right place by using the options given, then do so and move on to the next slide
if we reach the last three elements and the slice or segement from the beginning up to that ponint is not not sorted and the minimum of the three elements is not in the right place return false (base case)
after reaching the end of the array, call recursively the original array that has been modified
if the recursive call returns true, then we return true
Using the recursive helper and a simple ternary operator returns the desired results
Actual code
functionlarrysArray(A){return`${recursive(A)?'YES':'NO'}`;}constrecursive=(arr)=>{if(isSorted(arr))returntrue;for(leti=0;i<arr.length-2;i++){leta=arr[i],b=arr[i+1],c=arr[i+2];letsmallestInRightPlace=a<b&&a<c;constsegmentSorted=a<b&&b<c;constfirstSlice=arr.slice(0,i);if(smallestInRightPlace&&i===arr.length-3&&!segmentSorted&&isSorted(firstSlice)){returnfalse;}if(b<a&&b<c){// bcaarr[i]=b;arr[i+1]=c;arr[i+2]=a;}if(c<a&&c<b){// cabarr[i]=c;arr[i+1]=a;arr[i+2]=b;}}if(recursive(arr)){returntrue;}};// checks if an array is sortedconstisSorted=(arr)=>{for(leti=0;i<arr.length-1;i++){if(arr[i+1]){if(arr[i+1]<arr[i])returnfalse;}}returntrue;};
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Larry's Array
You are viewing a single comment's thread. Return to all comments →
Here is the Javascript solution
pseudo code
if the recursive call returns true, then we return true
Actual code