From ba9e405c33cb4d8ff73f45cb15004dd9d9623f5b Mon Sep 17 00:00:00 2001 From: Krishnavamshi <85016790+krishnavamshidevandla@users.noreply.github.com> Date: Fri, 4 Aug 2023 18:16:55 +0530 Subject: [PATCH 1/2] Create reverse_array_in_groups.py Added another problem in the Arrays category --- Arrays/reverse_array_in_groups.py | 58 +++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Arrays/reverse_array_in_groups.py diff --git a/Arrays/reverse_array_in_groups.py b/Arrays/reverse_array_in_groups.py new file mode 100644 index 0000000..b65d938 --- /dev/null +++ b/Arrays/reverse_array_in_groups.py @@ -0,0 +1,58 @@ +''' +Reverse Array in groups + +Given an Array of size N. Modify the array in-place by reversing every sub-array of size K. + +Note : If at any instance, there are no more subarrays of size greater than or equal to K, + then reverse the last subarray (irrespective of its size). + You shouldn't return any array, modify the given array in-place. + +Input: [1, 2, 3, 4, 5] +Output: [3, 2, 1, 5, 4] +Output explanation: 1, 2, 3 => 3, 2, 1; 4, 5 => 5, 4 + +========================================= +Find the start and end of each sublist and reverse it in-place. + Time Complexity: O(N) + Space Complexity: O(1) +''' + + +############ +# Solution # +############ + +def reverse_array_in_groups(arr, k): + # Initialize a variable to keep track of sub arrays of length k + i = 0 + n = len(arr) + while i [3, 2, 1, 5, 4] +print(reverse_array_in_groups([1, 2, 3, 4, 5], 3)) + +# Test 2 +# Correct result => [2, 3, 4, 5, 1] +print(reverse_array_in_groups([5, 4, 3, 2, 1], 4)) + +# Test 3 +# Correct result => [10, 7, 5, 7, 2, 4, 3, 1, 8c] +print(reverse_array_in_groups([5, 7, 10, 4, 2, 7, 8, 1, 3], 3)) From 8ae8d9e919237badff40a0f4168582ef24270037 Mon Sep 17 00:00:00 2001 From: Krishnavamshi <85016790+krishnavamshidevandla@users.noreply.github.com> Date: Fri, 4 Aug 2023 18:17:38 +0530 Subject: [PATCH 2/2] Update reverse_array_in_groups.py --- Arrays/reverse_array_in_groups.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Arrays/reverse_array_in_groups.py b/Arrays/reverse_array_in_groups.py index b65d938..0c29b20 100644 --- a/Arrays/reverse_array_in_groups.py +++ b/Arrays/reverse_array_in_groups.py @@ -54,5 +54,5 @@ def reverse_array_in_groups(arr, k): print(reverse_array_in_groups([5, 4, 3, 2, 1], 4)) # Test 3 -# Correct result => [10, 7, 5, 7, 2, 4, 3, 1, 8c] +# Correct result => [10, 7, 5, 7, 2, 4, 3, 1, 8] print(reverse_array_in_groups([5, 7, 10, 4, 2, 7, 8, 1, 3], 3))