Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Length of the longest sub-array which consists of all '1'

suppose i have a list say x=[1,0,0,1,0,1,1,1,0,1,1,0].Here longest sub-array which have continuous 1 is of length 3. I have a o(n) approach but can it be done in o(logn) using segment tree and how? I am practicing problems based on segment tree and am curious how to approach this i want to cut down the complexity.

a=[1,1,0,1,1,0,1,1,0,1,1,1,0,1,1,1,1,0]
size=len(a)
counter=0
lis=[]
for _ in range(size):
    if a[_]==1:
        counter+=1
    else:
        lis.append(counter)
        counter=0
print(max(lis))
like image 208
Om Sharma Avatar asked Dec 03 '17 13:12

Om Sharma


People also ask

How do you find the longest sub array?

Approach: The idea is to traverse the array and check that the current element is equal to the previous element or not. If yes then increment the length of the longest subarray by 1. Otherwise, the current longest subarray is equal to 1.

What is the length of longest Subarray that contains up to two distinct integers?

Explanation: Subarrays {1, 1, 2}, {4, 4, 4, 5, 5, 4, 5} and {8, 9} are the only subarray having difference between any two distinct values equal to K( = 1). The longest subarray among them is {4, 4, 4, 5, 5, 4, 5}. Hence, the length is 7.

How many sub arrays are there in an array?

The number of all possible subarrays of an array of size N is N * (N + 1)/2.

How do you find the longest Subarray with the sum of 0?

Algorithm. Declare and Initialize a variable max_length =0, which will store the length of the largest subarray with the sum 0. Start traversing the array from starting index and initialize the variable cur_sum =0 which will store the sum of the subarray starting from the ith index.


2 Answers

In general case, you cannot do better than O(n): let's suppose that we have

[0, 0, 0... 0, 1, 0 ... 0]

all zeros and one 1. In order to distinguish it from all zeroes case you have to find out the only 1 - you have to scan the entire list, since 1's position can be arbitrary.

If you are given an algorithm with better than O(n) time complexity it's easy to create a counter example. Run the algorithm on the all zeroes case. Since the algorithm is better than O(n), it can't check all the items of the list. Change one of these skipped items into 1 and run the algorithm again.

like image 56
Dmitry Bychenko Avatar answered Oct 16 '22 09:10

Dmitry Bychenko


As Dmitry Bychenko points out, you cannot improve on the algorithmic time complexity, but for the case at hand, the usage of some C-optimized utils over a plain Python loop can speed things up:

from itertools import groupby

a = [1,1,0,1,1,0,1,1,0,1,1,1,0,1,1,1,1,0]
m = max(sum(g) for k, g in groupby(a) if k == 1)
like image 4
user2390182 Avatar answered Oct 16 '22 09:10

user2390182