Reverse each element of an array then sort the array in Python

By | September 30, 2023

Given an array arr1[] of size n, so firstly we have to reverse each element of an array, and store each of that reversed element in new arr2[] and then sort.

Examples:

Input : arr1[]={45,67,98,10}
Output : after sorting=>{1,54,76,89}
Explanation :
arr1[]={45,67,98,10}

so after reversing each element:
arr2[]={54,76,89,1}

after sorting arr2[] becomes:
arr2={1,54,76,89}

Input : arr1[]={20,56,90,19,42,67}
Output : after sorting=>{2,9,24,65,76,91}

Approach:

  1. After taking the input just start a for loop in which we are reversing each element of arr1[] and store that in arr2[].
  2. After reversing and storing all the reverse elements in arr2[], then we have to sort arr2[].
  3. Then just print arr2[].

Below is the implementation:

# Python program to reverse each element of a list
# after reversing and storing in a new array
# sort the new array

# Function to reverse each element and sort the list
def reverse_sort(arr1, n):
    arr2 = []

    for i in range(n):
        # Convert the element to a string
        arr1[i] = str(arr1[i])
        # Reverse the string
        j = arr1[i][::-1]
        # After reversing, convert it back to an integer
        arr2.append(int(j))

    # Sort the list in ascending order
    arr2.sort()
    return arr2

# Driver Code
if __name__ == "__main__":
    arr1 = list(map(int, input().split()))
    l_sort = reverse_sort(arr1, len(arr1))
    for i in l_sort:
        print(i, end=" ")

Input:

20 56 90 19 42 67

Output:

2 9 24 65 76 91

Time Complexity: O(n logn)
Space Complexity: O(n)

Please write comments if you find anything incorrect. A gentle request to share this topic on your social media profile.

Author: Mithlesh Upadhyay

I hold an M.Tech degree in Artificial Intelligence (2023) from Delhi Technological University (DTU) and possess over 4 years of experience. I worked at GeeksforGeeks, leading teams and managing content, including GATE CS, Test Series, Placements, C, and C++. I've also contributed technical content to companies like MarsDev, Tutorialspoint, StudyTonight, TutorialCup, and Guru99. My skill set includes coding, Data Structures and Algorithms (DSA), and Object-Oriented Programming (OOPs). I'm proficient in C++, Python, JavaScript, HTML, CSS, Bootstrap, React.js, Node.js, MongoDB, Django, and Data Science.