Hackerrank Data Structures - Arrays
Reversing an array of integers
Problem
An array is a type of data structure that stores elements of the same type in a contiguous block of memory.
In an array, A, of size N, each memory location has some unique index, (where 0 ≤ i ≤ N), that can be referenced as A[i] (you may also see it written as Ai).
Challenge
Reverse an array of integers.
Input Format
The first line contains an integer, N (the number of integers in A).
The second line contains N space-separated integers that make up A.
Constraints
1 ≤ N ≤ 103
1 ≤ Ai ≤ 104. where A [i] is the i-th integer in A.
Get Arthi Murali’s stories in your inbox
Join Medium for free to get updates from this writer.
Sample Input
4
1 4 3 2Sample Output
2 3 4 1Solution :
len_of_num = int(input())
numbers = input().split(' ')
reverse = numbers[::-1]
r = ''
for i in range(len_of_num):
r = r + str(reverse[i]) + ' '
print(''.join(r))Explanation:
- The length of the list of numbers, is taken as input in integer. Assigned to variable len_of_num.
- The numbers seperated by space, are taken as input and assigned to the variable numbers. The numbers are stored as substrings ,seperated by spaces in a list .
For example if the input is 1 4 3 2, input would be stored as [‘1’, ‘4’, ‘3’, ‘2’] in numbers variable.
- The elements in numbers variable will be reversed using slicing method [::-1].
- An empty string is assigned to the variable r .
- The for loop runs till the number of len_of_num-1 . Elements with index starting from 0 till len_of_num-1 is stored in the variable r with spaces between each number .
- By using join function, the string is removed, with only number seperated by space is printed as result .
I hope this blog helps. Do let me know if there is any feedback or any other approach to this problem. Would love to learn :)









