I have this coding question, that i was unable to complete
Given an array, find all the subarrays, of length 1 <= k <= len(arr)
and find imbalance in those subarrays
Imbalance is when the difference between two neighboring items in a sorted array is more than one
Imbalance is defined as the number of items j who are more than 1 from the item before them, i.e sorted_arr[j] - sorted_arr[j - 1 > 1
for example given array = [4, 1, 3, 2]
The subarrays are:
1. [4]
2. [1]
3. [3]
4. [2]
5. [4, 1]
6. [1, 3]
7. [3, 2]
8. [4, 1, 3]
9. [1, 3, 2]
10. [4, 1, 3, 2]
for each subarray, after sorting them, only 5, 6 and 8
have a case where subarray[i] - subarray[i - 1] > 1
, in which case imbalance will be incremented by 1
In the above example, imbalance = 3
heres my code for the probem:
def get_imbalance(arr):
imbalance = 0
for i in range(1, len(arr)):
imbalance += 1 if arr[i] - arr[i - 1] > 1 else 0
return imbalance
def func(arr):
imbalance = 0
if len(arr) <= 1: return 0
if len(arr) == 2:
return 1 if abs(arr[0] - arr[1]) > 1 else 0
for i in range(2, len(arr) + 1):
for j in range(len(arr) - i + 1):
imbalance += get_imbalance(sorted(rank[j: j + i]))
return imbalance
I am using a sliding window to get all the different subarrays of the main array, then sorting the result and returning the imbalance. However, this runs into time limit exceed issues. How can I optimize the algorithm?