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.
sort the input and compare with the input to get the difference and append to new list. if new list only has 2 values, we can assume that we only need to swap to achieve final result. if new list has more than 2 values, check that the corresponding values are in order.
defalmostSorted(arr):# Write your code heresorted_arr=sorted(arr)index_list=[]foriinrange(len(sorted_arr)):ifsorted_arr[i]!=arr[i]:index_list.append(i+1)iflen(index_list)==2:print('yes')print('swap'+str(index_list[0])+' '+str(index_list[1]))else:sub_list=arr[index_list[0]-1:index_list[-1]]ifsorted(sub_list,reverse=True)!=arr[index_list[0]-1:index_list[-1]]:print('no')else:print('yes')print('reverse'+str(index_list[0])+' '+str(index_list[-1]))
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Almost Sorted
You are viewing a single comment's thread. Return to all comments →
sort the input and compare with the input to get the difference and append to new list. if new list only has 2 values, we can assume that we only need to swap to achieve final result. if new list has more than 2 values, check that the corresponding values are in order.