Open In App

Python Slicing | Reverse an array in groups of given size

Last Updated : 13 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Given an array, reverse every sub-array formed by consecutive k elements. Examples:

Input: 
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
k = 3
Output:  
[3, 2, 1, 6, 5, 4, 9, 8, 7]

Input: 
arr = [1, 2, 3, 4, 5, 6, 7, 8]
k = 5
Output:  
[5, 4, 3, 2, 1, 8, 7, 6]

Input: 
arr = [1, 2, 3, 4, 5, 6]
k = 1
Output:  
[1, 2, 3, 4, 5, 6]

Input: 
arr = [1, 2, 3, 4, 5, 6, 7, 8]
k = 10
Output:  
[8, 7, 6, 5, 4, 3, 2, 1]

We have existing solution for this problem please refer Reverse an array in groups of given size link. We can solve this problem quickly in Python using list slicing and reversed() function.Below example will give you better understanding of approach.
Example: 
Example 

Python3




# function to Reverse an array in groups of given size
 
def reverseGroup(input,k):
 
    # set starting index at 0
    start = 0
 
    # run a while loop len(input)/k times
    # because there will be len(input)/k number
    # of groups of size k
    result = []
    while (start<len(input)):
 
           # if length of group is less than k
           # that means we are left with only last
           # group reverse remaining elements
           if len(input[start:])<k:
                result = result + list(reversed(input[start:]))
                break
 
           # select current group of size of k
           # reverse it and concatenate
           result = result + list(reversed(input[start:start + k]))
           start = start + k
    print(result)
 
# Driver program
if __name__ == "__main__":
    input = [1, 2, 3, 4, 5, 6, 7, 8]
    k = 5
    reverseGroup(input,k)


Output:

[5, 4, 3, 2, 1, 8, 7, 6]

Using Direct Function 

Python3




# function to Reverse an array in groups of given size
  
def reverseGroup(a, k):
 
   # take an empty list
   res = []
 
   # iterate over the list with increment of
   # k times in each iteration
   for i in range(0, len(a), k):
      
       # reverse the list in each iteration over
       # span of k elements using extend
       res.extend((a[i:i + k])[::-1])
   print(res)
  
# Driver program
if __name__ == "__main__":
    input = [1, 2, 3, 4, 5, 6, 7, 8]
    k = 5
    reverseGroup(input, k)


Output:

[5, 4, 3, 2, 1, 8, 7, 6]

Approach#2: Using slicing and reversing the chunks

The given code takes an array and a group size as input. It iterates through the array in chunks of size k and reverses each chunk using slice notation. Finally, it concatenates all the chunks to form the final reversed array.

Algorithm

1. Initialize an empty list to store the final output
2. Iterate through the input list in steps of size k
3. For each step, slice the list from the current index to k elements ahead and reverse it
4. Append the reversed slice to the output list
If there are any remaining elements at the end of the list, reverse them and append to the output list
5. Return the output list

Python3




def reverse_groups(arr, k):
    output = []
    for i in range(0, len(arr), k):
        chunk = arr[i:i+k]
        output += chunk[::-1]
    return output
 
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
k = 3
print(reverse_groups(arr, k))
 
arr = [1, 2, 3, 4, 5, 6, 7, 8]
k = 5
print(reverse_groups(arr, k))
 
arr = [1, 2, 3, 4, 5, 6]
k = 1
print(reverse_groups(arr, k))
 
arr = [1, 2, 3, 4, 5, 6, 7, 8]
k = 10
print(reverse_groups(arr, k))


Output

[3, 2, 1, 6, 5, 4, 9, 8, 7]
[5, 4, 3, 2, 1, 8, 7, 6]
[1, 2, 3, 4, 5, 6]
[8, 7, 6, 5, 4, 3, 2, 1]

Time complexity: O(n), n is length of array
Auxiliary Space: O(n)

Approach#3: Using list comprehension

Here is the solution to reverse an array in groups of given size using list comprehension:

Algorithm:

Initialize an empty list to store the final output.
Create a list comprehension to iterate through the input list in steps of size k.
For each step, slice the list from the current index to k elements ahead and reverse it using the slice notation.
Append the reversed slice to the output list using the list concatenation operator ‘+’.
If there are any remaining elements at the end of the list, reverse them and append to the output list using the same list comprehension syntax.
Return the output list.

Python3




def reverse_groups(arr, k):
    # use list comprehension to iterate over arr in chunks of size k
    # and reverse each chunk
    return [val for i in range(0, len(arr), k) for val in reversed(arr[i:i+k])]
 
# test the function with different inputs
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9]
k = 3
print(reverse_groups(arr, k))  # prints [3, 2, 1, 6, 5, 4, 9, 8, 7]
 
arr = [1, 2, 3, 4, 5, 6, 7, 8]
k = 5
print(reverse_groups(arr, k))  # prints [5, 4, 3, 2, 1, 8, 7, 6]
 
arr = [1, 2, 3, 4, 5, 6]
k = 1
print(reverse_groups(arr, k))  # prints [1, 2, 3, 4, 5, 6]
 
arr = [1, 2, 3, 4, 5, 6, 7, 8]
k = 10
print(reverse_groups(arr, k))  # prints [8, 7, 6, 5, 4, 3, 2, 1]


Output

[3, 2, 1, 6, 5, 4, 9, 8, 7]
[5, 4, 3, 2, 1, 8, 7, 6]
[1, 2, 3, 4, 5, 6]
[8, 7, 6, 5, 4, 3, 2, 1]

Time Complexity: The time complexity of this solution is O(n/k) because we are iterating through the input list in steps of size k.

Auxiliary Space: The space complexity of this solution is O(n) because we are creating an output list to store the reversed subarrays.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads