coding-problems icon indicating copy to clipboard operation
coding-problems copied to clipboard

Added another array problem named reverse_array_in_groups

Open krishnavamshidevandla opened this issue 1 year ago • 3 comments

Added another problem of DSA of array where you reverse sub-arrays in the main array according to given sub-array length

krishnavamshidevandla avatar Aug 04 '23 12:08 krishnavamshidevandla

Okay, I have tried it and it looks like this:

def reverse_array_in_groups(arr, k):
    i = 0
    n = len(arr)
    group = 0
    group_size = k
    
    while i<n:
        if (i - group*k == k):
            group += 1
            if (n - i < k):
                group_size = n - i
            
        if (i - group*k < group_size//2):
            right = group*k + (group_size - 1 - (i - group*k))
            left = i
            
            print(i, arr[i], right)
            arr[left], arr[right] = arr[right], arr[left]
        
        i += 1
        
    return arr

But it can be simplified and refactored (some of the formulas can be simplified and some of the checks).

@krishnavamshidevandla could you please try it? thanks.

MTrajK avatar Aug 05 '23 19:08 MTrajK

You could also add both of the solutions in that file.

MTrajK avatar Aug 05 '23 19:08 MTrajK

@MTrajK I have tried your solution, it's working fine. But I can't get my mind around it. Can you edit the solution with a detailed explanation using comments between the code.

krishnavamshidevandla avatar Aug 06 '23 17:08 krishnavamshidevandla